September 2005 - Posts
Ask any ASP developer who has ever tried to dynamically create his own images and he'll tell you it's a nightmare. In fact, it's more than a nightmare. It's practically hell. The only true solution? Reverting to an expensive, dodgy, third-party control to do the work for you.
With ASP.NET however, you can develop your own dynamic images with ease. Simply create an image object and use the new GDI+ features to add objects to that image, such as text, rectangles, and ellipses. After that, you can simply stream straight back down to the client.
However, covering the graphics features in depth would require at least another two books—and unfortunately, we don't have that much room. So, I'm going to share a sample that demonstrates creating a small 'Empty Karl's Basket' button, alongside a little blue and yellow bullet point. It's the sort of personalized graphic you'll find on sites such as Amazon.com.
Just add the following code to the Page Load event of a Web form. That Web form will then feed back this image as its output. In other words, your Web browser will recognize the page as a graphic. That means if you wanted to reference the image in an Image control, say, you'd specify the source (the ImageUrl) as being YourWebFormName.aspx.
Here's the code:
' Create image - you could even load an image
' from a file and edit it in code
Dim objBitmap As Bitmap = New Bitmap(120, 30)
Dim objGraphics As Graphics = Graphics.FromImage(objBitmap)
' Fill background
objGraphics.FillRectangle(New SolidBrush(Color.LightBlue), _
0, 0, 120, 30)
' Create blue-yellow bullet point
objGraphics.FillEllipse(New SolidBrush(Color.Blue), 3, 9, 10, 10)
objGraphics.FillEllipse(New SolidBrush(Color.Yellow), 4, 10, 8, 8)
' Draw text next to bullet point
objGraphics.DrawString("Empty Karl's Basket", _
New Font("Tahoma", 8), New SolidBrush(Color.Green), 16, 8)
' Send down to client
Response.Clear
Response.ContentType = "image/jpeg"
objBitmap.Save(Response.OutputStream, _
System.Drawing.Imaging.ImageFormat.Jpeg)
' Tidy up
objGraphics.Dispose()
objBitmap.Dispose()
At its very least, this code demonstrates passing images back down to your browser via a Web page. Now, all you need to do is brush up on your GDI+ skills—and the dynamic image generation world is your oyster. For more information and a series of tutorials, use the Help Index to look up 'images, GDI+'.
In the golden, olden days of ASP, managing a file upload was pretty difficult. Most developers reverted to digging deep in their wallets to purchase a third-party add-on to help them achieve the desired result. No longer.
Thanks to the new ASP.NET features, you now can upload files with practically a few lines of code. And the following five, easy-to-follow steps show you exactly how to do it:
- Add a File Field control to your form. You'll find this under the HTML tab on the Toolbox. You'll have seen this control when uploading attachments through Hotmail, or when contributing files to a Web site.
- Right-click the File Field control and check the "Run as Server Control" option. This allows you to manipulate the control in code, sort of like a lesser-functional ASP.NET server control.
- Change the ID of your File Field control to something more understandable, such as "fileUpload".
- Enter the HTML view of your Web form and find the opening <form> tag. You'll need to edit this to add the parameter encType="multipart/form-data". Your <form> tag may look something like this when you're finished:
<form id="Form1" method="post" encType="multipart/form-data" _
runat="server">
And that's it—you've set up your form to receive file uploads. But, after the user has selected a file and submitted your form, how do you manipulate the sent file? The easiest technique is to run a simple line of code, like this:
NameOfFileFieldElement.PostedFile.SaveAs("c:\temp\testfile.txt")
Pretty simple, really. You might also want to check whether the user has uploaded a valid file first, before saving—unless you're really into errors. The following function does this for you, checking for null uploads and zero byte files:
Public Function FileFieldSelected(ByVal FileField As _
System.Web.UI.HtmlControls.HtmlInputFile) As Boolean
' Returns a True if the passed
' FileField has had a user post a file
Dim intFileLength As Integer
If FileField.PostedFile Is Nothing Then Return False
If FileField.PostedFile.ContentLength = 0 Then Return False
Return True
End Function
Top Tip: If you get an access denied error when trying to save files directly to your Web application folder, go check your permissions. Ensure that your virtual directory in IIS has read and write permissions (change this through IIS). You may also want to ensure your ASPNET, Guest, or impersonated accounts have appropriate permissions, both for computer access and for the actual folder itself (right-click the folder, select 'Sharing and Security', then select the 'Security' tab).
The problem is that both you and I know that 95% of people reading this don't really want to go ahead and store files directly on the server file system. Rather, you want to go saving information into your database, into that SQL Server 'image' field.
Every article I've seen so far manages to conveniently skip this topic. And so does this one. But my book—VB.NET and ASP.NET Secrets—contains ready-to-run functions that handle this for you 100% automatically. If you're interested, check it out!
Smart Navigation is a little-known Internet Explorer feature that enables the individual controls on your Web forms to maintain focus between post backs, plus allows you to suppress that "flicker" that occurs as you load the new page.
To turn on this little-known feature, simply set the SmartNavigation property of your ASPX page to True. Note that Smart Navigation only works on Internet Explorer 5 and above; however, the .NET Framework will automatically detect this and only serve up the "smart" code if the target browser supports it.
This is one of those little code snippets you can pull your hair out trying to find. And no help file nor book I've come across actually gives reference to it. So, surely it can't be that important?
Imagine you've created an ASP.NET Web page with a search button. The user taps a phrase into a text box and presses Enter. On most regular Web pages (think: Google), the form would be submitted and the results returned. In other words, the search button is automatically "clicked" for you.
However on an ASP.NET Web page, pressing Enter resubmits the form to the server, but actually does nothing... which is pretty useless, really.
So, how do you set a default button to be clicked when the user presses Enter? Simply add the following line to your page's Load event, replacing "btnSearch" with the name of your button. It uses a hidden Page method called RegisterHiddenField and works splendidly:
Page.RegisterHiddenField("__EVENTTARGET", "btnSearch")