Wednesday, March 24, 2010

Custom Error Handling in ASP.NET

.Net provides number of ways to manage and handle errors. Generally we use try..catch block to handle the error and show the error message in a label. Instead of showing the error in that page, we can show the error in another page with the customized manner, so that it can be seem more professional.

Steps:

1.Create an ASP.NET web site.
2.Add a class ErrorPage.cs in the App_Code folder.
3.Add the following variable in the ErrorPage.cs file

//Declare the private HttpApplication variable
private HttpApplication _application;

void IHttpModule.Init (HttpApplication application)
{
_application = application;

//check whether the ErrorHandling values is Application type set in the web.config
//file or not. If yes then declare an EventHandler 
if (GetValue("ErrorHandling") == "Application")
_application.Error += new EventHandler(ErrorPageHandler);

}


private void ErrorPageHandler(Object sender, EventArgs e)
{
//fetch the error
ProcessException(_application.Server.GetLastError());
}

//store the error in the Cache
private void ProcessException(Exception exception)
{
HttpContext.Current.Cache["Error"] = HttpContext.Current.Request.Url.ToString();
HttpContext.Current.Cache["ErrorMsg"] = exception.Message;
HttpContext.Current.Cache["StackTrace"] = exception.StackTrace;

HttpContext.Current.Response.Redirect(GetValue("SiteUrl") + "/Error.aspx");
}


//fetch the value from the web.config file
public string GetValue(string Key)
{
string ret = System.Web.Configuration.WebConfigurationManager.AppSettings[Key];

return ret;
}
public void Dispose()
{
}


4.Create an Error.aspx page and add the following html code
<asp:table width="100%" align="center" >

<asp:tr>
<asp:td style="text-align: left; font-weight: bold">
Error In
<asp:/td>
<asp:/tr>
<asp:tr>
<asp:td  style="text-align: left; font-weight: bold">
<asp:asp:Label ID="lblError" runat="server" CssClass="x-panel-mc-font"><asp:/asp:Label>
<asp:/td>
<asp:/tr>
<asp:tr>
<asp:td  style="text-align: left; font-weight: bold">
  
<asp:/td>
<asp:/tr>
<asp:tr>
<asp:td style="text-align: left; font-weight: bold">
Error Message
<asp:/td>
<asp:/tr>
<asp:tr>
<asp:td  style="text-align: left;">
<asp:asp:Label ID="lblErrorMsg" runat="server" CssClass="x-panel-mc-font"><asp:/asp:Label>
<asp:/td>
<asp:/tr>
<asp:tr>
<asp:td  style="text-align: left;">
  
<asp:/td>
<asp:/tr>
<asp:tr>
<asp:td style="text-align: left; font-weight: bold">
Stack Track
<asp:/td>
<asp:/tr>
<asp:tr>
<asp:td  style="text-align: left;">
<asp:asp:Label ID="lblStackTrace" runat="server" CssClass="x-panel-mc-font"><asp:/asp:Label>
<asp:/td>
<asp:/tr>
<asp:tr>
<asp:td  style="text-align: left;">
  
<asp:/td>
<asp:/tr>
<asp:/table>



Here I have used 3 lables to show the page name (from where error is generated), Error Message and Stack Track.

5.Add the following code in the Error.aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (Cache["Error"] != null)
lblError.Text = Cache["Error"].ToString();
if (Cache["ErrorMsg"] != null)
lblErrorMsg.Text = Cache["ErrorMsg"].ToString();
if (Cache["StackTrace"] != null)
lblStackTrace.Text = Cache["StackTrace"].ToString();

}


Fetched the errors from the Cache and showing in the labels.

6.In the default.aspx page add a button control, and add the following code in the button click event.

int a = 1, b = 0;
int c = a / b;


Generating the error.

7.Add the following setting in the web.config file

<asp:appSettings>
<asp:add key="SiteUrl" value="http://localhost:1371/CustomeErrorHandling"/>
<asp:add key="ErrorHandling" value="Application"/>
<asp:/appSettings>


And add in the <httpModules> section

<asp:add type="ErrorPage" name="ErrorPageHandler">


8.Now run the application



9.Click on the Show Error button, then the error will be show in the following manner.



Note: Do not use try..catch block in the code behind page, If you use then custome error will not work. i.e. If I write the code in the following manner
try
{
int a = 1, b = 0;
int c = a / b;
}
catch
{ }

Then the error page will not show.

Download :

Thursday, August 27, 2009

Use header checkbox in GridView in ASP.NET

Here I am going to give you a very easy steps to use the checkbox in the header of the Gridview in ASP.NET.




Steps:
1. I have created a class “Customer” and fill the gridview with the collection of customers.


public class Customer

{

int id;
string name;
string city;

public string City
{
get { return city; }
set { city = value; }
}

public string Name
{
get { return name; }
set { name = value; }
}

public int Id
{
get { return id; }
set { id = value; }
}

public Customer(int customerID, string customerName, string customerCity)
{

id = customerID;
name = customerName;
city = customerCity;
}

}


2.Created a gridview in the default.aspx page


<asp:GridView ID="dgridCustomer" runat="server" AutoGenerateColumns="false" Width="592px">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
 
<input type="checkbox" class="chkHeader" id="HeaderCheckBox" onclick="javascript:Check(this)" name="ItemCheckBox" runat="Server" />
</HeaderTemplate>
<ItemTemplate>
<input type="checkbox" value='<%# DataBinder.Eval(Container.DataItem, "Id") %>' class="chkItem"
id="ItemCheckBox" name="ItemCheckBox" runat="Server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "City") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>



3.To fill the gridview following functions has been used in default.aspx.cs file

protected void Page_Load(object sender, EventArgs e)

{

lblMsg.Visible = false;

if (IsPostBack) return;

FillCustomer();

}

private void FillCustomer()
{
List obCustomers = new List();

obCustomers = GetAllCustomers();

Session["Customers"] = obCustomers;

dgridCustomer.DataSource = obCustomers;
dgridCustomer.DataBind();
}

private List GetAllCustomers()
{
List obCustomers = new List();

Customer obCustomer = new Customer(1, "name1", "city1");
obCustomers.Add(obCustomer);

obCustomer = new Customer(2, "name2", "city2");
obCustomers.Add(obCustomer);

obCustomer = new Customer(3, "name3", "city3");
obCustomers.Add(obCustomer);

obCustomer = new Customer(4, "name4", "city4");
obCustomers.Add(obCustomer);

obCustomer = new Customer(5, "name5", "city5");
obCustomers.Add(obCustomer);

return obCustomers;

}



4.When header checkbox of the gridview is clicked then all the item checkboxes should be checked and if header checkbox is unchecked then all the item checkboxes should be unchecked. To do this I have created a javascript function and added in the default.aspx page.

 function Check(varchk)

{

var objInputs = document.getElementsByTagName('input')
for(i=0;i {
if(varchk.checked)
{
if(objInputs[i].className==='chkItem')
{
objInputs[i].checked=true;
}
}
else
{
if(objInputs[i].className==='chkItem')
{
objInputs[i].checked=false;
}
}
}
}


5.Remove all the checked record from the gridview, the following method has been used
in the Remove button.

 protected void btnRemove_Click(object sender, EventArgs e)

{
List obCollection = (List)Session["Customers"];

foreach (GridViewRow row in dgridCustomer.Rows)
{
System.Web.UI.HtmlControls.HtmlInputCheckBox chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)dgridCustomer.Rows[row.RowIndex].FindControl("ItemCheckBox");

if (chk.Checked)
{
Customer obCustomer = obCollection.Find(delegate(Customer obj) { return obj.Id == Convert.ToInt32(chk.Value); });

obCollection.Remove(obCustomer);

lblMsg.Visible = true;

lblMsg.Text = "Customer information deleted successfully.";
}
}

dgridCustomer.DataSource = obCollection;
dgridCustomer.DataBind();

}



Below method is used to find the checked item from the collection.

Customer obCustomer = obCollection.Find(delegate(Customer obj) { return obj.Id == Convert.ToInt32(chk.Value); });




Download :



Saturday, August 1, 2009

Decorator Pattern

There are numbers of way we used in the designing software application. These ways are called Patterns, and in the object-oriented programming, we use so many patterns. Decorator Pattern is a design pattern in the object-oriented programming that allows us to add the new functionality in the existing class dynamically. To understand let me give you a simple example. Suppose you have an application in ASP.NET and SQL Server.
In your business logic, you have written all you logics. i.e.

1. Insert()
2. Update()
3. Delete
4. Get()

In these logics, you have written the code according to your SQL Server fetching technique. You have used System.Data.SqlClient and open/close the connection with SQL Server and done all the insert/update/delete opertaions with SQL Server. You have also called this business logic objects into your UI layer. Now your application is fully dependent in SQL Server. The problem start now, you have a single application where you have done your all effort with the SQL Server and the new requirement is you have to also provide the support of the Microsoft Access with the same database and UI. Then what will you do? You have to create the another business logic with the Microsoft Access as well as have to change all the logic of UI layer because it is accessing the SQL Server business layer logic right now. It will force you rethink again in your design pattern. In such type of situation Decorator Pattern help you to get up. Let me make it simpler. Suppose, I have an asp.net .aspx page where I have to show all products information. Remember we have two databases one is in SQL Server, another is in Microsoft Access, and we have to write the code in a single UI. At the run time, we can decide which database we have to use. First, I will create an interface IProduct. (Here I am using a console application.)

public interface IProduct
{
bool Insert(int id, string name);
bool Update(int id, string name);
bool Delete(int id);
string GetRecords();
}

Then I have to create a Product class which will contains all the operations with SQL Server database. This Product class will inherits the IProduct interface.


public class ProductSQLServer : IProduct 
{
int id = 10;
string name = "SQL Server";

#region IProduct Members

public bool Insert(int id, string name)
{

//insert logic

return true;

}

public bool Update(int id, string name)
{
//upate logic
return true;
}

public bool Delete(int id)
{
//delete login
return true;
}

public string GetRecords()
{
return "sql server : id=" + id + " name=" + name ;
}

#endregion

}


public class ProductMicrosoftAccess : IProduct
{
int id = 10;
string name = "MicrosoftAccess";

#region IProduct Members

public bool Insert(int id, string name)
{
//insert into the microsoft access
return true;
}

public bool Update(int id, string name)
{
//update in the microsoft access
return true;
}

public bool Delete(int id)
{
//delete from the microsoft access
return true;
}

public string GetRecords()
{
return "MicrosoftAccess : id=" + id + " name=" + name ;
}

#endregion
}


Now in the UI layer we can decide in the run time what type of object (SQL Server/Access) need to be accessed.

In the view product.aspx page I can decide whether I want to create the object of ProductMicrosoftAccess class or ProductSQLServer class.
For that you have to use the IProduct interface


static void Main(string[] args)
{
IProduct  obOperation = new ProductMicrosoftAccess();

Console.WriteLine(obOperation.GetRecords());

obOperation = new ProductSQLServer();

Console.WriteLine(obOperation.GetRecords());


Console.ReadLine();
}


You can choose the type of database by setting the key in your web.config file or any configuration file.




Download :

Monday, July 20, 2009

ADO.NET Entity Framework

Introducing the ADO.NET Entity Framework

During the development with the database and ADO.NET, we use some traditional way. First we create the database tables and their relationships and then create the classes in the code for business layer. We write our business logic in these classes and performs different operations on the database though these classes. Most of the developers have to do the complex code to move the data between the application and the database. However, to write such type of the code develops must have the database knowledge. In this type of development we generally do not care about the database concepts in our code. Now the Microsoft has introduced the concept of Entity Framework Model where it deals with the database tables as en entity and allows us to write and maintain the code according to the database concepts. Using the entity relationship modeling, developers create the conceptual model of the data and write their code against this model. So we can say “ADO.NET Entity Framework Model allows you to deal with database concepts in your code."
ADO.NET Entity framework intended to make the development easier and more effective for object-oriented application to work with data.





The Entity Framework architecture




The ADO.NET Entity Framework is a layered framework which abstracts the relational schema of a database and presents a conceptual model.

Data Source: The bottom layer is the data which can be stored in one or many databases.

Data Providers: The data will be accessed by a ADO.NET data provider. At this moment only SQL Server is supported but in the near future there will be data providers for Oracle, MySQL, DB2, Firebird, Sybase, VistaDB, SQLite.

Entity Data Model (EDM): The Entity Data Model consists of 3 parts :
Conceptual schema definition language (CSDL) : Declare and define entities, associations, inheritance, ... Entity classes are generated from this schema.
Store schema definition language (SSDL) : Metadata describing the storage container (=database) that persists data.
Mapping specification language (MSL) : Maps the entities in the CSDL file to tables described in the SSDL file.

Entity Client: EntityClient is an ADO.NET managed provider that supports accessing data described in an Entity Data Model. It is similar to SQLClient, OracleClient and others. It provides several components like EntityCommand, EntityConnection and EntityTransaction.

Object Services: This component enables you to query, insert, update, and delete data, expressed as strongly-typed CLR objects that are instances of entity types. Object Services supports both Entity SQL and LINQ to Entities queries.

Entity SQL (ESQL): Entity SQL is a derivative of Transact-SQL, designed to query and manipulate entities defined in the Entity Data Model. It supports inheritance and associations. Both Object Services components and Entity Client components can execute Entity SQL statements.

LINQ to Entities: This is a strong-typed query language for querying against entities defined in the Entity Data Model.



DATABASE MODELING LAYERS

Common design pattern for data modeling is the division of the data model into three parts: a conceptual model, a logical model, and a physical model

1.Physical Data Model: This model describes how data are represented in the physical resources such as memory, wire or disk. The vocabulary of concepts discussed at this layer includes record formats, file partitions and groups, heaps, and indexes. The physical model is typically invisible to the application –applications

2.Logical/Relational Data Model: The concepts discussed at the logical level include tables, rows, and primary key-foreign key constraints, and normalization.




3.Conceptual Model: The conceptual model captures the core information entities from the problem domain and their relationships. conceptual model is the Entity-Relationship Model. UML is a more recent example of a conceptual model




Why Entity Framework is used/ADO.NET Entity Data Model

Entity Framework maps relational tables, columns, and foreign key constraints in logical models to entities and relationships in conceptual models. The Entity Data Model tools generate extensible data classes based on the conceptual model. These classes are partial classes that can be extended with additional members that the developer adds. The classes that are generated for a particular conceptual model derive from base classes that provide Object Services for materializing entities as objects and for tracking and saving changes. Developers can use these classes to work with the entities and relationships as objects related by navigation properties.

Object Services: Object Services is a component of the Entity Framework that enables you to query, insert, update, and delete data, expressed as strongly typed CLR objects that are instances of entity types. Object Services supports both Language-Integrated Query (LINQ) and Entity SQL queries against types that are defined in an Entity Data Model (EDM).
Entity framework enables application to access and change the data that is represented as entities and relationship in the conceptual model. Object Services uses the EDM to translate object queries against entity types that are represented in the conceptual model into data source-specific queries. Query results are materialized into objects that Object Services manages. The Entity Framework provides the following ways to query an EDM and return objects:

• LINQ to Entities - provides Language-Integrated Query (LINQ) support for querying entity types that are defined in a conceptual model.

• Entity SQL - a storage-independent dialect of SQL that works directly with entities in the conceptual model and that supports EDM features such as inheritance and relationships. Entity SQL is used both with object queries and queries that are executed by using the EntityClient provider. For more information, see Entity SQL Overview.

• Query builder methods - enables you to construct Entity SQL queries using LINQ-style query methods. For more information, see Query Builder Methods (Entity Framework).

The Entity Framework includes the EntityClient(The EntityClient provider is a data provider used by Entity Framework applications to access data described in an Entity Data Model (EDM)) data provider. This provider manages connections, translates entity queries into data source-specific queries, and returns a data reader that Object Services uses to materialize entity data into objects. When object materialization is not required, the EntityClient provider can also be used like a standard ADO.NET data provider by enabling applications to execute Entity SQL queries and consume the returned read-only data reader.
The following mythology is used generally




If you use the Entity Framework concept then the result would be





Thus we can say the ADO.NET Entity Framework provide the abstraction layer between the logical data model and application domain. When you will generate the logical tables to entity data diagram, it combines multiple data tables to one entity.

NET 3.5 SP1 includes the new ADO.NET Entity Framework, which allows developers to define a higher-level Entity Data Model over their relational data, and then program in terms of this model. Concepts like inheritance, complex types and relationships can be modeled using it.



Scheme file (EDMX)

If can also see the EDMS file as XML. To see the xml file open the solution explorer, right click on .EDMS file, select Open With XML Editor.




Now you can see here 3 sections
1. Conceptual Model (CSDL)
2. Storage Model (SSDL)
3. Mapping (MSL)

<?xml version="1.0" encoding="utf-8"?>

<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
<edmx:Runtime>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema Namespace="NorthwindModel" Alias="Self" xmlns="http://schemas.microsoft.com/ado/2006/04/edm">
<EntityContainer Name="NorthwindEntities">
<EntitySet Name="Employees" EntityType="NorthwindModel.Employee" />
<AssociationSet Name="FK_Orders_Employees" Association="NorthwindModel.FK_Orders_Employees">
<End Role="Employees" EntitySet="Employees" />
<End Role="Orders" EntitySet="Orders" />
</AssociationSet>
</EntityContainer>
<EntityType Name="Employee">
<Documentation><Summary>Employee entity which corresponds with the Northwind.Employees table</Summary></Documentation>
<Key>
<PropertyRef Name="EmployeeID" />
</Key>
<Property Name="EmployeeID" Type="Int32" Nullable="false" />
<Property Name="LastName" Type="String" Nullable="false" MaxLength="20" />
<Property Name="FirstName" Type="String" Nullable="false" MaxLength="10" />
<NavigationProperty Name="Orders" Relationship="NorthwindModel.FK_Orders_Employees" FromRole="Employees" ToRole="Orders" />
</EntityType>
</Schema>
</edmx:ConceptualModels>

<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="NorthwindModel.Store" Alias="Self" ProviderManifestToken="09.00.1399"
xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl">
<EntityContainer Name="dbo">
<EntitySet Name="Employees" EntityType="NorthwindModel.Store.Employees" />
<AssociationSet Name="FK_Orders_Employees" Association="NorthwindModel.Store.FK_Orders_Employees">
<End Role="Employees" EntitySet="Employees" />
<End Role="Orders" EntitySet="Orders" />
</AssociationSet>
</Schema>
</edmx:StorageModels>

<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS">
<EntityContainerMapping StorageEntityContainer="dbo" CdmEntityContainer="NorthwindEntities">
<EntitySetMapping Name="Employees">
<EntityTypeMapping TypeName="IsTypeOf(NorthwindModel.Employee)">
<MappingFragment StoreEntitySet="Employees">
<ScalarProperty Name="EmployeeID" ColumnName="EmployeeID" />
<ScalarProperty Name="LastName" ColumnName="LastName" />
<ScalarProperty Name="FirstName" ColumnName="FirstName" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<AssociationSetMapping Name="FK_Orders_Employees" TypeName="NorthwindModel.FK_Orders_Employees" StoreEntitySet="Orders">
<EndProperty Name="Employees">
<ScalarProperty Name="EmployeeID" ColumnName="EmployeeID" />
</EndProperty>
<EndProperty Name="Orders">
<ScalarProperty Name="OrderID" ColumnName="OrderID" />
</EndProperty>
<Condition ColumnName="EmployeeID" IsNull="false" />
</AssociationSetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
</edmx:Edmx>

When you build your project, MSBuild will extract the CSDL/SSDL/MSL content from the EDMX file and places these 3 seperate XML files in your project output directory.



Model View

The Model Browser window can be used to visualize the conceptual model and storage model in a well-organized tree hierarchy.





• Conceptual Model
o Entity Types : Employee
o Associations : FK_Orders_Employees
o Entity Container
1. Entity Sets : Employees
2. Association Sets
3. Function Imports

• Storage Model
o Tables / Views : Employees
o Stored Procedures
o Constraints




Generating an Entity Data Model in Your Visual Studio Project

The very first step you have to generate the Entity Data Model for your database. Here I am using the asp.net web application to create the sample of the Entity Data Mode.
Right click on sample project -> Add -> New Item -> ADO.NET Entity Data Model




Changed the model name to EntityDataModel.edmx






Select the Generate from database and click on Next




Select your database connection or create New Connection. And click on Next button



You can select objects (Tables, Vies, Stored Procedures) from this window. Then click on the Finish button. Blow is the graphical representation of the Entity Data Mode (EDM) that is generated by the wizard.




Here I have created a .aspx page to fetch all the categories from the database with the Entity Framework Model and showing the products in the gridview by the selected category.
The .aspx page is
 <table width="100%">

<tr>
<td align="right" >
Category :
</td>
<td>
<asp:DropDownList ID="drpCategory" runat=server AutoPostBack=true
onselectedindexchanged="drpCategory_SelectedIndexChanged" ></asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2" align="center" style="padding-top:10px" >
<asp:GridView ID="dgridProducs" Width="90%" runat=server ></asp:GridView>
</td>
</tr>
</table>


Code:

NORTHWNDEntities obNORTHWNDEntities = new NORTHWNDEntities();


protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
FillCategories();
}

private void FillCategories()
{
try
{
drpCategory.DataSource = obNORTHWNDEntities.Categories;
drpCategory.DataTextField = "CategoryName";
drpCategory.DataValueField = "CategoryID";
drpCategory.DataBind();
}
catch
{
throw;
}
}


protected void drpCategory_SelectedIndexChanged(object sender, EventArgs e)
{
int categoryID =Convert.ToInt32(drpCategory.SelectedValue);

IQueryable<Products> products = from c in obNORTHWNDEntities.Products
where c.Categories.CategoryID == categoryID
select c;


dgridProducs.DataSource = products;
dgridProducs.DataBind();
}
}


Here obNORTHWNDEntities represent the NORTHWNDEntities context. To fill all the categories into the DrowDownList the FillCategories() is used. To fetch all the product of the selected categories, called the SelectedIndexChanged of the dropdownlist.





How to: Add, Modify, and Delete Objects (Entity Framework)

Here I have created an Employee page where you can add, modify and delete a new employee from the database through the Entity Framework.





To show all the employees the FillEmployees() has been called on the page load event.

 private void FillEmployees()

{
dgridEmployee.DataSource = obNORTHWNDEntities.Employees;
dgridEmployee.DataBind();
}


To add the new employee AddNewEmployee() has been used.

 private void AddNewEmployee()

{
Employees obEmployee = new Employees();

obEmployee.EmployeeID = -1;

obEmployee.FirstName = txtFirstName.Text.Trim();

obEmployee.LastName = txtLastName.Text.Trim();

obEmployee.City = txtCity.Text.Trim();

obEmployee.Country = txtCountry.Text.Trim();

obNORTHWNDEntities.AddToEmployees(obEmployee);

obNORTHWNDEntities.SaveChanges();

}


Since this the new employee that’s why the employeeID has been assigned to -1. After assigning all the values to the new employee object it has to be added to the obNORTHWNDEntities context through the AddToEmployees() method. To save the employee to the database SaveChanges() is called.

For modifying the employee, the EditEmployee() functions has been called.
 private void EditEmployee()

{

Employees obEmployee = new Employees();

int employeeId = Convert.ToInt32(hdnEmployeeId.Value);


//IQueryable<Employees> employees = from c in obNORTHWNDEntities.Employees
// where c.EmployeeID == employeeId
// select c;

//List<Employees> obCollection = employees.ToList<Employees>();

//obEmployee = obCollection[0];

//IQueryable<Employees> emp = obNORTHWNDEntities.Employees.Where("it.EmployeeID=" + employeeId);

//obEmployee = emp.First();

obEmployee = obNORTHWNDEntities.Employees.Where("it.EmployeeID=" + employeeId).First();

obEmployee.FirstName = txtFirstName.Text.Trim();

obEmployee.LastName = txtLastName.Text.Trim();

obEmployee.City = txtCity.Text.Trim();

obEmployee.Country = txtCountry.Text.Trim();

hdnEmployeeId.Value = string.Empty;


obNORTHWNDEntities.SaveChanges();
}


First of all the modified employees information is fatched.

obEmployee = obNORTHWNDEntities.Employees.Where("it.EmployeeID=" + employeeId).First();



you can also use the following code to fetch the employee information

//IQueryable<Employees> employees = from c in obNORTHWNDEntities.Employees

// where c.EmployeeID == employeeId
// select c;

//List<Employees> obCollection = employees.ToList<Employees>();

//obEmployee = obCollection[0];

After assinging the modified values you need to call the obNORTHWNDEntities.SaveChanges().


Use stored procedure with ADO.NET Entity Framework

1. Create the stored procedure to fetch all the orders of a customer


Create PROCEDURE [dbo].[GetOrderByCustomer] 

@CustomerID nchar(5)
AS
SELECT *
FROM Orders
WHERE CustomerID = @CustomerID
ORDER BY OrderID


2. Now you have to import this stored procedure to your EDM. There are two ways: first you have to regenerate the EDM and import is via the designer, or in second way you can edit the xml file directly. Here we are using the first method.

a. Right click on the Entity Designer View and click on the Update Model from Database.





b. Choose the newly created stored procedure what you want to include.



3. Go to the Model Browser and search the newly imported stored procedure
4. Right click on that stored procedure and then click on Create Function Import.



5. A new Add Function Import window will be opened. Here select the Entities to Orders. Since this function returns the order list.




To fetch all the orders of a customer the above stored procedure is used in the c# code.

private void FillOrder()
{
using (NORTHWNDEntities obNORTHWNDEntities = new NORTHWNDEntities())
{
ObjectResult<Orders> objectResultOrder = obNORTHWNDEntities.GetOrderByCustomer("ALFKI");

dgridOrder.DataSource = objectResultOrder;
dgridOrder.DataBind();

}
}



Mapping the stored procedure

1. Create the stored procedure to insert the new employee


CREATE PROCEDURE InsertEmployee

@FirstName nvarchar(20)
,@LastName nvarchar(20)


AS
BEGIN


INSERT INTO EMPLOYEES
(
FirstName
,LastName

)
VALUES
(
@FirstName
,@LastName
)


SELECT MAX(EmployeeID) as NewEmployeeID FROM Employees


END
GO


2. Right click on the Employee entity on the EDM and click on Stored Procedure Mapping.





Once you click on that, you will see the Mapping Details window



Here you can map your insert, update and delete stored procedure. Now you have insertEmployee stored procedure to map this procedure click on the <Select Insert Function> then select the InsertEmployee stored procedure from the dropdownlist box.





Difference between LINQ to SQL and Entity Framework


LINQ to SQL is an object-relational mapping (ORM) framework that allows the direct 1-1 mapping of a Microsoft SQL Server database to .NET classes, and query of the resulting objects using LINQ. More specifically, LINQ to SQL has been developed to target a rapid development scenario against Microsoft SQL Server where the database closely resembles the application object model and the primary concern is increased developer productivity. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5.

• LINQ to SQL supports a wide breadth of abstractions
• LINQ to SQL support domain Model
• Linq to SQL is only for SQL
• LINQ to SQL is simple to use
• LINQ to SQL is used for rapid development.
• LINQ to SQL class uses the mapping only for the single table
• LINQ to SQL generate only dbml file


LINQ to Entities (ADO.Net Entity Framework) is an ORM (Object Relational Mapper) API which allows for a broad definition of object domain models and their relationships to many different ADO.Net data providers. As such, you can mix and match a number of different database vendors, application servers or protocols to design an aggregated mash-up of objects which are constructed from a variety of tables, sources, services, etc. ADO.Net Framework was released with the .Net Framework 3.5 SP1.

• Entity framework supports a high level of abstraction.
• Entity framework support conceptual data mode.
• Entity Framework will have ability to target different database engines in addition to Microsoft SQL Server.
• Entity framework is complex to use.
• Entity framework is slower development but has more capabilities.
• Entity framework map a single class to multipal tables
• Entity framework generate the three xml files csdl, msl and ssdl.


Reference:
http://blogs.msdn.com/adonet/archive/2007/05/30/entitysql.aspx
http://msdn.microsoft.com/en-us/library/bb399567.aspx



Tuesday, May 12, 2009

Read and Write from the xml file with C# / ASP.NET

In this article I have created different methods to read and write from the xml files.
Here are two applications one is class library where I have put all the methods to read and write the xml files and another is a web site.

Example-1: Read the xml file

Here is a Config.xml file in the XMLFile folder. The structure of the file is

<?xml version="1.0" encoding="utf-8" ?>
<root>
<!-- site url-->
<SiteUrl> http://www.site.com</SiteUrl>
<!-- file path-->
<FilePath> c:\\myfolder</FilePath>
<!-- domain name-->
<DomainName> mydoman.com</DomainName>
</root> 


Here I have put some comments also. To read this file I have created a class Configure.cs in the class liberary.
To read the element of the xml file I have used the document.GetElementsByTagName() method.

public void GetValues()
{
  XmlDocument document = new XmlDocument();
  XmlNode node = null;
  try
  {
   if (String.IsNullOrEmpty(path))
   {
    return;
   }
  document.Load(path);
  node = document.GetElementsByTagName("SiteUrl").Item(0);
  this.siteUrl = node.InnerText;
  node = document.GetElementsByTagName("FilePath").Item(0);
  this.FilePath = node.InnerText;
  node = document.GetElementsByTagName("DomainName").Item(0);
  this.domainName = node.InnerText;
 }
 catch
 {
  throw;
 }
 finally
 {
  document = null;
  node = null;
 }
}





To write to this file I have created WriteToFile(string filePath, string fileStreamData), where you have to pass the xml file path and data (may be the xml data in string format). For example I have used this function to create the country1. xml file with node "Mydata" in the default.aspx.cs page.


private void WriteToFile()
{
  ReadWriteXMLClassLib.Configure obConfigure = new ReadWriteXMLClassLib.Configure();

  obConfigure.WriteToFile(Server.MapPath("XMLFiles/Country1.xml"), "Mydata");

}


Example-2: Read the xml file

In the previous example there was a no repetition of elements in the file but in this example the xml file structure is different. Here are number of sub nodes or elements (Employee) are more than one and also added the attribute “id” to each sub node.

< ?xml version="1.0" encoding="utf-8" ? >
<?xml version="1.0" encoding="utf-8" ?>
< Employees>
< Employee id="1" >
< Name>Pankaj Saha< /Name>
< Age>26< /Age>
< Address>
< City>Baroda< /City>
< State>Gujaraat< /State>
< /Address>
< /Employee>
< Employee id="2" >
< Name>Sanjay< /Name>
< Age>27< /Age>
< Address>
< City>Baroda< /City>
< State>Gujaraat< /State>
< /Address>
< /Employee>
< /Employees>


To read this xml file I have created a class FileOperataion.cs in the class library. If there is only one Employee node then you can read this node value only with ReadXmlSubNodeValue() method. Since there are multiple nodes that’s why I have used ReadXmlNodeList() method to read all the node list of Employees and then fetch each node of Employees and get the value of each node of Employee through the ReadXmlSubNodeValue() method.



Example-3: Read the xml file

In this example I have used an xml file with the following format

< ?xml version="1.0" encoding="utf-8" ?>
< Countries>
< Country id="1" >India< /Country>
< Country id="2" >US< /Country>
< Country id="3" >Uk< /Country>
< /Countries>



Here each node has an attribute id and each attribute has different values. Now I need to get the node value by their attribute value, for that I have used the ReadXmlNodeList(string fileName, string xmlPath) method to get the node list and then pass each node to ReadXmlSubNodeValue(XmlNode node, string xPath, string attributeName, string attributeValue) method to get values of specific node. For example if you need to get the country which has id=1 then you can use GetCountry(1) method.

private void GetCountry(int countryId)
{
  ReadWriteXMLClassLib.FileOperataion obFileOperataion = new ReadWriteXMLClassLib.FileOperataion();

  XmlNodeList obNodeList = obFileOperataion.ReadXmlNodeList(Server.MapPath("XMLFiles/Country.xml"), "//Countries");

  if (obNodeList != null)
  {
   foreach (XmlNode obNode in obNodeList)
  {
   tdContry.InnerHtml = obFileOperataion.ReadXmlSubNodeValue(obNode, "Country", "id", countryId.ToString());
  }
 }
}



Example-4: Fill gridview from xml file

In this example I have used the country.xml file. You can see in the Example4.aspx page where I have used to read the xml file to the dataset and assigned that dataset to the gridview. To read the xml file I have used the following function

public DataSet GenerateDataSet(string filePath)
{
  DataSet objDataSet = new DataSet();

  objDataSet.ReadXml(filePath);

  return objDataSet;
}



In this function you have to pass the xml file path. You can also pass the xml string, for this you have to use the following function

public DataSet GenerateDataSetWithString(string inputXmlString)
{
  DataSet objDataSet = new DataSet();

  StringReader sr = new StringReader(inputXmlString);

  objDataSet.ReadXml(sr);

  return objDataSet;
}


Example-5: Create and update the xml file

Here I have implemented a product xml file. The format of the xml file is

< ?xml version="1.0" encoding="utf-8"?>
< Items>
< Item>
< Code>101< /Code>
< Name>Product1< /Name>
< Price>100< /Price>
< Qty>12< /Qty>
< /Item>
< Item>
< Code>102< /Code>
< Name>Product2< /Name>
< Price>100< /Price>
< Qty>12< /Qty>
< /Item>
< /Items>



In this example you can add a new item, update the item and delete the items from the xml file.

Example-6: Delete node from xml file / Select Nodes Using XPath Navigation

Whenever you need to delete a node from the xml file, first of all you have to find the node with specified value then delete that node from the file. Here the xml format is


< ?xml version='1.0'?>
< bookstore xmlns="urn:newbooks-schema">
< book genre="novel" style="hardcover">
< title>Book1< /title>
< author>
< first-name>Pankaj< /first-name>
< last-name>Saha< /last-name>
< /author>
< price>19.95< /price>
< /book>
< book genre="novel" style="other">
< title>Book2< /title>
< author>
< first-name>Sanjay< /first-name>
< last-name>Singh< /last-name>
< /author>
< price>11.99< /price>
< /book>
< /bookstore>

public bool DeleteNode(string bookName)
{
  bool isValue = false;

  XmlDocument doc = new XmlDocument();

  try
  {

  string filePath = Server.MapPath("~/XMLFiles/Example6.xml");

  doc.Load(filePath);

  XmlNodeList nodeList;

  XmlNode root = doc.DocumentElement;

  nodeList = root.SelectNodes("descendant::book[title='" + bookName.ToLower() + "']");

  foreach (XmlNode obNode in nodeList)
  {
  root.RemoveChild(obNode);

  break;

  }

  doc.Save(filePath);
 }
 catch
 {
  throw;
 }
 finally
 {
 doc = null;
 }
 return isValue;
}



Example-6: Reading xml file with XmlTextReader

XmlTextReader is the best way when you need to read the xml file without loading the xml file in memory. When you have a very large xml file, which takes lots of time to load in the memory or document object and you need to find or read some values from the xml file then you can use the XmlTextReader class. This will help you to read the xml node value very fast.
Here I am using the Employee.xml file to read the xml file with the help of XmlTextReader class. You need to add the reference of using System.Xml.

 XmlTextReader reader = new XmlTextReader( Server.MapPath(@"~/XMLFiles/Employee.xml"));

 StringBuilder xmlString = new StringBuilder();

 while (reader.Read())
 {
 switch (reader.NodeType)
 {
  case XmlNodeType.Element: // when node is an element
  xmlString.AppendFormat("<" + reader.Name );

  //fetch all the attributes of the node
  while (reader.MoveToNextAttribute())
  {
   xmlString.AppendFormat(" " + reader.Name + "='" + reader.Value + "'");
  }

  xmlString.AppendFormat (">");
  break;
 case XmlNodeType.Text: //fetch the value of xml element
  xmlString.AppendFormat(reader.Value);
 break;
 case XmlNodeType.EndElement: //show the end of the element.
  xmlString.AppendFormat("");

 break;
 }
}

 Response.Write(xmlString.ToString());





Download:

Thursday, April 30, 2009

Create row at run time in ASP.NET GridView

Here I have created an ASP.NET GridView example where you can add, delete and update the row in the GridView at run time.

Steps:

1. Create a asp.net web application

2. Create a global DataTable globalDataTable

3. To create a DataTable first time I have created the following function


private DataTable CreateDataTable()
{
  DataTable dtSample = new DataTable();

  DataColumn myDataColumn;

  myDataColumn = new DataColumn();
  myDataColumn.DataType = Type.GetType("System.String");
  myDataColumn.ColumnName = "Id";
  dtSample.Columns.Add(myDataColumn);


  myDataColumn = new DataColumn();
  myDataColumn.DataType = Type.GetType("System.String");
  myDataColumn.ColumnName = "FirstName";
  dtSample.Columns.Add(myDataColumn);

  myDataColumn = new DataColumn();
  myDataColumn.DataType = Type.GetType("System.String");
  myDataColumn.ColumnName = "LastName";
  dtSample.Columns.Add(myDataColumn);

  return dtSample;
}

First time when the page is loaded it call this function to create the gridview and then store the gridview into the Session["dtSample"]. You can also use viewstate here instead of session.

4. To create a new row in the gridview the following function has been created :


private void AddNewRow(string firstname, string lastname, DataTable myTable)
{
  DataRow row;

  row = myTable.NewRow();

  row["Id"] = myTable.Rows.Count + 1;

  row["FirstName"] = firstname;

  row["LastName"] = lastname;

  myTable.Rows.Add(row);

  rowCount = myTable.Rows.Count;
}


6. To Edit and Delete from the gridview the following event has been added to the gridview


protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
  DataTable userDataTable = (DataTable)Session["dtSample"];

  userDataTable.Rows[e.RowIndex].Delete();

  Session["dtSample"] = userDataTable;

  this.GridView1.DataSource = ((DataTable)Session["dtSample"]).DefaultView;

  this.GridView1.DataBind();

}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{

  DataTable userDataTable = (DataTable)Session["dtSample"];

  if (userDataTable != null)
  {
    lblMsg.Text = Convert.ToString(userDataTable.Rows[e.NewEditIndex]["Id"]);

    txtFirstName.Text = Convert.ToString(userDataTable.Rows[e.NewEditIndex]["FirstName"]);

    txtLastName.Text = Convert.ToString(userDataTable.Rows[e.NewEditIndex]["LastName"]);
  }
}


7. We have saved the data on the Submit button click. 



protected void btnSubmit_Click(object sender, EventArgs e)
{
   if (txtFirstName.Text.Trim() == "")
   {
     this.lblMsg.Text = "You must fill a name.";
     return;
   }
  else
  {
   if (lblMsg.Text != "")
    {
      DataTable dtSample = (DataTable)Session["dtSample"];

     for (int iCount = 0; iCount < dtSample.Rows.Count; iCount++)
     {
      if (Convert.ToString(dtSample.Rows[iCount]["Id"]) == lblMsg.Text)
       {
         dtSample.Rows[iCount]["FirstName"] = txtFirstName.Text;
         dtSample.Rows[iCount]["LastName"] = txtLastName.Text;
        }
     }
 }
else
 {
  AddNewRow(this.txtFirstName.Text.Trim(), this.txtLastName.Text.Trim(), (DataTable)Session["dtSample"]);
}

 this.GridView1.DataSource = ((DataTable)Session["dtSample"]).DefaultView;      this.GridView1.DataBind();
this.txtFirstName.Text = "";
this.txtLastName.Text = "";
this.lblMsg.Text = "";
 }
}




Download: