जगदीश खोलिया: October 2011

Friday, October 14, 2011

Ajax,Linq and XML in ASP.NET 3.5 and C#


AJAX and LINQ are probably the most-talked about Microsoft offerings at the moment, and rightly-so. Both provide us with powerful features to add to our development arsenal- AJAX allows us to create more user-friendly web applications that can almost rival our desktop equivalents; and then LINQ provides a unified way for us to communicate and interact with a wide array of data sources.
This tutorial will combine the two, and throw in a bit of XML too. In this example we are going to create a web application that will use an XML file to store small amounts of data, that we will display and also add to using AJAX and LINQ.
To demonstrate this, we will be storing names, cities and ages of people in the XML file. We will use a literal control to display the XML data and three textboxes to input new data.
Our XML file structure will look something like this:


<?xml version="1.0" encoding="utf-8"?>
<Persons>
<Person>
<Name>Paxton</Name>
<City>Munich</City>
<Age>29</Age>
</Person>
<Person>
<Name>Mike</Name>
<City>Orlando</City>
<Age>33</Age>
</Person>
</Persons>

Because we are using VS.NET 2008, all we need to do to enable AJAX on our page is add the following:

<form id="form1" runat="server">
<asp:ScriptManager id="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="updAdd" runat="server">
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>
</form>
This is the AJAX structure we will be using for our page. The ScriptManager will handle all of our AJAX calls, we don't need to do anything with that. The UpdatePanel specifies an area of the page that will partially refresh- instead of posting back the whole page. We will also add a trigger, to specify what will 'trigger' the partial refresh. To do this, though, we need the name of our button.
We add a button and the trigger to the page:

<form id="form1" runat="server">
<asp:ScriptManager id="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="updAdd" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="butAdd" EventName="Click" />
</Triggers>
<ContentTemplate>

<asp:Button ID="butAdd" runat="server" Text="Add" onclick="butAdd_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>


We reference the button in the trigger field of the UpdatePanel, which will cause the partial refresh to initiate when the button is clicked.
Next, we can add the rest of our form - the textboxes for data input, and the literal control for reading the XML. We can also add another button to initiate the reading of the XML file:

<form id="form1" runat="server">
<asp:ScriptManager id="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="updAdd" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="butAdd" EventName="Click" />
</Triggers>
<ContentTemplate>
<strong>Add to XML</strong><br />
Name:<br />
<asp:TextBox ID="txtName" runat="server" /><br />
City:<br />
<asp:TextBox ID="txtCity" runat="server" /><br />
Age:<br />
<asp:TextBox ID="txtAge" runat="server" /><br />
<asp:Button ID="butAdd" runat="server" Text="Add" onclick="butAdd_Click" /><br />
<asp:Label ID="lblStatus" runat="server" />
<br /><br />
<strong>Read XML:</strong><br />
<asp:Button ID="butRead" runat="server" Text="Read" onclick="butRead_Click" /><br />
<asp:Literal ID="litResults" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

Notice that both of our buttons have the onclick handlers specified. We can now code these in the code-behind, like so:

protected void butRead_Click(object sender, EventArgs e)
{
readXML();
lblStatus.Text = "";
}

protected void butAdd_Click(object sender, EventArgs e)
{
try
{
XDocument xmlDoc = XDocument.Load(Server.MapPath("People.xml"));

xmlDoc.Element("Persons").Add(new XElement("Person", new XElement("Name", txtName.Text),
new XElement("City", txtCity.Text), new XElement("Age", txtAge.Text)));

xmlDoc.Save(Server.MapPath("People.xml"));
lblStatus.Text = "Data successfully added to XML file.";
readXML();
}
catch
{
lblStatus.Text = "Sorry, unable to process request. Please try again.";
}
}
We tell the read button to call another method when it is clicked because we can reuse it - notice we call the same method at the end of the add button. This is so we can update the displayed XML when we add new content. We are using LINQ to open the XML document first, and then add a new element into the parent element of Persons. Then we save changes to the XML file and let the user know.
The readXML method looks like this:

protected void readXML()
{
XDocument xmlDoc = XDocument.Load(Server.MapPath("People.xml"));

var persons = from person in xmlDoc.Descendants("Person")
select new
{
Name = person.Element("Name").Value,
City = person.Element("City").Value,
Age = person.Element("Age").Value,
};

litResults.Text = "";
foreach (var person in persons)
{
litResults.Text = litResults.Text + "Name: " + person.Name + "<br />";
litResults.Text = litResults.Text + "City: " + person.City + "<br />";
litResults.Text = litResults.Text + "Age: " + person.Age + "<br /><br />";
}

if (litResults.Text == "")
litResults.Text = "No Results.";
}
As you can see, LINQ looks similar to SQL, but instead of communicating with a database only, we can use LINQ to communication with any data source - in this case an XML file. First we declare a variable persons and assign to it the collection from the XML file's descendants, Person. Then we select all the data from within and simply loop through our collection and output to the literal control.

Monday, October 3, 2011

LINQ to SQL


What is LINQ TO SQL ?
LINQ to SQL is new component that is released with .NetFramework 3.5. LINQ to SQL provides a way where a developer can manage a relational database object as a .net object. In simple terms, it is an ORM (Object-relational mapping) that is used to manage a back end object as a front end object in object oriented way i.e. relational to object oriented type system.
We can query, insert, update and delete the underlying database object with LINQ to SQL classes.  When we query or update or delete these .net objects, LINQ to SQL will automatically take care of the operations in underlying relational data objects.


LINQ to SQL uses LINQ as querying technique to query the database object through the LINQ to SQL.

What is LINQ?
LINQ stands for Language Integrated Query.  LINQ is a data querying methodology which provides querying capabilities to .Net languages with syntax similar to SQL query. LINQ has a set of querying operators that can be used to query in memory object collection, Sql database, XML, etc. LINQ processing engine will then convert the LINQ query to native query specific to the database to execute against the datasource.  Since, the querying feature is integrated with the language; one can build an efficient query based on the language of their choice.  With Visual Studio, we have intellisense support and with language support, we have type safety and compile-time error checks.

There are many advantages when we use ORM in our projects. Below are few,
1.      You can query the database object treating it as a .net object using .net language.
2.      Your data access development will be easier.
3.      It handles the SQL injection attacks automatically.
4.      You will get type safety and compiler advantages since the database objects are managed as .net object.
5.      Using Visual Studio provides you intellisense support and other tools for developing the LINQ to SQL classes

Constructing your first LINQ to class
Visual studio 2008 is packed with tool called LINQ to SQL designer which will help us to build the LINQ to SQL classes very easily.

LINQ to SQL designer
It is a new designer to design relational database object as LINQ to SQL objects.  We can either, drag and drop database object from “Server Explorer” or, we can design the LINQ to SQL object manually using the designer and tools.

To understand better, we will create two simple tables, Employee and Department, will design our LINQ to SQL class.

Open Visual Studio 2008, Click File >Website and choose ASP.Net Website. Choose the language of your choice and name your website according to your need.

In solution explorer, right the project and select “Add New Item”. Select “LINQ to SQL classes” as shown in below figure. I have named it as EmployeeInfo.
 What is LINQ to SQL?
This will add an EmployeeInfo.dbml file inside “App_Code” folder.  In Visual Studio, EmployeeInfo.dbml will have 2 panes. The left pane is for deigning the data objects and the right pane can be used for creating methods that operates on the data objects.
The Visual Studio toolbar will contain a new toolbar for designing LINQ to SQL objects. Refer below,
 What is LINQ to SQL?
We will see more about using these toolbar to create our own object in future articles. Once we include the LINQ to SQL Class in the project, there will be 3 files added to the App_Code.

EmployeeInfo.dbml
An XML file that contains information about the tables like table name, column name, type, etc
EmployeeInfo.layout
An XML file that specifies how the designer places the objects.
EmployeeInfo.designer.cs
The C# code file that will have code to interact with the underlying database called DataContext object. It also has entity class definition.

Designing the LINQ to SQL classes
Open Server Explorer, Expand the database tables.
Drag Employee and Department into LINQ to SQL designer and click Save. The Objects will be created automatically. Refer the below figure.

 What is LINQ to SQL?

This will update the EmployeeInfo.designer.cs file with class definition for Employee and Department. It will also generate the DataContext object for these objects for interacting with the underlying datasource i.e. it is with the help of this DataContext class we can interact with the database objects in our managed environment. In our case, it is EmployeeInfoDataContext.

The arrow between the object is the foreign key relationship between them. This means that the Employee class will have the Department class as a member.

Thus, we have modelled LINQ to SQL classes which has O/R mapping. Moving forward, we will see how we can we use these objects to do our data access.

Using LINQ to SQL classes
The below code will fetch all the employees rows and will populate a GridView control.
EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();
        var LINQQuery = from emp in dbEmp.Employees
                        select emp;
        gvEmployee.DataSource = LINQQuery;
        gvEmployee.DataBind();


Updating Employee Information
The below code uses the LINQ to SQL class to update the employee information whose employee id is fetched from txtEmpID.
EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();       
        string EmpID = txtEmpID.Text;           
        Employee empTemp = (from emp in dbEmp.Employees
                           where emp.EmpID == int.Parse(EmpID)
                           select emp).Single();
     
         empTemp.EmpName = txtEmpName.Text;       
         empTemp.DeptID = int.Parse(ddlTemp.SelectedValue);      
         empTemp.Age = int.Parse(txtAge.Text);       
         empTemp.Address = txtAddr.Text;
       
dbEmp.SubmitChanges();






Deleting a Row
EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();      
        string EmpID = null;      
        EmpID = txtEmpID.Text;
        Employee empTemp = (from emp in dbEmp.Employees
                            where emp.EmpID == int.Parse(EmpID)
                            select emp).Single();
        dbEmp.Employees.DeleteOnSubmit(empTemp);
        dbEmp.SubmitChanges();

Inserting a new Row
EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();
        Employee emp = new Employee();      
       emp.EmpName = txtEmpName.Text;     
       emp.DeptID = int.Parse(ddlTemp.SelectedValue);     
       emp.Age = int.Parse(txtAge.Text);     
       emp.Address = txtAddr.Text;
       dbEmp.Employees.InsertOnSubmit(emp);
       dbEmp.SubmitChanges();