Nannette Thacker ShiningStar.net

ASP.net Web Application Development

Sponsors

News

See all Blog Posts by Nannette.

Nannette Thacker, consultant and owner of Shining Star Services LLC, specializes in development of custom dynamic database driven web applications utilizing ASP.net technologies. Nannette has been developing ASP sites since 1997. Nannette has written numerous articles on web development techniques and tutorials.

Nannette is the owner and developer of ChristianSinglesDating.com.

 Subscribe in a reader





View Nannette  Thacker's profile on LinkedIn

January 2009 - Posts

Attributes.Add: Adding Javascript Click Events Programmatically in Code-Behind

I'm going to demonstrate how to add javascript events programmatically in codebehind using the Attributes.Add method. You may want to add your javascript attributes programmatically so that you can populate the values from a database.

For demonstration purposes, I'm going to add javascript click events to an image. Let's start out with this cute little script contributed by Paul Kurenkunnas that I found on Javascript.Internet.Com (click to see it in action), which enlarges and reduces an image size on click and double-click. This javascript is simple enough that anyone can use it to see Attributes.Add in action.

<img src="waterfall.jpg" width="150" height="200" onclick="this.src='waterfall.jpg';this.height=400;this.width=300" ondblclick="this.src='waterfall.jpg';this.height=200;this.width=150">

Next in our code in front, we place an image control:

<asp:Image ID="Image1" runat="server" />

In the codebehind, we want to programmatically setup everything else. Notice I hard-code in the dimensions and URL, but you could easily retrieve the values from a database table and use them instead. This demo is primarily for the purpose of showing how to use the Attributes.Add and ResolveClientUrl methods:

VB.net:

Image1.ImageUrl = "~/site/images/MyImage.jpg"
Dim imageSrc As String = ResolveClientUrl(Image1.ImageUrl)
Image1.Attributes.Add("onclick", "this.src='" & _
   imageSrc & "';this.height=600;this.width=400")
Image1.Attributes.Add("ondblclick", "this.src='" & _
   imageSrc & "';this.height=300;this.width=200")

C#:


Image1.ImageUrl = "~/site/images/MyImage.jpg"; 
string imageSrc = ResolveClientUrl(Image1.ImageUrl); 
Image1.Attributes.Add("onclick", "this.src='" + imageSrc +
   "';this.height=600;this.width=400"); 
Image1.Attributes.Add("ondblclick", "this.src='" + imageSrc +
   "';this.height=300;this.width=200"); 
 

The code generated within the browser is:

<img id="ctl00_MainBody_Image1"
onclick="this.src='../../../site/images/MyImage.jpg';
this.height=600;this.width=400"
ondblclick="this.src='../../../site/images/MyImage.jpg';
this.height=300;this.width=200"
src="../../../site/images/MyImage.jpg" style="border-width:0px;" /><br />

Notice the image path was originally setup with:

"~/site/images/MyImage.jpg"

We must use the ResolveClientUrl method to obtain a URL that can be used by the browser:

../../../site/images/MyImage.jpg

Just FYI, don't put a height and width for the image or the resizing won't work. 

The Attributes.Add method can be added to numerous controls, such as images, buttons, comboboxes, labels, textboxes, radio buttons, checkboxes and more.

May your dreams be in ASP.NET!

Nannette Thacker


View Nannette  Thacker's profile on LinkedIn
Employers Should Promote Fitness Because Fit Programmers Program Better

Employers should encourage programmers to exercise and be fit, as a recent study found that those who are fit have four times less brain shrinkage than those who aren't. And seriously, that can only help you be a better programmer, right?

A recent Reader's Digest blurb in the Health section tells of an Alzheimer's study.

"A University of Kansas study found that patients who were fit had four times less brain shrinkage (meaning cell death) than those who were out of shape. The benefits of exercise, including changes in growth factors and increased blood vessels and blood flow, may prevent brain cells from dying. Researchers suggest first-time exercisers begin with a 15- to 30- minute walk three times a week." - Reader's Digest pg. 96, December 2008.

Okay, so I stretched it a bit. But yes, I believe in being fit, and I believe in the advantages of proper diet and exercise. Personally, I feel this can be related to everyone's brain and general health.

I think companies should encourage programmers to get outside at least once a day for a 10-15 minute walk. It would clear up the cricks in the necks, allow the mind to relax, and some of those tough problems might even get resolved while walking.

We're told we should take a break from monitors every few hours, to avoid eye strain, so why not take a walk. The cigarette and coffee breaks don't count. And seriously, if management allows all the cigarette and coffee breaks, why don't they encourage exercise breaks? I think the trouble is peer pressure. No one wants to go outside and have people accuse us of goofing off. If management would encourage it, wouldn't that be great!

What do you think?

3 John 1:2 Beloved, I wish above all things that thou mayest prosper and be in health, even as thy soul prospereth.

May your dreams be in ASP.NET and may your Health be Excellent!

Nannette

ASP.NET Web Application Development Consulting

Perhaps there are times when you just need a short-term ASP.NET developer for a 3-6 month project and don't wish to invest in a full-time employee. I am available for 1099 or W-2 consulting. No contract is required.

Check out the details and my current rates, then feel free to contact me with your project details.

Skills include: Professional development of custom database-driven, interactive web sites using:
  • ASP.NET 3.5 SP1 and ASP.NET 2.x using VB.NET with codebehind. C# on several projects.
  • Visual Studio 2008: Web Applications/Projects, Web Forms, Web Services, DLLs.
  • ADO.NET, Entities, Typed Data Sets and Table Adapters.
  • Telerik Controls, CodeSmith generated DAL base classes, Visual Source Safe.
  • MS SQL Server Database 2008, 2005 and 2000, MS SQL query programming and stored procedures.
  • CSS (Cascading Style Sheets), DHTML, Master Pages, Themes.
  • GDI+, VBScript, Javascript.
  • Windows 2008 Web Server and IIS7 and Windows 2000 Web Server and IIS6.
  • XML, HTML, Object-oriented technologies.
  • Image compression and manipulation using Adobe Photoshop and Adobe Illustrator.
  • ASP Classic to ASP.NET Conversions.
  • Self-motivated and able to work independently or on a team with few instructions or follow a detailed plan.
  • Ability to research and easily learn and utilize new web technologies.

Please contact me with your needs. 

Where's the Integrity?

I've said it before, and I'll say it again, "Where is the integrity?"

In "Report Sees Cloud Trend for OSS Developers," Herb Torrens reported "Interestingly, more than 51 percent [of developers surveyed] also admitted to us that they spend time on nonwork-related open source projects while at work."

In "May We Have Your Attention, Please?" Businessweek reports "The average knowledge worker has the attention span of a sparrow. Roughly once every three minutes, typical cubicle dwellers set aside whatever they're doing and start something else—anything else. It could be answering the phone, checking e-mail, responding to an instant message, clicking over to YouTube (GOOG), or posting something amusing on Facebook. Constant interruptions are the Achilles' heel of the information economy in the U.S. These distractions consume as much as 28% of the average U.S. worker's day, including recovery time, and sap productivity to the tune of $650 billion a year, according to Basex, a business research company in New York City."

Whether for a contract or permanent position, when I'm getting paid, that time is my client's. Not my own. As I've said before, would you work as a sales clerk at Wal-mart and take $50 out of the cash register for yourself to keep? That's what you're doing to your employer when you spend personal time on non-work related things. No wonder the cost of developing a website is so much when half of the employees are goofing off.

May dishonesty keep you awake at night and integrity grant you blissful sleep, and when it does....

May your dreams be in ASP.NET!

Nannette Thacker

 

Image Text using GDI+: Creating an Image from Text or Adding Text to an Existing Image

There are some nice tutorials on how to display text as an image. Some examples of when you might wish to use something like this is perhaps if you wish to display your email address on a web page, but don't want it to be harvested by spammers; a CAPTCHA for authenticating a real person on log in, or adding a URL to existing images on your site to keep them from being "swiped" by others.

I'm going to demonstrate the last scenario, a simple method that will print text to the bottom left of an image. You could easily alter it to pass in the x and y coordinates of where you wish to add the text, if desired.

Please download the ImageEdit.zip which contains code for both this example and an example of Resizing ASP.NET Images Using GDI+ Dynamically

Here is what our final image will look like:

In my code-in-front, I have this:

<asp:Image ID="Image1" runat="server" /><br />
<asp:Button ID="Button1" runat="server" Text="Button" />

In the code-behind I make sure to import:

Imports System.Drawing
Imports
System.Drawing.Imaging

You may add this to your Page_Load or a button click event or some method you call:

Dim fileNameFrom As String = Server.MapPath("~/Images/PiperAtComputer.jpg")
Dim fileNameTo As String = Server.MapPath("~/Images/test2.jpg")
TextOnImage(
"Programming Is Fun!", fileNameFrom, fileNameTo)
Image1.ImageUrl = "~/Images/test2.jpg"

From the above, you see that to call our TextOnImage method, pass in a path from your root directory.

Protected Sub TextOnImage(ByVal textString As String, _
ByVal fileNameFrom As String, _
ByVal fileNameTo As String)

Dim Bmp As Drawing.Bitmap = Drawing.Bitmap.FromFile(fileNameFrom)

Using graphicsImage As Graphics = Graphics.FromImage(Bmp)
Dim typeFont As New Font("Arial", 8, FontStyle.Bold)' get height of current image
Dim height As Integer = Bmp.Height
' start string in 2 pixels from left and 15 pixels up from the bottom of the image
Dim leftMargin As Integer = 2
Dim bottomMargin As Integer = height - 15

graphicsImage.DrawString(textString, typeFont, Brushes.WhiteSmoke, leftMargin, bottomMargin)
Bmp.Save(fileNameTo, ImageFormat.Jpeg)

End Using
Bmp.Dispose()

End Sub

Other examples show how to create a new image from text.

Dynamic ASP.NET Text Image (C#) - This shows how to take text and display it as an image. Within this article, a reader posts a message how to do this with a transparent background (VB) which he altered after viewing this code (C#). Another readers shows how to display an image in an image control.

Programmatically add text to an image (C#)

May your dreams be in ASP.NET! 

P.S. Some other imaging urls of interest:

Displaying Dynamically Generated Images (C#) -  I downloaded this zip project and it works with 3.5 framework. The demo zooms and enlarges an image of a pineapple.

Graphics in VB.NET - Articles, Resources, Downloads, Blogs, Book Chapters, Tutorial, Source code

GDI+ & Graphics in C# - Articles, Resources, Downloads, Blogs, Book Chapters, Tutorial and Source code

Getting Started with GDI+ in C# Applications

GDI+ in VB.NET Tutorial for Beginners

Opening and viewing Images and Text files

Image Conversion Utility in C#

Resizing ASP.NET Images Using GDI+ Dynamically

In ASP.NET, you may easily resize images without using a third-party control. Whether reducing or enlarging, or creating a thumbnail image, ASP.NET is your oyster.

I'd like to review a solution by Alex Hildyard and demonstrate his custom ImageResize class in action. I'll provide a zip file for you to download with both my UI layer and Alex's ImageResize class project.

Go Picture Crazy: Resize Images Using GDI+ (C#) provides a tutorial and zip file and shows how to avoid using the GetThumbnailImage method to manipulate the size of an image and instead use the ImageResize class created by author, Alex Hildyard, who explains:

"The problem is, certain kinds of image formats (for example, JPEG) may already include embedded thumbnails, and under these circumstances GetThumbnailImage() just extracts the image's existing thumbnail and scales it to the proportions you specify, rather than generating a new bitmap by resampling the original image. In fact, many digital cameras will generate and embed a thumbnail automatically whenever you take a picture, so that you can quickly browse through any pictures you've taken on the camera itself."

In my example of using his class (VB.NET), we are going to create a proportionate resized image by pixels and save it to a file, and also create a proportionate resized image by percent and save it to an output stream to be used in the "src" tag of an image. Below is an example of our resuts:

 

To use the zip, within your original web project, simply go to File / Add Existing Project, and select the ImageResize.csproj. Using Alex's original zip, I right-clicked the project, selected Properties, and from the Application tab, changed the Target Framework to 3.5. Then in your web project, be sure to add this project to your references.

In my web form aspx page within my web application, I added this to the code-in-front:

<asp:Image ID="Image2" runat="server" /><br />
50 pixels high, saved to a file.<br />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label>
<br />
<br />
<asp:Image ID="Image3" runat="server" /><br />
10 percent high, saved to an output stream.<br />
<asp:Label ID="Label3" runat="server" Text=""></asp:Label>

In the code-behind, I added this:

Imports ImageHelper
Imports System.Drawing.Imaging
Imports System.Drawing

Partial Class _Default
Inherits System.Web.UI.Page Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not Page.IsPostBack Then
LoadImage()
End If

End Sub

Private Sub LoadImage() Dim filepathFrom As String = Server.MapPath("~/Images/DSCF0015.JPG")
Dim filepathTo As String = Server.MapPath("~/Images/test1.JPG")

Dim o As New ImageResize()
o.File = filepathFrom
o.Height = 50
o.UsePercentages =
False
o.GetThumbnail().Save(filepathTo, ImageFormat.Jpeg)
Image2.ImageUrl = "~/images/test1.jpg"
Label1.Text = GetImageValues(filepathFrom)
Label2.Text = GetImageValues(filepathTo)
Image3.ImageUrl =
"ImageResizer.aspx?filepath=" & filepathFrom & "&height=10&usepercent=true"
Label3.Text = "Width: 283 Height: 212"

End Sub

Protected Function GetImageValues(ByVal fileName As String) As String

Dim Bmp As Drawing.Bitmap = Drawing.Bitmap.FromFile(fileName)
Dim labelString As String = String.Empty
Dim height As Integer = Bmp.Height
Dim width As Integer = Bmp.Width
Bmp.Dispose()
labelString =
"Width: " & width.ToString & " Height: " & height.ToString
Return labelString End Function

End Class

In the LoadImages method, put your path to the existing file and path to the new file. If you set UsePercentages to True, 50 will equal 50% of the image height, and if False, 50 will be 50 pixels high.

Notice Image2 is loaded on the page within the codebehind. If you want to embed the resizer within your src url, as done with Image3, simply create another web form, in my example I named it "ImageResizer." Add nothing to the code-in-front, and in the code behind, add this:

Imports ImageHelper
Imports System.Drawing.Imaging

Partial Class ImageResizer
Inherits System.Web.UI.Page

Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
LoadImage()
End Sub

Private Sub LoadImage() Dim filepath As String = Request.QueryString("filepath")
Dim height As String = Request.QueryString("height")
Dim usePercent As String = Request.QueryString("usepercent")

If usePercent = String.Empty Then
usePercent = "false"
End If

If filepath <> String.Empty Then

Dim o As New ImageResize()
o.File = filepath
o.Height =
CInt(height)
o.UsePercentages =
CBool(usePercent)
o.GetThumbnail().Save(Response.OutputStream, ImageFormat.Jpeg)

End If
End Sub End Class

Notice how the dynamic values are added to the query string in the original Image3.ImageURL and retreived in the ImageResizer LoadImage() method:

Image3.ImageUrl = "ImageResizer.aspx?filepath=" & filepathFrom & "&height=10&usepercent=true"

You may download the complete zip file: ImageEdit.zip

The ImageEdit.zip file also contains the source code for Image Text using GDI+: Creating an Image from Text or Adding Text to an Existing Image.

May your dreams be in ASP.NET and your images resized for the web!

Nannette Thacker

Enabling ASP Classic error messages in IIS7 and Windows Web Server 2008

I recently moved my asp classic code from my windows 2000 web server to my windows 2008 web server. But alas, error messages are turned off by default. I got a whole lot of blank pages with grinding hour glasses.

To turn back on the error messages, I found two invaluable posts on the web:

The first post covered about everything I needed:

ASP Detailed Error Messages. From this post, these are the three things that are required for turning on error messages. Most developers will likely already have the first step done.

"Turn off HTTP Friendly Errors in your web browser.
http://support.microsoft.com/kb/294807

To revert back to IIS6- behavior, simply run the following command:
%windir%\system32\inetsrv\appcmd set config -section:asp -scriptErrorSentToBrowser:true

You also have to configure IIS custom-error to allow detailed errors to be sent to remote clients.
%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/httpErrors -errorMode:Detailed (default is DetailedLocalOnly)."

I wanted to see if there was a GUI method of doing the above two commands, and found a screenshot for  scriptErrorSentToBrowser in this second post.

I couldn't find a GUI method of doing the errorMode, and you'll notice that AnilR recommends "Note that you would never want to do the last step on a production server." If anyone knows where this can be setup via the GUI, please let us know.

The second post lists Tips for Classic ASP Developers. Scroll down to the section on "Script errors no longer shown in browser by default." There you'll see screenshots of how to set the "scriptErrorSentToBrowser" setting via the GUI. This second post doesn't mention the "errorMode" but I found that doing the first command without the errorMode command was useless. I had to have the second command before messages were sent to the screen.

You may also wish to look at the next section on preventing errors due to the "Parents paths disabled by default" setting.

I also should mention that you may need to run your commands as Administrator, from this post on "Classic ASP: Security is Painful" we read these steps on running as administrator:

"1) Start an elevated command prompt. Right-click the command shell item in the Start-Accessories menu and select "Run as Administrator".

2) Run the following command: %windir%\system32\inetsrv\appcmd set config -section:asp -scriptErrorSentToBrowser:true"

May your dreams be in ASP.NET and your classic applications magically converted to .NET while you sleep,

Nannette Thacker

 

Setting Maximum Failures: Windows 2008 and IIS7 Application Pool Stopped

In IIS7, when your application pool errors so many times, it will automatically stop the application pool, thus taking your web application off line.

Service Unavailable


HTTP Error 503. The service is unavailable.

In your system events log, you will also have an error:

'A process serving application pool 'Pool Name' terminated unexpectedly...' 

To restart it, go to the application pool in IIS7 and select the stopped pool and restart it. 

This can be a real nuisance when you're debugging code and getting a lot of errors. To change the number of allowed failures, go to the application pool for the website you are working on in IIS7. Select it in the application pool list. Select "Advanced Settings" from the Actions panel on the right. Scroll down to Maximum Failures and change the number to a larger number. Mine was 5 by default and below I changed it to 50.

Then when you're done debugging/developing, change it back to a lower number as desired. 

This is great because you can create a pool for different applications and only increase this setting on the application that you're working on that is causing the failures. So be sure to assign your "buggy" application to its own pool, rather than having it share a pool with your "behaved" applications.

May your dreams be in ASP.NET!

Nannette Thacker

 

More Posts