January 2006 - Posts

In Windows Form 2.0, they have made it easier to do a screen dump of a Windows Form. Now, just about any control along with anything that inherits from Form has a DrawToBitmap method. This method allows you to easily save a copy of what is on the current form to an image.

// declare a new bitmap
Bitmap myBitmap = new Bitmap(this.Width, this.Height);

// get the bitmap
this.DrawToBitmap(myBitmap, this.ClientRectangle);

// save the bitmap
myBitmap.Save("c:\screendump.bmp");

Screendump, huh huh. Ok, basically this code is pretty simple. You create a bitmap that set to the width and height of the form. In this case the use of this is assuming that you are executing it from some method inside of a form class somewhere. The DrawToBitmap method grabs the bitmap and then you just save it do disk or whatever.

There are a few things to note about it, it doesn't work with Ink controls for Tablet PCs (not like any of you are doing that). It also doesn't work quite right with the RichTextBox (it only shows the border). Lastly, it doesn't work with ActiveX controls.

As I have mentioned before, Virtual Labs are a great way to try out new features in Visual Studio without installing the product on your own machine. They are a great way to walk you through tasks and get some real hand-on experience. Anyhow, now as a bonus, if you try a virtual lab and submit and evaluation, you could win a Pocket PC.

Go give it a try at the link below.

Virtual Labs

As an update, I tried to do one of the labs this morning and it said the credentials to login were in the lab manual but they were not. Maybe it was just a problem with that lab's documentation, I am not sure.

If you have played with any of the ASP.NET design templates that I have posted on earlier, you will probably have noticed that this site uses one of those. This has worked well for me in the fact that I have absolutely no graphic design skills whatsoever. On top of that an added benefit is that the design templates are built with XHTML and CSS. This site for the most part will usually validate unless I happen to screw it up. Since all of my older content came from SharePoint, I have had to fix each entry manually to make it comply. Unfortunately, I have only made it through the most recent 100 entries or so.

This site uses a Jello Mold as described on PositionIsEverything.net. I have found that it works pretty well, but there are a few issues in Internet Explorer that will cause the site to mess up. The Jello Mold attempts to set a minimum width via a hack, but it doesn't completly work. That is why if you make the browser to narrow, the content will jump to the bottom. The other issue I have is when using the pre tag, if the content is too long, it will also cause the content to jump to the bottom. Firefox handles this fine, but it doesn't necessarily look good either.

Again, if you are interested in design templates, look at my past postings at the link below.

Design Templates

Ok, well if you hated the new web project system in ASP.NET 2.0, you will be glad to know that they now have in beta (well its been out for quite some time), something called a Web Application Project which is very similar to what they had in Visual Studio 2003.

The biggest benefit to this is that you actually have a default namespace and you can set properties on the web project just like you could in Visual Studio 2003. However there are a number of cons. The .csproj file is back, so you are back to dealing with crap when someone has it checked out.

Secondly, you lost all benefits of the partial class system. Normally in ASP.NET 2.0, when you drop a control or whatever onto an .aspx page you don't have to have it declared anywhere. Well now, since this is like VS2003, it will put the declaration in PageName.aspx.designer.cs (very similar to windows forms). This is in fact very lame. On top of that this beta preview doesn't do that for you, so you have to do it manually (even more lame).

The only other benefit that the ASP.NET team claims is that it could make the migration process easier. I'm not sure, maybe it will. The last thing to note is that it compiles all files into a single DLL. So in my opinion by using this, you are losing a lot of the key beneifts of upgrading to ASP.NET 2.0.

If you still want to check it out, you can find it at the link below.

Web Application Project

I posted on this quite some time ago, but I thought I would post on it again since it is relatively easy to do and it is a great way to protect your connection strings and what not. If you are wondering, yes I do get lots of ideas for posts from other people's blogs, but since I know most of the people that read this are not the scan Microsoft blog type of people, I provide it here for you.

For example if you wanted to encrypt the connectionStrings element of your web.config, simply type the following.

aspnet_regiis.exe -pef connectionStrings

Note you must be in the same directory or specify the path to the physical directory. You can use -pe and specify the -app parameter to specify a virtual path if you prefer.

To decrypt the section, simply use the -pdf parameter instead.

aspnet_regiis -pdf connectionStrings

Remember it is not necessary to do anything in your code to decrypt the data. ASP.NET will handle it automatically when you retrieve a value from it using the ConfigurationManager object.

This is nothing new to ASP.NET 2.0, but Scott mentioned its uses in one of his blog posts briefly. Take a look at the statement below.

int id = int32.Parse(Request.QueryString["Id"]);

If you have written anything like this before, you know that if Request.QueryString returns null, you are going to have a bad time. This is why in the past, I had created the WebConfiguration class to safely get these values without throwing an exception. Typically, you would have to write something like the sample below. Of course that still didn't prevent an exception from occuring if an int wasn't passed.

int id;
if (Request.QueryString["Id"] != null)
    id = int32.Parse(Request.QueryString["Id"];

Microsoft.JScript has long had a class called Convert with methods such as ToIn32(), ToDateTime(), etc. The nice thing about using ToInt32 for example is that if the value is null, it won't thrown an exception it will just return 0.

Now you can replace the above expression with something like this.

int id = Convert.ToInt32(Request.QueryString["Id"]);

It's a simple tip but maybe you will find it useful at some point.

I am finally getting settled into my new job, so I should be posting more reguarly now. Since, the Tip of the Day is on a real web server now, I can actually make posts that contain images (how exciting).

Today's topic is on the Code Snippet Manager. The Code Snippet manager provides support for configuring code expansions. You probably have heard about code expansion by now, but maybe not. Basically, they allow you to automate routine things in code such as creating a property, or a try/catch block. The most common one you heard of is the prop expansion. Simply type prop and hit tab and it will expand to include a private variable declaration and the property that reads and writes to it. You can then tab through and set the private variable name and the property name. It will automatically update the relavent spots in the property when you change the private variable's name.

So that's cool, but if what if you want to make your own? Well it's pretty easy. The Code Snippets folder in your Document and Settings\<username>\My Documents\Visual Studio\Code Snippets folder will let you add your own. There are divided into a number of categories such as VB, VC#, J#, Office, and XML. If you want to configure a snippet manually, simply copy it into the appropriate directory.

Of course, there is an easier way to do it. The Code Snippet Manager makes it easy to add your own snippets and manage them. It will even let you search online for new ones. To get to the Code Snippets Manager, go to the Tools menu and click on Code Snippets Manager. Some installations and some projects do not have this in there by default, so if you don't see it, you will have to reconfigure your toolbars or you can try hitting Ctrl + K, Ctrl + B.

When you open the manager, you will notice there is about a billion snippets for Visual Basic that let you do some pretty advanced things such as SQL queries and copying files. Nice if you are like Marcus and love VB, but no good for C#. There are still some handy snippets that you can make use of though. Once you have it open you can click the Import button and import a custom snippet into your collection.

Code Snippet Manager

Now, if you are actually still reading this, you might be wondering exactly, how you create the snippet itself. Snippet files are actually just XML, so the easiet way to create your own is to copy an existing one such as prop. The builtin snippets can be found in the C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C# folder. Here is an example.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  
xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
 <CodeSnippet Format="1.0.0">
 <Header>
   <Title>ErrorKey Test</Title>
     <Shortcut>errorkeytest</Shortcut>
     <Description>Code snippet for creating an Erorr Key Test</Description>
     <Author>Microsoft Corporation</Author>
     <SnippetTypes>
     <SnippetType>Expansion</SnippetType>
	</SnippetTypes>
     </Header>
     <Snippet>
	<Declarations>
		<Literal>
			<ID>rule</ID>
			<ToolTip>Rule Name</ToolTip>
			<Default>errorRule1</Default>
		</Literal>
		<Literal>
			<ID>request</ID>
			<ToolTip>Request Name</ToolTip>
			<Default>request1</Default>
		</Literal>
	</Declarations>
	<Code Language="csharp">
  <![CDATA[if ((this.Context.ValidationLevel >= 
Microsoft.VisualStudio.TestTools.WebTesting.ValidationLevel.High))
	{
		ValidationRuleFindText $rule$ = new ValidationRuleFindText();
		$rule$.FindText = "ErrorKey";
		$rule$.IgnoreCase = true;
		$rule$.UseRegularExpression = false;
		$rule$.PassIfTextFound = false;
		$request$.ValidateResponse += 
new EventHandler<ValidationEventArgs>($rule$.Validate);
	}$end$]]>
        </Code>
     </Snippet>
   </CodeSnippet>
</CodeSnippets>

Some of the elemnts are obvious, I'll point out the function of some of the key ones. The Shortcut element specified the key sequence to type to expand the code snippet in the editor. I believe this has to be unique. The SnippetType is used to specify that the snippet is a code expansion (refactoring can also be done in this manner but I have not tried it). The Literal element in the Declarations section specifies the user replacable values. So after this expansion is expanded, the expansion will prompt for a value for rule and replace everything in the code element that has $rule$ in it with whatever the user typed in. Lastly, the code element specifies the actual code to expand. Just make sure to include it in a CDATA.

Code snippets are extremely useful and people are providing more and more of them. Just click on the Search Online link the Code Snippet Manager to see for yourself.

As I mentioned many times in the past, the old SmtpMail message objects in the System.Web namespace have been marked obsolete in ASP.NET 2.0. I have found a great site that will tell you everything you need to know about the mail object. Now, if you want to send e-mail, you should use the SmtpMail class in System.Net. This new class makes it a lot easier to do attachments and send multi-part messages.

Here is a simple example of sending out a message (remmeber to include System.Net)

//create the mail message
MailMessage mail = new MailMessage();

//set the addresses
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");

//set the content
mail.Subject = "This is an email";
mail.Body = "this is a sample body";

//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(mail);

Do you want to send out an HTML E-mail instead? That is simple, simply just set the IsBodyHtml property to true.

Sending out multi-part e-mails is pretty easy as well. Simply create new AlternateView objects and add them to the AlternateViews collection of the SmtpMail object as shown in the example below.

//create the mail message
MailMessage mail = new MailMessage();

//set the addresses
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");

//set the content
mail.Subject = "This is an email";

//first we create the Plain Text part
AlternateView plainView = 
AlternateView.CreateAlternateViewFromString("This is my 
plain text content, viewable by those clients that don't 
support html", null, "text/plain");
//then we create the Html part
AlternateView htmlView = 
AlternateView.CreateAlternateViewFromString("this is 
bold text, and viewable by those mail clients that support 
html", null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);

//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1"); 
//specify the mail server address
smtp.Send(mail);

There are a ton more examples and lots of additional information at this site below.

System.Net.Mail

More Posts « Previous page