Welcome to the second part of ASP.NET Secrets!
I’m Karl Moore and in this article, we’ll be exploring a bundle of further .NET tricks to really put the shine on your Web applications. Today, we’ll figure out:
- Three Steps to Changing Your Page Title in Code!
- How to Send Mail in ASP.NET
- The Secret to Uploading Files with Ease
- How to Dynamically Create Images
Ready to get stuck into .NET code?
Three Steps to Changing Your Page Title in Code!
If I asked you to change the title of your Web form, you’d be forgiven for looking for a “title” or “text” property somewhere. The problem is, that mysterious property doesn’t exist: Microsoft forgot to put it in. If you want to change your page title programmatically, you have to do it yourself. Here’s how.
Firstly, switch to the HTML view on your Web form. Near the top of your page, you’ll see the title tag, looking something like <title>WebForm1</title>. Replace this with <title runat=”server” id=”PageTitle”></title>. Here, you’re creating a title tag that runs on the server and has an ID, meaning you can manipulate it in code.
Next, switch back to design mode; then, open up the code window behind your form. At the top of your page, under the Inherits line, add the following line of code. This declares the server title tag you’ve just added:
Protected PageTitle _ As System.Web.UI.HtmlControls.HtmlGenericControl
Our third and final step involves changing the page text. Behind the Load event of your page, or in response to some similar event, set the InnerText property of the PageTitle tag to your new page title. Here’s my sample code:
PageTitle.InnerText = "Welcome! - Last Updated 20/05/2003"
And that’s it—one line of code and your page title has changed. Hey, presto!
How to Send Mail in ASP.NET
Sending mail from a Web page is perhaps one of the most commonly requested code snippets. And to make your life easier, here’s a function that encapsulates all the functionality for you. Simply call it, passing in the appropriate arguments, and you’re sorted:
Public Function SendMail(ByVal [To] As String, _ ByVal From As String, ByVal Subject As String, _ ByVal Body As String, ByVal IsHTML As Boolean, _ Optional ByVal SmtpServer As String = "domain.com") As Boolean ' Sends a mail message using the specified details ' - returns a False if delivery fails Try Dim objMsg As New System.Web.Mail.MailMessage() SendMail = True With objMsg .To = [To] .From = From .Subject = Subject .Body = Body ' .BodyFormat specifies whether the Body is ' in plain text or HTML format .BodyFormat = IIf(IsHTML = True, _ System.Web.Mail.MailFormat.Html, _ System.Web.Mail.MailFormat.Text) End With System.Web.Mail.SmtpMail.SmtpServer = SmtpServer System.Web.Mail.SmtpMail.Send(objMsg) Catch SendMail = False End Try End Function
In our function here, we’re setting the SMTP server to a default—domain.com, at present. You’ll need to change this to the address of your host SMTP server for the code to work.
The Secrets to Uploading Files with Ease
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:
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!
Caption: Click the button and pick a file!
How to Dynamically Create Images
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+’.
Caption: The result of our code: hey, it’s my shopping basket. Apparently.
Coming Up in Part Three of ASP.NET Secrets:
- Four Steps to ASP.NET Authentication
- How to Authenticate Just Part of your Site
- The Best Place to Store your Settings
- Steal Fantastic Forum Code from Microsoft and Save Yourself Hours!
See you next time!
And if you want to read more, you’ll have to check out my new book, Ultimate VB .NET and ASP.NET Code Book, which contains full versions of all the secrets I’m covering in this series, plus much, much, much more.
# # #