Archive

Archive for the ‘ASP.Net’ Category

Localizing a SharePoint UI using ASP.Net Resource Files

August 5, 2009 Lee Dale 1 comment

I have a requirement for a project I’m working on to make all strings in the UI of a SharePoint 2007 site localized. The problem was that the rest of the site collection needed to stay in English, this meant all the system and admin pages needed to stay in English while all the user interface needed to be localized. The requirement also stated that an admin of the site collection could change this is the admin pages.

I immediately turned to ASP.Net resource files as this would achieve exactly what I wanted, I wanted to use the Regional Settings -> Locale setting in the site collection to determine the locale to show. The problem with this was that changing the sites Regional Settings Locale had no effect on the CurrentUICulture that the current ASP.Net thread was running under, this meant that ASP.Net would load the resource file for the user’s browser not the resource file for the locale of the site collection.

I used the following blog post from Mikhail Dikov which is a good example of how to use ASP.Net resource files in a SharePoint site. The blog post fails to mention however that for the culture to change within a SharePoint site you need the language packs installed and this would affect the whole site collection, admin pages and all.

So the following is an outline of how I achieved my goal:

  • First I created a default resource file which contained all the English strings and then resource files for each locale I wanted to support.
  • Next I deployed these resource files into my SharePoint web applications App_GlobalResources folder (see Mikhail’s blog post on how to deploy your resource files using a SharePoint feature).
  • I then added the following code to my page layout which changed the current ASP.Net threads UI culture to the same culture of the SharePoint site collection:

<script runat=”server”>
protected
override void InitializeCulture()

{

System.Threading.Thread.CurrentThread.CurrentUICulture = Microsoft.SharePoint.SPContext.Current.Web.Locale;
base
.InitializeCulture();

}

</
script>

This made sure that each time the page loads the ASP.Net culture was set to the correct site collection culture.

  • Now that the correct ASP.Net culture is selected in the page we can go ahead and localize our strings in the page layout like this:

    <asp:Literal runat=”server” Text=”<%$Resources:MyResourceFile,MyLocalizedStringKey %> />

    Note that we can also just use <%$Resources:MyResourceFile,MyLocalizedStringKey%>in any ASP.Net web controls property if you don’t want to use a Literal control.

And that’s all there is to it, I think it’s a clean and simple way to localize the SharePoint UI without using language packs and localizing the whole site collection including admin and system pages.

Categories: .Net, ASP.Net, C#, SharePoint

Web.config Transformations with Visual Studio 2010

February 27, 2009 Lee Dale Leave a comment

When deploying a web application across your organizations hosting environments you need to make sure you make the correct modifications to your web.config on each environment. Currently with Visual Studio 2008 this means hand modifying each web.config to make connection strings point to the right database servers, changing the debug compilation attribute to false etc. Doing this for each deployment can be a major pain and can allow bugs to slip into your environments, for instance you may forget to modify your connection string and have your production application pointing to your staging server or have your application underperform because you have left debug compilation on.

Thankfully the Visual Studio team has come up with a great feature to be included in the next release of the IDE that allows you to keep a copy of transformations for each web.config. Your transformations will get applied to your main web.config when the application is deployed to each environment. This should greatly improve the deployment experience and help keep deployment errors down to a minimum.

Channel9 have a video all about it so head over to there and check it out.

http://channel9.msdn.com/shows/10-4/10-4-Episode-10-Making-Web-Deployment-Easier/

Categories: .Net, ASP.Net, Visual Studio Tags: ,

New website: www.moggymart.com

February 3, 2009 Lee Dale Leave a comment

A while back I decided to build a website for allowing people to post free classified advertisements for pets and animals; I decided to use ASP.Net 2.0 with AJAX Extensions and SQL Server 2005. User registration and authentication was done using the ASP.Net Forms Based Authentication with SQL Server Membership Providers.

As normally happens with side projects I gave up on it because I was too busy with my day to day projects and never touch it for a long while. Lately I picked it up again and decided to at least finish what I started so the first release looks like this www.moggymart.com

I plan to add more features when I get time and would be grateful for any feedback on the site.

Book review: Professional SharePoint 2007 Development

December 31, 2008 Lee Dale 1 comment

I will be frequently reviewing books on my blog from now on and I would like to start with a good wholesome SharePoint (MOSS 2007) development book entitled Professional SharePoint 2007 Development.

The book is written by some very knowledgeable SharePoint guys who have a vast amount of experience developing on the SharePoint platform. The book provides a good programmer to programmer learning experience from real world professionals who have been developing SharePoint solutions out in the wild for a number of years.

The authors of the book are: John Holiday, John Alexander, Jeff Julian, Eli Robillard, Brendon Schwartz, Matt Ranlett, J. Dan Attis, Adam Buenz and Tom Rizzo.

It’s a fairly large book some 716 pages long packed full of good solid SharePoint development techniques and good examples to guide you along the way.

The table of contents looks like this:

  • Chapter 1 – The Microsoft Application Platform and SharePoint
  • Chapter 2 – MOSS 2007 Overview for Developers
  • Chapter 3 – The SharePoint User Experience
  • Chapter 4 – WSS v3 Platform Services
  • Chapter 5 – Programming Windows SharePoint Services
  • Chapter 6 – A Sample Collaboration Solution
  • Chapter 7 – RSS, Blogs, and Wikis
  • Chapter 8 – Building Personalized Solutions
  • Chapter 9 – Using Enterprise Search
  • Chapter 10 – Using the Business Data Catalog
  • Chapter 11 – Building Document Management Solutions
  • Chapter 12 – Building Records Management Solutions
  • Chapter 13 – Building Web Content Management Solutions
  • Chapter 14 – Electronic Forms in MOSS 2007
  • Chapter 15 – Building Workflow Solutions
  • Chapter 16 – Business Intelligence and SharePoint Server 2007
  • Appendix A: Using the Microsoft Visual Studio 2005 Extension for Windows SharePoint Services 3.0

The book covers most if not all of the fundamentals to get you started building solutions with WSS 3.0 or MOSS 2007 and has whole chapters dedicated to building certain types of solutions such as using MOSS as a CMS platform and utilising the web content management features of the product.

I have had this book for a while now and find myself constantly referring back to it especially to lookup some XML I forgot.

As a summary this book covers a wide range of topics and focuses on teaching the right development techniques from an experienced developer’s point of view and is an excellent source to refer back to when you’re stuck. I would definitely recommend getting this if you are planning to do any development on the SharePoint platform.

I’ll be giving a copy of this book away as a prize in the near future but if you want to get your hands on it now then head over to http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470117567.html to purchase it for a mere £31.99.

ISBN: 978-0-470-11756-9

MOSS 2007 Forms Based Authentication using AD LDS and Windows Server 2008

September 11, 2008 Lee Dale 17 comments

Forms Based Authentication is an attractive option for companies running MOSS 2007 because it means you can give partners and external clients access to your Sharepoint sites without having to give them a full blown Windows domain account, the only drawbacks being it’s quite tricky to set up and most people only see SQL Server as an option for a user store which gives complications with regards to maintenance of them users and less flexibility should you need to migrate them users to a full blown Windows account later on.

I am currently running MOSS 2007 on Windows Server 2008 and I wanted to implement Forms Based authentication using AD LDS as the user store instead of SQL Server. The benefit for using AD LDS as a user store is that it is built on the same enterprise level authentication server as Active Directory and comes with a user management application that will be familiar to most Windows administrators unlike SQL Server which can only be administered using the Web Site Administration tool that comes with Visual Studio. You can also easily migrate an AD LDS user store to a full blown Active Directory domain controller if that requirement should arise in the future.

I couldn’t find much on the web on how to setup and configure AD LDS with Windows Server 2008 and as It’s a fairly tricky undertaking I thought I would write an article to hopefully give a clear and concise step by step guide on how to get it up and running.

Installing AD LDS

To start off with I am assuming you have MOSS 2007 installed on Windows Server 2008 already so the first step would be to add the AD LDS role.

  • Open up Server Manager and click on the roles section to the left.
  • Click on the “Add Roles” link on the right which should bring up the “Add Roles Wizard”.
  • Check the box next to Active Directory Lightweight directory services and click next as shown below.

  • Follow the wizard until the end and AD LDS should now be installed on your server.

Configuring AD LDS

Now we have AD LDS installed we need to create a user store.

  • Open up Administrative Tools and click on “Active Directory Lightweight Directory Services Setup Wizard” to start the setup process.
  • Click next on the first page and you will be presented with the step below, make sure “Unique instance” is selected and click next.

  • On the next step give your user store instance a name as shown below and click next.

  • Now you need to give your instance a port number so you can access it, recommended to leave the default values here.

  • Now we need to create a partition for our user store. Select “Yes, create an application directory partition” and enter a valid X.500 AD partition name. Make a note of this Partition name as you will need it later on.

  • The next step is to tell AD LDS where to physically store your data.

  • Choose which domain account you want AD LDS to run under, I have left selected the default Network Service Account.

  • Next tell AD LDS which account you would like to give admin rights to.

  • The last step is pretty important make sure you select the MS-User.ldif file to import; this makes sure you have the User classes available within your AD LDS store.

And thats it you now have a AD LDS store setup. Then next step is to add a user to your store.

  • Under Administrative tool you will now see ADSI Edit application, open this up.
  • Right click on the ADSI Edit node and select “Connect to” you will see the “Connection Settings” dialog box shown below.

  • Enter a name for your connection in the Name box.
  • Under Connection Point enter your Distinguished Name into the “Select or type a Distinguished Name or Naming Context:” box. This will be the Partition name you entered earlier on when creating the user store.
  • In the “Select or type a domain or server” box enter you domain name and port number you setup earlier.
  • Click the Ok button and you should now see your connection under the ADSI Edit node.
  • You can now add a user by right clicking on the Users container and selecting New -> object.
  • You will be presented with the dialog box shown below. Select the user class and click next.

  • On the next screen enter the users username into the value box and click next, then click finish.

  • You now have a user in your user store, to set the users password right click on the user and selected “Reset password”.
  • One more step you need to take is to enable the user by right clicking on the user and selecting “Properties”.
  • Scroll down to the ms-DS-UserAccountDisabled property and change it to TRUE.

Extending your web application

Now we have our user store in place we need to tell Sharepoint that we want to allow access to our sites for these users. You will need a separate URL and web application so that MOSS can distinguish from internal and external users and present them with the right authentication mechanism. For example my internal URL is portal.athousandthreads.net which will use Windows authentication and my external URL is partner.athousandthreads.net which will use FBA authentication. Both URL’s point to the same SharePoint site but each use different mechanisms for authenticating users.

Our first step is to extend the internal portal.athousandthreads.net application.

  • Open Central Administration and go to “Application Management”
  • Click on “Create or extend Web Application”.
  • Click “Extend an existing web application”.
  • You will be presented with the screen below.

  • Change the web application to your internal web application, in my case portal.athousandthreads.net
  • Select create a new IIS website and enter a name.
  • Enter port 80 into the port textbox and your host header into the host header section, in my case partner.athousandthreads.net, this will be your external URL.
  • Under the Load Balanced URL section make sure you change the Zone dropdown to Internet, this is very important.
  • Click Ok and you extended web application will be created.
  • Make sure you can navigate to your external URL, if you don’t get anything then make sure you have made the right DNS or Host file entries on your server.


Modifying web.config files.

At a minimum we need to modify the Central Administration and external web application web.config files you will also need to modify the SSP and MySite web.config files if you intend to use FBA with these services.

  • Open up your external web application web.config file and make the following entry just before the system.web node.

  • Be sure to change the connectionString attribute to match your own domain, port and partition name.
  • Now make the following entry inside the system.web node.

  • Change the connectionUsername and connectionPassword attributes to match your own credentials.
  • Save the web.config file and now open up your Central Administration web.config file.
  • Insert exactly the same entries in this web.config file as before.
  • Change the defaultProvider attribute of the roleManager node to AspNetWindowsTokenRoleManger, this is to ensure you can still access Central Administration with Windows authentication.
  • Save the web.config file and do and IISRESET for good luck.

Configuring authentication providers.

All we need to do now is tell Sharepoint that our external web application (partner.athousandthreads.net) will be using Forms Based Authentication.

  • Open up Central Administration and go to Application Management.
  • Click Authentication Providers and click the Internet zone on next screen. You should then be presented with the screen below.

  • Change the authentication type to Forms and enter the Membership provider name and Role manager name from your web.config files in the respective boxes.
  • Make sure you select Yes under Enable Client Integration.
  • Click Save.


Adding FBA permissions.

Ok so now our external web application is using FBA and our Central Administration knows about our AD LDS store, we can now go ahead and add an FBA user to our web application.

  • Open up Central Administration and select Policy for Web Application.
  • Add a new user and you should now be able to enter an FBA user into the people picker box.
  • Once you have added a user to the web application policy you should be able to log into the internal web application using Windows authentication (portal.athousandthreads.com) and begin adding your FBA user permissions to the site.

There you have it, It’s a bit long winded and a little tricky but pretty cool when it’s finally set up and working, trying navigation to you external web application (partner.athousandthreads.net) and you should be presented with a FBA login screen.

kick it on DotNetKicks.com

Dynamically adding WebParts using WebPartManagerInternals class

January 10, 2008 Lee Dale 20 comments

I’m currently working on a project the requires the use of WebParts to allow a user to construct custom reports by dragging and dropping WebParts into WebPartZones. I needed to dynamically create these WebParts on the fly and add them to the page programmatically. I tried to do this by using the standard AddWebPart() method of the WebPartManager control but found that using this method the WebPart doesn’t seem to be added to the page correctly which seems to be because the AddWebPart() methods gives the WebPart a random ID therefore it cannot participate in ViewState management. Furthermore because of the need to add the WebPartZones within the Page OnInit event the WebParts were getting recreated each time the page did a postback.

I searched around the web and found lots of people having the same problem but very little in the way of solutions to the problem. Eventually I stumbled across a forum post that mentioned the WebPartManagerInternals class. The documentation fails to mention exactly how to use this class but contained the following text:

“Isolates into a separate class methods that are used by the WebPartManager control and can be overridden by developers who extend the control, but are rarely needed by page developers.”

It also mentions that the class is a sealed class meaning you cannot derive from it and a quick look in Reflector showed me that it’s contructors were internal. This meant I needed to access the class from within the WebPartManager class.

I created a new DynamicWebPartManager class that derived from WebPartManager and in this class I created a method called AddDynamicWebPart(WebPart webPart, WebPartZone zone) which as you can see accepts a WebPart and a WebPartZone. In this method I called two methods on the Internals property (beware this Internals property DOE’S NOT show up in Intellisense) AddWebPart() which accepts a WebPart and SetZoneID() which tells it which WebPartZone to add the WebPart to.

public class DynamicWebPartManager : WebPartManager
{
public void AddDynamicWebPart(WebPart webPart, WebPartZone zone)
{
Internals.AddWebPart(webPart);
Internals.SetZoneID(webPart, zone.ID);
}
}

Now by using this DynamicWebPartManager class on your page instead of the out of the box WebPartManager class you can add WebParts by calling the AddDynamicWebPart() method.

WebPartZone reportZone = new WebPartZone();
reportZone.ID = “reportZone1″
reportZone.HeaderText = “My Report”;
ToolBoxPanel.Controls.Add(reportZone);

TestTableWebPart webPart = new TestTableWebPart();
webPart.ID = “webPart1″
webPart.Title = “My Report – Table”;
ReportBuilderWebPartManager.AddDynamicWebPart(webPart, reportZone);

kick it on DotNetKicks.com

Categories: .Net, ASP.Net, C#, SharePoint, WebParts

Creating a Tableless LoginControl with ASP.Net 2.0

November 17, 2007 Lee Dale 6 comments

The trouble with using some of the built in .Net controls like LoginControl and TreeView is that they render their output in tables and as we know tables should only be used to display tabular data not control the layout of a web page.

If we wanted to write semantic markup and style our web pages so they have proper accessible output we need to override the way ASP.Net controls render their HTML.

One way of doing this is using the CSS friendly control adapters which come with a number of built in controls for changing the rendered output of certain ASP.Net controls. Using these controls you can completely alter the way each ASP.Net control renders its output to the browser. The drawback here is that you need to reference another assembly and write .Net code if you need to modify anything.

The LoginControl supplies you with a nice ContentTemplate section that allows you to control the rendered output directly in the markup.

The following ASP.Net and CSS demonstrates how to create a tableless LoginControl. I apologise for the code formatting, it seems no matter what I do wordpress doesn’t like code :( . Best thing to do is copy and paste into a proper editor window to see what I’ve done.

Markup:

<div id=”Registration”>
<asp:CreateUserWizard ID=”CreateUserWizard1″ runat=”server”>
<WizardSteps>
<asp:CreateUserWizardStep ID=”CreateUserWizardStep1″ runat=”server”>
<ContentTemplate>
<h1>Sign Up for Your New Account</h1>
<div id=”Security”>

<span class=”FormLabel”>
<
asp:Label ID=”UserNameLabel” runat=”server” AssociatedControlID=”UserName”>User Name:</asp:Label>
</span>
<span class=”FormControl”>
<asp:TextBox ID=”UserName” runat=”server”></asp:TextBox>
<
asp:RequiredFieldValidator ID=”UserNameRequired” runat=”server” ControlToValidate=”UserName”
ErrorMessage
=”User Name is required.” ToolTip=”User Name is required.” ValidationGroup=”CreateUserWizard1″>*
</asp:RequiredFieldValidator>
</span>
<span class=”FormLabel”>
<
asp:Label ID=”PasswordLabel” runat=”server” AssociatedControlID=”Password”>Password:</asp:Label>
</span>
<span class=”FormControl”>
<asp:TextBox ID=”Password” runat=”server” TextMode=”Password”></asp:TextBox>
<
asp:RequiredFieldValidator ID=”PasswordRequired” runat=”server” ControlToValidate=”Password”
ErrorMessage
=”Password is required.” ToolTip=”Password is required.” ValidationGroup=”CreateUserWizard1″>*</asp:RequiredFieldValidator>
</span>

<span class=”FormLabel”>
<
asp:Label ID=”ConfirmPasswordLabel” runat=”server” AssociatedControlID=”ConfirmPassword”>Confirm Password:</asp:Label>
</span>
<span class=”FormControl”>
<
asp:TextBox ID=”ConfirmPassword” runat=”server” TextMode=”Password”></asp:TextBox>
<
asp:RequiredFieldValidator ID=”ConfirmPasswordRequired” runat=”server” ControlToValidate=”ConfirmPassword”
ErrorMessage
=”Confirm Password is required.” ToolTip=”Confirm Password is required.”
ValidationGroup=”CreateUserWizard1″>*
</
asp:RequiredFieldValidator>
</span>
<span class=”FormLabel”>
<
asp:Label ID=”EmailLabel” runat=”server” AssociatedControlID=”Email”>E-mail:</asp:Label>
</span>
<span class=”FormControl”>
<asp:TextBox ID=”Email” runat=”server”></asp:TextBox>
<
asp:RequiredFieldValidator ID=”EmailRequired” runat=”server” ControlToValidate=”Email”
ErrorMessage
=”E-mail is required.” ToolTip=”E-mail is required.” ValidationGroup=”CreateUserWizard1″>*</asp:RequiredFieldValidator>
</span>
<span class=”FormLabel”>
<
asp:Label ID=”QuestionLabel” runat=”server” AssociatedControlID=”Question”>Security Question:</asp:Label>
</span>
<span class=”FormControl”>
<asp:TextBox ID=”Question” runat=”server”></asp:TextBox>
<
asp:RequiredFieldValidator ID=”QuestionRequired” runat=”server” ControlToValidate=”Question”
ErrorMessage
=”Security question is required.” ToolTip=”Security question is required.”
ValidationGroup=”CreateUserWizard1″>*</asp:RequiredFieldValidator>
</span>
<span class=”FormLabel”>
<
asp:Label ID=”AnswerLabel” runat=”server” AssociatedControlID=”Answer”>Security Answer:</asp:Label>
</span>
<span class=”FormControl”>
<asp:TextBox ID=”Answer” runat=”server”></asp:TextBox>
<
asp:RequiredFieldValidator ID=”AnswerRequired” runat=”server” ControlToValidate=”Answer”
ErrorMessage
=”Security answer is required.” ToolTip=”Security answer is required.”
ValidationGroup=”CreateUserWizard1″>*</asp:RequiredFieldValidator>
</span>
<span class=”FormLabel”>
<
asp:CompareValidator ID=”PasswordCompare” runat=”server” ControlToCompare=”Password”
ControlToValidate
=”ConfirmPassword” Display=”Dynamic” ErrorMessage=”The Password and Confirmation Password must match.”
ValidationGroup=”CreateUserWizard1″></asp:CompareValidator>
</
span>
<span class=”FormControl”>
<
asp:Literal ID=”ErrorMessage” runat=”server” EnableViewState=”False”></asp:Literal>
</span>
</div>
</ContentTemplate>
</asp:CreateUserWizardStep>
<asp:CompleteWizardStep ID=”CompleteWizardStep1″ runat=”server”>
</asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
</div>

 

CSS:
#Security
{
margin-top: 10px;
width: 60%;
text-align: left;
border: dashed 1px #999999;
padding: 20px;
background-color: #f9f9f9;
}

#Registration
{
margin-top: 5px;
margin-left: auto;
margin-right: auto;
text-align: center;
width: 70%;
font-size: 1.2em;
}

#Registration h1
{
margin-top: 20px;
margin-bottom: 20px;
}
#Registration
input, textarea
{
width: 180px;
margin-bottom: 5px;
}

.Boxes
{
width: 1em;
}
.FormLabel
{
float: left;
width: 120px;
font-weight: bold;
}
.FormControl
{
float: left;
width: 45%;
}

This should provide you with a nicely formatted form that is rendered using DIV’s and SPAN’s rather than in a TABLE. You should now be able to style the markup and control layout better to provide your end users with a more accessible web page.

kick it on DotNetKicks.com

Categories: .Net, ASP.Net

Scott Guthrie’s presentation on new MVC Framework

October 12, 2007 Lee Dale Leave a comment

Scott Hansleman posted this video recorded from a recent ALT.Net conference.

Scott Guthrie demo’s the new MVC Framework from Microsoft which uses the MVC Front controller pattern that Ruby on Rails people would be familar with.

I definately recommend watching the presentation it’s 60 minutes long but well worth it.

I’m undecided on the Framework yet until I get to play with it, but I do know that introducing a more disiplined, structured way of developing web applications with .Net is a good thing.

Categories: .Net, ASP.Net, C#, MVC, patterns

Creating a Templated User Control with ASP.Net 2.0

August 11, 2007 Lee Dale 18 comments

We all know the benefits of re-usable components in our applications and User Controls in ASP.Net are an easy way to build reusable components that can be used throughout an entire web application.

Templated User Controls allows us to seperate the controls data from it’s presentation because a Templated User Control does not provide a default user interface.

For example I will show you how to create a templated address control thats allows you to reuse address fields across your web application but leaves the formatting up to the individual page designer to style how they wish.

First we open a new web application in Visual Studio and add a new Web User Control to our solution.

We then add a PlaceHolder control to the User Control which will act as a placeholder for our controls rendered data. Our controls markup looks like this:

Next we switch to our controls code behind and implement all the properties we need for our address control plus one other property that returns a type of ITemplate. Our code behind looks like this:


Now we need to create a container class that will act as our naming container and exposes all the properties of the User Control to the host page. The container class needs to inherit from the Control class and implkements the INamingContainer interface. The class looks like this:

We need to put the following code inside out controls Init event to instantiate our container class and set its properties, instantiate a copy of the controls ITemplate inside the container control and add our container control to the PlaceHolder’’s controls collection.

Now we have a fully working Templated User Control we can put this control onto any web page within out web application and set its data. The markup below shows how this is done:

And thats it!

If you want to do the same as this but package the control up into an assembly that can be reused across multiple web applications you need to create a control that inherits from the Control or WebControl class.

kick it on DotNetKicks.com

Categories: .Net, ASP.Net, C#

Multithreading with ASP.Net 2.0

July 22, 2007 Lee Dale 7 comments

Every good developer should understand the basics of how Threads and Processes work on the platform they are writing applications for.  For us it’s the Windows operating system and using the .Net Framework it’s even easier to harness the power of Multithreading.

Good Multithreading design can vastly improve your applications user experience and I have a little example below of how Multithreading can be used within an ASP.Net 2.0 website.

Our goal here is to send a request to the server and write out 101 lines to a text file on the webserver.  The WriteOutTextFile() method takes a very long time to complete as I have deliberatly made the method run slow by making the thread go to sleep for 500ms every iteration of the loop.  Now say this method was used as a logging tool behind the scenes, we wouldn’t want our user waiting for the method to write out all 101 lines before the web page was returnd to them. The user doesn’t care that your logging method takes a long time they just want to see their request returned to them, this is where multithreading comes in. We open up a new web site in Visual Studio and we have a simple application as shown below:

I put one label and one button on the form and our markup looks like this:

We then switch to our code behind and write the following code in the OnLoad event:

Here the first thing we are doing is setting the label’s text property to “PostBack!” which is pretty standard stuff, the interesting part is the next four lines.   In version 2.0 of the .Net Framework multithreading was made so much easier by introducing the ThreadStart class which allows us to easily pass the method we want to be called when our threads starts to the Thread class.  The ParameterizedThreadStart class makes things even easier when you want to pass arguments to your methods and anyone who has done multithreading in .Net 1.1 knows how much of a headache this was. So what we are doing in these four lines is creating an instance of the ThreadStart class to tell our new thread to call our worker method WriteOutTextFile when we start out new thread. We then go ahead and create our new Thread and call it’s Start() method. This will kick off our WriteOutTextFile() method on a new thread and allow the OnLoad event to finish execution and return our request back to the user.  Our new thread will continue executing and writing to our text file in the background. The WriteOutTextFile() method looks like this:

That’s a simple example of how multithreading can be used to good effect with the .Net 2.0 framework.  As you can see it’s a very powerful tool and mastering multithreading can make your applications more performant, much more scalable and give your end user and less frustrating experience. I have uploaded the source code here, if you want to download and anaylse it yourself.

kick it on DotNetKicks.com

Categories: .Net, ASP.Net, C#