Blogroll

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Read XML File into DataSet

There are a number of ways to read an XML file and use the contents in .NET. One nice way, for people who are familiar with using DataSets is the ReadXML method of the DataSet Class. This method reads an XML file into a DataSet that can then be used to retreive and manipulate the elements via standard DataTable and DataRow methods.

In this example we have created a simple XML file used to store application settings that need to be shared amongst several applications. It is bascially a trimmed-down version of the app.config file Visual Studio creates whenever you add settings to s project via the IDE.

<?xmlversion="1.0"encoding="utf-8" ?>

<AppSettings>

<settingname="CurrentInstance"serializeAs="String">

<value>1</value>

</setting>

<settingname="OutputDirectory"serializeAs="String">

<value>\\SV-OCRMGR\mbrc\ocr\xmloutput\test2</value>

</setting>

</AppSettings>

To retrieve the value of any setting, we need to grab the setting node from the XML file and return the child element called value.

When we load the DataSet, in this simple case it consists of just one DataTable, called settings. The settings tables consists of two rows. One interesing thing to note is that when the child element returns a single value, there is not distinction made between child elements and attributes. The child element value and the attribute name will both be treated as columns in the resulting DataTable.

To see how .NET DataSets handle more complex XML, we can modify the original XML file so that in addition to the value child element, setting also had a complex child element called currentStatus. This element has a number of sub-elements, namely status and lastUpdated.

<?xmlversion="1.0"encoding="utf-8" ?>

<AppSettings>

<settingname="CurrentInstance"serializeAs="String">

<value>1</value>

<currentStatus>

<status>live</status>

<lastUpdated></lastUpdated>

</currentStatus>

</setting>

<settingname="OutputDirectory"serializeAs="String">

<value>\\SV-OCRMGR\mbrc\ocr\xmloutput\test2</value>

<currentStatus>

<status>test</status>

<lastUpdated></lastUpdated>

</currentStatus>

</setting>

</AppSettings>

If we run our code, nothing seems to have changed, however if we add a breakpoint we will see the the DataSet contains two DataTables, setting and currentStatus. In addition, .NET has added a new column to both tables called setting_Id. This is the primary-foreign key between the two tables that is used to link the values in setting to those in currentStatus. Read the next post as we investigate how .NET handles more complicated XML files.

Raising Events from Master Pages

In the post on Adding Custom Events to Web User Controls we looked at how we could access events raised by controls within a Web User Control. This worked perfectly on our single default.aspx page, but in more complex websites using Master and Content Pages, we need a slightly different approach. In the first scenario, imagine we have a Web User Control located on a Master Page and we want the content to change when an event is raised.

To get started, review the previous posts. Then add a new Master Page called Default.Master to your project by selecting Add New Item from the Website menu.

Drag and drop the CustomDropDown Web User Control onto the design surface of Default.master. Put it above the ContentPlaceHolder as we will be changing the results selected in the ContentPlaceHolder depending on the value selected in CustomDropDown.

Next create a new blank web page called Results.aspx, making sure to select Default.master as the master page.

Next we will add a label on the design surface of Results.aspx. The label will be used to display the name selected in the CustomDropDown, similarly to how the label operated in Adding Custom Events to Web User Controls. To be able to access the selected value of CustomDropDown, we need to make a few changes.

Firstly, we need to add some extra code to create a constructor for our CustomDropDownEventArgs class so that we can raise events using delegation.

Public Sub New(ByVal EmployeeID As String, ByVal EmployeeName As String)

_payrollID = EmployeeID

_fullname = EmployeeName

End Sub

Raising the event in Default.aspx is similar to how we raised the event in the single page in previous posts. We need to create a method that handles ListChanged - for now, simply cut and paste the code from the previous post into the code behind for Default.master.

Now to refer to the events arguments in the content page, we add add an event handler into the Page_Init sub of Results.aspx and create a call to a private function that displays the selected name in the label on out content page.

Now when we run Results.aspx and select a value from the drop down list, three actions are being taken. First within the Web Custom Control the drop down list SelectedItemChanged event is raised, displaying the employee ID in a label. Next, the same event is captured by Default.master and the selected name is displayed in a label to the right of the Web Custom Control. Lastly, the content page also captures the same event and displays the selected name in a label below the Web Custom Control.

Saving a Web User Control as a reusable DLL

If you have been folowing the previous posts you would now have successfully created a simple Web User Control and used it within a single page website. In the first post we created the Web User Control named CustomDropDown. In the second and third posts we added Events to the CustomDropDown control. The final step in the process is to make this control easily reusable across a multitude of web sites. To do this, we compile the Web User Control as a dll.

Creating a DLL from a Web User Control

Before we set about saving the CustomDropDown control as a dll, we need to make some small changes. The first is to add a ClassName to the @Control directive in the CustomDropDown.ascx file.

Secondly, to ensure that the custom Event class CustomDropDownEventArgs is accessable from the DLL, we need to copy the code from the class .vb file into the CustomDropDown.ascx.vb file. Make sure you copy the complete class code - i.e. everything including the Public Class CustomDropDownEventArgs tags. The complete code for the CustomDropDown.ascx.vb file is shown below.

Public Property FullName() As String Get Return _fullName End Get Set(ByVal value As String) _fullname = value End Set End Property Public Property PayRollID() As String Get Return _payrollID End Get Set(ByVal value As String) _payrollID = value End Set End PropertyEnd Class

We can now build and publish the website using the commands in Visual Studio.

Un-tick the Allow this precompiled site to be updatable, this ensures that everything, including the mark-up on the ascx page is compiled.

Tick the Use fixed naming and single page assemlies, this will ensure that the ascx file, including the code behind file will be saved in its own DLL and not compiled with any other elements.

Adding the DLL to a new Website

Once you have published the control, you can now add it to a new or existing website. To utilise the control, simply use the Add Reference command and browse to the location where you published the website in the step above. The DLL's will be saved under the \bin folder.

To include the control on a page in your new website you need to add two lines of code to the source. The first line registers the control and is similar (but not identical) to the @Register directive added automatically by Visual Studio when you drag and drop the Web User Control onto a page.

Two things to note about the above tag, firstly make sure the Namespace element matches the namespace you added to the Classname element in the previous steps and you only need to inlcude the root Namespace component of the Classname. The second it that the Assemby name must match the DLL name that you added a reference to, but does not include the file extension '.DLL'.

Once you have set up a reference and registered it on the page, you can add the tag whereever you need the control to appear in your mark-up. While you are there, add a label control to the page so that you can test the Event handling

Adding Custom Event Handling

The final step is to add the custom event handling we outline in Adding Custom Events to Web User Controls As we named the control the same as the Web User Control in the previous post, we can simply cut and past the CustomDropDown1_ListChanged code from the default.aspx page into our new page.

In our previous posts we have been creating a Web User Control named CustomDropDown that contains a dropdownlist containing employee names and payroll numbers. In the first post we added an event to the CustomDropDown that displayed the PayrollID of the selected employee in a label control within the Web User Control itself. In the next post, we expanded upon this so that when a new employee is selected, a label on the page containing CustomDropDown displays the text 'List Changed'. In this post, we now want to add functionality that will display the details of the employee in a label on the page containing CustomDropDown.

The first step is to create a new Class containing the code that will provide the information we want on the page. Go to the Website menu and select Add New Item, then choose the Class item and enter the Name 'CustomDropDownEventArgs'. If you are prompted to add the code to the App_Code folder, choose Yes.

The CustomDropDownEventArgs class will consist of two public properties that will be populated by the controls on the CustomDropDown Web User Control. At this stage, all we need to do is create the properties, as the Event Handler will call this class from the CustomDropDown control.

Public Property FullName() As String Get Return _fullName End Get Set(ByVal value As String) _fullname = value End Set End Property Public Property PayRollID() As String Get Return _payrollID End Get Set(ByVal value As String) _payrollID = value End Set End PropertyEnd Class

We now need to modify the code behide CustomDropDown so that the ListChanged Event we created in the previous post now includes the new CustomDropDownEventArgs class.

Public Event ListChanged(ByVal sender As Object, ByVal e As CustomDropDownEventArgs)

We will also need to change the SelectedIndexChanged event for the DropDownList, so that it will popluate the CustomDropDownEventArgs with its current values.

That's all we need to do in CustomDropDown.ascx, so we can make a few changed to the page containg the Web User Control, named default.aspx.

First, we modify the CustomDropDown1_ListChanged event to handle the class we created. We can then add code to this event to display the values returned from this class, which have been populated by the Web User Control.

Now when we build and run the default.aspx page and select an employee, the SelectedIndexChanged event is raised within the Web User Control and the name of the employee is displayed in a label on the page.

Adding Events to Web User Controls in VB.NET

In a previous post, Creating Web Custom Controls in VB.NET we discussed how to create a very simple Web User Control, including how to respond to events raised by the controls contained within the Web User Control. In this post, we are going to extend upon this functionality and disuss how to handle events raised within the Web User Control from the page containing the the control. In otherwords, we want to learn how to tell the containing page when an event within the Web User Control has been raised and carry out some processing based on the results.

Firstly, we will need to make some changes to our Web Custom Web Control, code behind file named CustomDropDown.ascx.vb. To start with, we will declare a public Event called ListChanged.

Public Event ListChanged(ByVal sender As Object, ByVal e As EventArgs)

We then modify the DropDownList SelectedIndexChanged event to raise our new public Event.

Now we can make use of the ListChanged Event within the containing page, in this case the default.aspx page. When we dragged the CustomDropDown control onto the design surface of the dafault.aspx page Visual Studio added a few lines of code to the source view. By default, it named our control CustomDropDown1 and registered the control within a Page declaration. Start by adding a label to default.aspx in which we can display a message when the event is raised.

In the code behind page, default.aspx.vb, we can add some code to handle the ListChanged Event.

When you build and run the page and select an emplyee, the employees PayrollID is displayed in the label inside the Web User Control as implemented in the previous post, but now we also have a second label that displays the text 'List Changed' after we have selected an employee. This simple example shows how it possible to handle a sinigle event within the Web User Control, in this case the SelectedIndexChanged event, from both inside the control and on the containing page.

In the next post we will expand upon this functionality and learn how to create and handle custom events for Web User Controls.

Creating Web User Controls in VB.NET

Visual Studio provides a quick and simple way to create controls that can be reused on any page and across multiple applications. These are called Web User Controls and are similar to standard ASP.NET pages in that they can contain other controls, such as TextBox's and ImageButtons. One difference is the the Web User Control cannot be opened directly in a browser and must be contained within another page, as it does not contain HTML page tags of its own.

This simple tutorial will show you how to create a new web user control and add it to a standard ASP.NET page.

Creating the Web User Control

Create a new folder in your project to strore your web user controls, in this example we will create a folder called UserControls

From the Website menu, select Add New Item and choose Web User Control. Name your new control, in this example we are creating a resuable DropDownList so we will name the control CustomDropDown.

In the design surface of the of the CustomDropDown.ascx you can drag and drop any of the standard ASP.NET controls. We will drag a Label and a DropDownList. From the DropDownList Tasks popup menu, select Choose Data Source and add the details to retrieve data from your database. In this exa,ple we are retrieving a list of employees from a SQL Server database, so we set the display field to 'FullName' and the value field to 'PayrollID'

Adding the Web Custom Control to and Existing Page

That's all we need to do to our web user control for the moment, so its time to add it to our default.aspx page to test it out. Open the default.aspx page in design view and simply drag and drop the CustomDropDown.ascx file into the design surface.

Once you have added the custom control, press F5 to build and run the dafault.aspx page. You should see the label and dropdownlist populated with your data from the database.

Responding to Events inside a Web Custom Control

As mentioned earlier, a Web Custom Control is very similar to a standard ASP.NET Page and can contain any number of other controls. The Web Custom Control can also respond to events raised by the control it contains, just like a standard ASP.NET page.

Going back to our CustomDropDown.ascx control we are going to add an event that will display the PayrollID of the employee selected in the dropdownlist. First, make sure that the dropdownlist is set to automatically postback, so that the SelectIndexChanged event fires when the user selects the name of an employee. Then add this code to you code behind page CustomDropDown.ascx.vb

Now when we run the default.aspx page, whenever a new employee is selected, their PayrollID is displayed in the label. Yes I know, this is hardly very exciting, but it demonstrates how easy it is to respond to events raised by controls within the Web User Control.

In a future post, we will look at how we can respond to events raised by the Web user Control from the page containing the control, for example if we want to show the name of the employee in a TextBox located on the default.aspx page. We will also look at how to send information to the Web User Control from the containing page, such as connection strings, which is very handy when you want to reuse the control with a different datasource.