I am Raghuveer

In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

Showing posts with label ASP.NET. Show all posts
Showing posts with label ASP.NET. Show all posts

Binding Repeater Control with XML Documents using XmlDataSource

The Extensible Markup Language (XML) is the universal format for structured documents and data on the Web. Developers are using XML based RSS feeds and XML Web Services in their web applications on quite regular basis these days. ASP.NET version 1.1 was lacking built in capability to handle XML data that’s why ASP.NET version 2.0 is shipped with dedicated data source control called XmlDataSource. In this tutorial I will show you how you can use XmlDataSource control to handle and display XML data with very famous ASP.NET Repeater control. This tutorial will also show you how to bind XML elements with Repeater control using XPath binding expressions.

The XmlDataSource control usually used to display read only XML data but it still allows user to edit, delete or update XML data using custom code as there is no built in support for automatic edit/update in the control. The XmlDataSource control supports declarative data binding to XML files and because of hierarchical nature of XML data, developers usually bind this control with hierarchical data bound controls such as TreeView or Menu. However this control can also be used with tabular data bound controls such as GridView, Repeater or DataList controls.
The XmlDataSource control has following important properties which can be set either through the Configure DataSource dialog box or programmatically using code behind file.
DataFile: This property specifies the absolute or relative file path of XML file which you want to use for data binding.
Data: This property gets or sets the block of XML data for data binding. If both DataFile and Data properties are set, the DataFile property takes precedence and data in the XML file will be used for binding.
XPath: This property specifies an XPath expression which acts as filter to XML data. Actually XPath is a language used to retrieve information from XML documents and by using XPath you can traverse through the nodes and attributes of XML documents.
For the purpose of this tutorial, I have created the following sample XML file. It has list of employees with their departments available as attributes and their names and salaries available as elements. Create the following XML file and save it with the name Employees.xml in your website root directory.

<?xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee Department="Sales">
<Name>David</Name>
<Salary>20000</Salary>
</Employee>
<Employee Department="Finance">
<Name>Simon</Name>
<Salary>18000</Salary>
</Employee>
<Employee Department="Accounts">
<Name>Peter</Name>
<Salary>22000</Salary>
</Employee>
</Employees>

Now create a web form in your website and drag the XmlDataSource control from the Data category in the toolbox. Click the arrow on the right side of the XmlDataSource Control to open the XmlDataSource smart tasks options and click Configure Data Source link to open the Configure Data Source dialog box. Click Browse button available next to Data File property and select the Employees.xml file stored in your website. In the XPath expression property type Employees/Employee to traverse to Employee elements in the XML file. Following figure shows all the above mentioned steps for your reference.

XmlDataSource Control
Configure Data Source dialog box for XmlDataSource configuration

Next, add a Repeater control on your web page and set its DataSourceID property to XmlDataSource1. This property will bind the Repeater control with XmlDataSource control which is linked with XML file. The following code shows you how you can bind the Department attribute andName and Salary elements inside Repeater ItemTemplate using XPath binding expressions.

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="XmlDataSource1">
<ItemTemplate>
<strong>
<%# XPath("@Department")%><br />
</strong>
- Name: <%#XPath("Name")%><br />
- Salary: <%#XPath("Salary")%><br />
</ItemTemplate>
</asp:Repeater>

If you have configure both Repeater and XmlDataSource controls properly as described in this tutorial you should be able to see the following output rendered in browser.

Binding Repeater Control with XmlDataSource

Repeater control displaying XML File data

Download SourceCode

Creating Custom Configuration Sections in ASP.NET

Almost all ASP.NET Web Applications require some sort of configuration settings to be stored in the web.config files. These settings can be application settings, database connection strings, user authentication settings, page specific settings and so on. ASP.NET also provides very powerful Configuration API to work with configuration settings defined in web.config files. The Configuration API not only allows us to read/write settings in configuration files with ease but also allow us to define our own custom configuration sections in web.config. These custom sections are very useful in large web applications where you have a lot of application settings to store in the configuration file. In this tutorial, I will show you how to create and use custom configuration sections in ASP.NET.

I am sure many of you are using the following appSettings section of web.config to define your application specific settings.

<appSettings>
   <add key="DefaultLanguage" value="English-US"/>
   <add key="WebsiteTitle" value="Microsoft Corporation"/> 
   <add key="MaximumTransactionLimit" value="100000"/>
</appSettings>

However, in large projects you end up having an endless list of key/value pairs in your web.config file. This makes life little difficult as you have to make sure when you are reading these values you are typing the spellings of all keys correctly e.g. DefautlLanguage is not same as DefaultLanguage. You also need to do lot of type casting when you are reading all types of values such as numbers, Booleans, dates, etc.

To solve these problems, ASP.NET allows us to create a custom configuration section in web.config. A custom configuration section can be defined in the element in web.config. You need to specify the name of the section and the class name that is responsible for serialization and de-serialization of attributes of custom configuration section into class properties. Following is an example of custom configuration section defined for a typical ecommerce web application.

<configuration>
<configSections>
      <section name="ShoppingCartSettings" type="ShoppingCartSection"/>
   </configSections>

   ...
   ...
</configuration>

Please keep in mind that the value given for the type attribute above is the fully qualified name of the class. If the class is in App_Code folder of your project, you can simply use its name as used in the above example. If the class is in another assembly (.dll) then you need to use"Namespace.ClassName, AssemblyName" as the value of the type attribute. Once you have defined the custom configuration section you can use it in web.config file anywhere inside root configuration element as shown in the following code.

<configuration>
<system.web>
</system.web>
...
<ShoppingCartSettings
defaultCurrency="USD"
maxItemsInCart="10"
paypalCheckoutEnabled="true" />

</configuration>

You can define any number of properties in the ShoppingCartSettings section but keep in mind that these properties need to be defined in the class named ShoppingCartSection as mentioned above in the type attribute. ShoppingCartSection class will be a simple C# class inherited from the System.Configuration.ConfigurationSection class. To define this class, add the reference of System.Configuration in your project and import the namespace on the top of the file with using statement.

using System.Configuration;
public class ShoppingCartSection : ConfigurationSection
{
...
...
}

The ShoppingCartSection class represents the root ShoppingCartSettings element of the custom configuration section defined in web.config file. Next you need to define the properties of the class as shown in the following code.

public class ShoppingCartSection : ConfigurationSection
{
[ConfigurationProperty("defaultCurrency", IsRequired = true, DefaultValue="USD")]
[StringValidator(MinLength=1, MaxLength=100)]

public string DefaultCurrency
{
get { return (string)this["defaultCurrency"]; }
set { this["defaultCurrency"] = value; }
}
[ConfigurationProperty("maxItemsInCart", IsRequired = true, DefaultValue = "5")]
[IntegerValidator(MinValue=1, MaxValue=10)]

public int MaxItemsInCart
{
get { return Convert.ToInt32(this["maxItemsInCart"]); }
set { this["maxItemsInCart"] = value; }
}
[ConfigurationProperty("paypalCheckoutEnabled", IsRequired = false, DefaultValue = false)]
public bool PaypalCheckoutEnabled
{
get { return Convert.ToBoolean(this["paypalCheckoutEnabled"]); }
set { this["paypalCheckoutEnabled"] = value; }
}
}

Notice how the class properties MaxItemsInCart, DefaultCurrency etc. are mapped with the attributes defined in custom configuration element in web.config using the ConfigurationProperty attribute declaration on top of the properties. The ConfigurationProperty attribute is also using some other parameters such as DefaultValue and IsRequired. The DefaultValue parameter specifies the default value of the property if it is not defined in the web.config. The IsRequired parameter specified whether the attribute defined in web.config is required or optional. I have also used the StringValidator and IntegerValidator attributes in the above code to show you how to validate the values specified in the web.config.
To read the custom configuration section data in your web pages you can use the static GetSection method of ConfigurationManager class as shown below:

ShoppingCartSection settings =
ConfigurationManager.GetSection("ShoppingCartSettings") as ShoppingCartSection;

Label1.Text = "Default Currency: " + settings.DefaultCurrency;
Label2.Text = "Max Allowed Items in Shopping Cart: " + settings.MaxItemsInCart.ToString();
Label3.Text = "Paypal Checkout Enable: " + settings.PaypalCheckoutEnabled.ToString();

Using Multiple Programming Languages in ASP.NET Website

Source: ezzylearning

ASP.NET websites do not allow you to use multiple programming languages such as C# and Visual Basic in the App_Code folder of the website project. If you are creating a C# web site and you have copied a Visual Basic source file in App_Code folder, you won’t be able to compile your ASP.NET website. Off course, if it is a small source file, then you can convert it into C# source code either yourself or by using any code converter but it is time wasting practice if you have a large file or you want to use multiple source files. In this tutorial, I will show you how you can use multiple programming languages source files in a single website project by just doing some simple modifications in the configuration settings of the website.

To get things started, create an ASP.NET website project using either Visual Basic or C# in Visual Studio. I am creating a C# website project for this tutorial. Now right click the website project name in Solution Explorer and add the Add App_Code folder in the website from the "Add ASP.NET Folder" menu option. Next you need to create a separate subfolder for each of the programming language you want to support in your website. For the purpose of this tutorial I am adding CS and VB subfolders to support C# and Visual Basic source files. For this tutorial I am creating two simple code files named "ClassOne.cs" and "ClassTwo.vb" in CS and VB subfolders respectively. Your website structure should look like the following figure after the files are created.

Multiple Programming Languages in ASP.NET website

To check whether these files compile and work properly, I am adding a field and a function in both files. The source code of both files is shown below:

ClassOne.cs

public class ClassOne
{
   public string Message;
   public string GetMessage()
   {
      return this.Message;
   }
}

ClassTwo.vb

Public Class ClassTwo
    Public Message As String
    Public Function GetMessage() As String
        Return Me.Message
    End Function
End Class

After creating separate subfolders for each programming language and creating multiple source files, all you need is simple modification in your website web.config file to tell ASP.NET to compile the files located in those subfolders separately. Open the web.config file of the website project and locate <compilation> the section in the file. You need to add the following <codesubdirectories> section inside the <compilation>section.

<compilation>
<codeSubDirectories>
      <add directoryName="CS"/>
      <add directoryName="VB"/>
   </codeSubDirectories>

</compilation>

That’s all is required to support multiple languages in ASP.NET website project. You can now use both classes as normally in your website. To test these classes, create a Default.aspx page if it is not already created in your project. Add Two buttons and a label control on it and you can use those two classes on the button click events of both buttons as shown in the code below:

 

protected void Button1_Click(object sender, EventArgs e)
{
   ClassOne obj = new ClassOne();
   obj.Message = "C# Function is called...";
   Label2.Text = obj.GetMessage();
}
protected void Button2_Click(object sender, EventArgs e)
{
   ClassTwo obj = new ClassTwo();
   obj.Message = "VB Function is called...";
   Label2.Text = obj.GetMessage();
}

Following is the output of the page.

Multiple Programming Languages in ASP.NET website

Developers commonly include multiple programming languages in Web applications to support multiple development teams that operate independently and prefer different programming languages. I hope I am able to teach you how you can support multiple programming languages in ASP.NET website project.

Download SourceCode

GridView Manual Implementation


Open VisualStudio => Select new Website=> give name to the website as GridView_Demo
Add a asp.net webpage to website Default.aspx
Add a Gridview to the page and put AutoGenerateColumns="False"
    <asp:GridView ID="GridView2" runat="server" BackColor="White"
        BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4"
        Width="691px" AutoGenerateColumns="False">
        <Columns>       
            <asp:BoundField HeaderText="Party Name" DataField="patName" />
            <asp:BoundField HeaderText="Party Id" DataField="patId" />
            <asp:BoundField HeaderText="Email" DataField="email" />
        </Columns>
        <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
        <RowStyle BackColor="White" ForeColor="#330099" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
        <SortedAscendingCellStyle BackColor="#FEFCEB" />
        <SortedAscendingHeaderStyle BackColor="#AF0101" />
        <SortedDescendingCellStyle BackColor="#F6F0C0" />
        <SortedDescendingHeaderStyle BackColor="#7E0000" />
    </asp:GridView>

In code behind file put the fallowing code in page_load
            DataTable dt = new DataTable();
            DataColumn patName = new DataColumn("patName");
            DataColumn patId = new DataColumn("patId");
            DataColumn email = new DataColumn("email");
           
            dt.Columns.Add(patName);
            dt.Columns.Add(patId);
            dt.Columns.Add(email);
           
            DataRow row = null;
            foreach (string record in records)
            {
                string[] cols = record.Replace("||", "|").Split('|');
                if (cols.Length > 1)
                {
                    row = dt.NewRow();
                    row[patId] = cols[1].Trim();
                    row[patName] = cols[0].Trim();
                    row[email] = cols[2].Trim();
                    dt.Rows.Add(row);
                }
}
            GridView2.DataSource = dt;
            GridView2.DataBind();
The gridview in webpage will look like fallowing image:
Capture