Skip to main content
Select a theme:
   
RSS Feed

Microsoft Expression Interactive Designer (Sparkle) CTP Is Available

I have been waiting for this to be released for a very long time. This is a true designer for building XAML applications and it makes it incredibly easy to build nice looking applications very quickly. If you have installed the Windows SDK and what not, I highly recommend you download this tool and give it a try.

Microsoft Expression Interactive Designer

Updated Hand-On-Labs for WPF (Avalon)

I have probably learned the most about XAML and the Windows Presentation Foundation (WPF formerly Avalon) by going through the Hands-On-Labs. Most of these originated at the PDC from last year. Any how, they are a great way to get familiar with XAML and they were much needed since the schema for XAML has changed significantly since these were originally released. If you have an interest in learning XAML (and you should), I recommend you check them out.

WPF Hands-On-Labs

Obsolete API List (Again)

I have already posted a few times on obsolete API calls in .NET 2.0, but I stumbled upon another list that is easier to read. In the past you had to kind of dig through a compiled help file and it wasn't really convenient to look through.

Obsolete API List: By Namespace

Obsolete API List: By Assembly

VB Code Snippets Now Available in C#

A while back I posted about how some of the better code snippets are only available for VB. Although, that was all perfectly fine for Marcus, the rest of us couldn't take advantage of these handy chunks of code. Well, Microsoft went ahead and ported all of them over to C#, so now you can take advantage of them when using C#.

There are now snippets available in the following categories. There are code snippets here to do common things such as read text from a file or ping a computer. A lot of them are pretty handy, so be sure and check them out to save yourself on some code.

  • Application Code Snippets
  • Collections and Arrays Code Snippets
  • Connectivity Code Snippets
  • Crystal Reports Code Snippets
  • Database Code Snippets
  • Datatypes Code Snippets
  • File System Code Snippets
  • Math Code Snippets
  • Operating System Code Snippets
  • Security Code Snippets
  • Smart Devices Code Snippets
  • Windows Forms Code Snippets
  • XML Code Snippets

Be sure and click on the link after the group of snippets labeled click here to download all of them at once. It is a total pain in the ass to do each group seperately and I couldn't get it to work right anyway. You can find them at the URL below. Lastly after you get the snippets installed, you will have to go to the Code Snippet Manager (Ctrl+K, Ctrl+B) and add the folder where it installed them which is typically C:\Documents and Settings\<username>\My Documents\MSDN\Visual C# 2005 Code Snippets\

C# Code Snippets

Encrypted Web.Config sections after deployment

A while back I posted about using aspnet_regiis to encrypt a section of a web.config. When trying this on a local machine, you will probably find that it works great. However, after deploying it I found a couple of things to look out for. First, is of course, make sure that the machine.config has a machineKey specified and it is the same across machines (including the original machine you did the encrpytion on).

I had already done that but when I tried to access the data, I found that I got the error "Failed to decrypt using provider 'RsaProtectedConfigurationProvider'.". This is because the network service account does not have access to the keytore by default, so you have to go and grant it on each target server. To do that run the command below.

aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT Authority\Network Service"

The Network Service account is the account asp.net typically runs under on Windows Server 2003. You would have to change this if you are running on Windows 2000.

After running this you shouldn't have any problem using an encrypted configuration section. If you need more help, refer to the article below from Microsoft.

How To: Encrypt Configuration Sections

Getting the DataFormatString to work with a GridView

Sooner or later you will probably use a GridView to do some simple data binding. The GridView is great because once you set up your SqlDataSource or ObjectDataSource (or whatever), it automatically detects the schema of your table. This is great because it allows you to databinding really easily.

There are also a number of features that let you format the data you have without writing in code. One such propery is the DataFormatString property. This property is useful for formating numbers or dates. If you are trying to format a date however, you may notice that the string you are providing is not doing anything. It took me a while to figure this out but basically this is because of HTML Encoding. In the example below, I have a data format string of {0:MM/dd/yyyy} to format my date. By default, the HtmlEncode property is set to true. To get your DataFormatString simply change it to false as shown in the image below.

Data Format String

ASP.NET Controls and Accessibility

I was stumbling around looking at the documentation and I stumbled upon this information in the help by accident. Basicaly, it tells you what controls you might run into issues with in trying to meet accessibility guidelines.

ASP.NET Controls and Accessibility

Free Training CD From AppDev

Puffy was always a big fan of these training CDs. Well now they are offering various titles for free. Here are some of the titles being offered.

  • Exploring Visual C# 2005
  • Exploring Visual Basic 2005 (Marcus probably already has this one)
  • ASP.NET using Visual C# 2005
  • Exploring SQL Server 2005

Free Training CD from AppDev

Regular Expression Editor for RegularExpressionValidator Control

I was building a new form and was adding validation and I found a nice surprise. When in design mode, if you click on the ... box next to the ValidationExpression, you are prompted with the following dialog.

Regular Expression Editor

This editor has all the common regular expressions you might need such as E-mail Address, URL, Phone Number, and Postal Code. Who needs Marcus any more, this has almost everything you need?

Specifying a Master Page globally

Just like you can specify referneces to controls, globally, you can also use the pages element to specify a default master page so that you don't have to specify it on every page.

<configuration>
  <system.web>
    <pages masterPageFile="~/MasterPage.master" />
  </system.web>
</configuration>

ROW_NUMBER() Function will revolutionize data paging

One feature not talked about very much until recently in SQL Server is the ROW_NUMBER() function. This function returns a sequential mnumber for each row returned in a resultset. With this row number you can implement data paging relatively easy. It's still somewhat complicated to understand how the basic parts work, but a query like the one will work as a good tempalte.

CREATE PROCEDRUE dbo.MyStoredProcedure
    @PageIndex int,
    @PageSize int
AS
BEGIN
  WITH TemporaryView AS {
  SELECT ROW_NUMBER() OVER (ORDER BY AnyColumn)
  AS Row, Column1, Column2 FROM TableName)

  SELECT Column1, Column2 FROM TemporaryView
  WHERE Row between
  (@PageIndex - 1) & @PageSize + 1 and @PageIndex * @PageSize
END

I want to point out the use of the WITH statement above. There is something new in SQL Server 2005 called Common Table Expressions (CTE). These effectively let you dynamically create a virtual view. So what the fire statement does is assigns a row number to everything in the table and creates a virtual view that the next statement can select from. Although ASP.NET 2.0 has built in paging features with the GridView, etc. It is not suitable for large amounts of data because all of the paging is done on the web server. This method of writing a stored procedure will probably become a best practice for paging with large amounts of data because it only grabs the rows it needs at the SQL Server level.

WinFX December CTP Released

I am getting where I can't keep up with these CTPs. Anyhow, this version is getting closer and closer to beta. In fact, they now have go-live licenses now for Windows Communication Foundation and Windows Workflow Foundation (nothing for Windows Presentation Foundation yet unfortunately). The other key thing it adds is that the "Cider" XAML designer has now been integrated into Visual Studio. This is basically the same designer that will be using in Microsoft Sparkle so it should be a lot easier to do XAML applications.

As usual, you need to uninstall any previous versions first. This page has a link to everything that you need.

WinFX January CTP

Use XslCompiledTransform Now!

If you are using a lot of XSL Transformations and have migrated to ASP.NET 2.0, then there are some significant preformance gains to be had by making a few simple code changes. The XslTransform class is now considered obsolete and has been replaced with XslCompiledTransform. This class on averages performs transformations four times faster than XslTransform. Basically it is supposed to be on par to using MSXML 4.0 directly.

It's syntax is roughly the same as using XslTransform. Unless you are using some of the more obscure parameters with XslTransform, you can pretty much do a straight refactor nad it should compile and work. If XSL performance has ever been an issue, I recommend making the change as soon as possible.

The link below contains detailed information on it from Microsoft's XML Team.

XslCompiledTransform

Global Namespace Qualifier

Although creating a class outside of a namespace is probably considered bad form, in .NET 2.0 there is actually a way to access it.

namespace Blah
{
  class Class1
  {
    public void MyMethod()
    {
       // reference using the global keyword
       global::Class2 myClass2 = new global::Class2();
       myClass2.MyMethod();
    }
  }
}

public class Class2
{
  public void MyMethod()
  {
    // do something
  }
}

You will notice that Class2 is not included in the namespace of blah. Before, it would be rather difficult to make a call to that class. It might not have even compiled, I am not sure. Well, now with the use of global::, you are able to make a call to that class.

I have more included this information, not because you will use it, but in case you run into it some place in the future.

Also if you are wondering where else you have seen global::, it is also used in the reference.cs of web services inside class libraries.

global:: used in Web Service Proxies

Finding a duplicate key when importing data

This isn't really .NET 2.0 related or anything, but I still think it might be useful. I don't know how many times I have been charged with a task of importing data from a text file or from an access database or whatever and I ran into an issue where the supposed primary keys have duplicate rows in them. Well, with the aid of google, I found a relatively easy way to find the duplicates using the HAVING SQL clause.

The query below, will spit out the values committing the offense against the primary key. You may need to import your data to a temp table in SQL first without a key set. It will also work directly in Access.

SELECT COUNT(*), PrimaryKeyColumn
FROM TableName
GROUP BY PrimaryKeyColumn
HAVING Count(*) > 1

That's all there is to it. If you have a compound primary key, you can find it in a similar way.

SELECT COUNT(*), PrimaryKeyColumn1, PriamryKeyColumn2
FROM TableName
GROUP BY PrimaryKeyColumn1, PrimaryKeyColumn2
HAVING Count(*) > 1

That's not .NET related, but I hope it helps you out someday.

Screen Dumps Made Easy with DrawToBitmap

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.

Attend a Virtual Lab and win a Pocket PC

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.

About This Site

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

VS2003 Style Web Application Projects

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

BONUS TIP!!! Using aspnet_regiis.exe to encrypt the Web.Config

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.

Using the JScript Convert class to safely convert types

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.

Creating your own code snippets with the Code Snippet Manager

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.

System.Net.Mail

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

NOTE: This site is migrating to DotNetMafia. For the latest tips on Visual Studio 2008, SharePoint, and MOSS, see Corey's .NET Tip of the Day.