Hello folks,
This is the second article of XML Manipulation using .NET and you can find the first article from here .
In the first article I have discussed how to
1. Create an XML file
2. Modify an XML elements using XPath
3. Bind an XML document to Data Grid View
4. Delete an XML node using Xpath
In this article I'm going to demonstrate how to extract/ search data from an XML document using LINQ (Language INtegrated Query) and bind the extracted data to grid view. I'm going to use following XML file to search and grid view to bind the searched result.
Harry PotterJ K. Rowling200529.99CHILDRENEveryday ItalianGiada De Laurentiis200530.00COOKINGXQuery Kick StartJames McGovern201049.99WEB
I'm going to perform following actions
1. Search by author name
2. Search by year
3. Search by price
First of all I have to load the XML file into XDocument.
XDocument main = XDocument.Load(Server.MapPath(XMLManager.GetFilePath()));
Please note: XMLManager is a user defined class. You can enter the file path as a string or read article one for more details about XMLManager class.
Search by Author Name
private List searchByAuthor(XDocument doc ,string seachName)
{
var book = from c in doc.Descendants("book")
where c.Element("author").Value.ToLower().Contains(seachName)
//where c.Element("author").Value.StartsWith(seachName)
//where c.Element("author").Value.EndsWith(seachName)
select new Book
{
Id = Convert.ToInt32(c.Attribute("id").Value),
Author = c.Element("author").Value,
Year = Convert.ToInt32(c.Element("year").Value),
Price = Convert.ToDouble(c.Element("price").Value),
Category = c.Element("category").Value
};
return book.ToList();
}
searchByAuthor method required two parameters, XDocument and the seachName.
The above LINQ search through all the book elements and select the elements where author name contains the seachName and add them to book variable. Then return the list of books. You can use either StartsWith or EndsWith methods to search a string when necessary.
Search by Year
private List searchByYear(XDocument doc, int year)
{
var book = from c in doc.Descendants("book")
where c.Element("year").Value == year.ToString()
select new Book
{
Id = Convert.ToInt32(c.Attribute("id").Value),
Author = c.Element("author").Value,
Year = Convert.ToInt32(c.Element("year").Value),
Price = Convert.ToDouble(c.Element("price").Value),
Category = c.Element("category").Value
};
return book.ToList();
}
searchByYear returns the list of books that match with the search criteria.
Search by Price
private List searchByPrice(XDocument doc, double minPrice, double maxPrice)
{
var book = from c in doc.Descendants("book")
where Convert.ToDouble(c.Element("price").Value)> minPrice
&& Convert.ToDouble(c.Element("price").Value)<= maxPrice
select new Book
{
Id = Convert.ToInt32(c.Attribute("id").Value),
Author = c.Element("author").Value,
Year = Convert.ToInt32(c.Element("year").Value),
Price = Convert.ToDouble(c.Element("price").Value),
Category = c.Element("category").Value
};
return book.ToList();
}
searchByPrice method returns the list of books that the price comes between minimum and maximum value.
Bind to the data grid
Following code shows how to bind the book list to the grid view.
Hello folks,
In this article I'm going to discuss how to
1. Create an XML file
2. Modify an XML elements using XPath
3. Bind an XML document to Data Grid View
4. Delete an XML node using Xpath
In the Part II, I will discuss how to
1. Search XML elements and display searched result in Data Grid View using LINQ.
Please note: Please use Firefox or IE to read this article.Sorry for the inconvenience caused.
I'm gonna create and use following XML file throughout this article.
Harry PotterJ K. Rowling200529.99CHILDRENEveryday ItalianGiada De Laurentiis200530.00COOKINGXQuery Kick StartJames McGovern201049.99WEB
First of all let's define the file path of our XML file in the web config file and create a class called XMLManager to get the file path.
The reason for this step is to keep the file path in a specific place and access it from anywhere from the application.
Insert the following code under configuration section in web config file.
The XML file we are going to create is bookDetails.xml and it locates in a folder called XML.
Here's the XMLManager class. In here I use a static method because in order to use the method we don't have to create an instance of the class.
public class XMLManager
{
public static string GetFilePath()
{
return ConfigurationManager.AppSettings["XmlFilePath"].ToString();
}
}
Create an XML Document
Following code snippet shows how to create above XML file using XMLDocument class.
In order to use below code you have import System.XML base class
private void writeXML()
{
// Create new XML document
XmlDocument doc = new XmlDocument();
// Create nodes and attributes
XmlNode bookstore, book, title, author, year, price, category;
XmlAttribute id;
// the root element
bookstore = doc.CreateElement("bookstore");
doc.AppendChild(bookstore);
// element with category attribute
book = doc.CreateElement("book");
bookstore.AppendChild(book);
id = doc.CreateAttribute("id");
id.Value = getNewBookID().ToString();
book.Attributes.Append(id);
// element
title = doc.CreateElement("title");
title.InnerText = txtTitle.Text.Trim();
book.AppendChild(title);
// element
author = doc.CreateElement("author");
author.InnerText = txtAuthor.Text.Trim();
book.AppendChild(author);
// element
year = doc.CreateElement("year");
year.InnerText = txtYear.Text.Trim();
book.AppendChild(year);
// element
price = doc.CreateElement("price");
price.InnerText = txtPrice.Text.Trim();
book.AppendChild(price);
//
category = doc.CreateElement("category");
category.InnerText = drpCategory.SelectedItem.Text;
book.AppendChild(category);
// Save the XML document to XML folder
doc.Save(Server.MapPath(XMLManager.GetFilePath()));
}
First create an XML document called doc by using XMLDocument class and then define necessary XML nodes and attributes.
In here I have 7 XML nodes (elements) and 1 attribute called ID to store book ID.
After that create the XML root element called bookstore and append it to the XML document doc. Then create the book element with ID attribute and append it as a child of root element. Please note the value of the book id receive from a private method called getNewBookID and code for this method can be found latter part of the article.
Then create the other child elements of the book element and append them to the book element.
After creating the XML document it can be saved by using Save method. In here I have consumed GetFilePath static method of our XMLManager class to give the file path. The new file will be save to the location that we have defined in the web.config file. In this case XML file will be create inside the XML folder with the name bookDetails.
Please note: You won't be able to see the created XML file in the specified location because it is not included to the project. In order to view the XML file using VS, first you have to select "Show All Files" option in the solution explorer and right click on the created bookDetails XML file (which is now exclude from the project) and select include to project option. Then and only you can see the created XML document using VS.
The above code will create and save your first book details in to a XML file called "bookDetails.xml". However when you want to add another book details to an existing XML file you have to use slightly different code. Below code shows how to append another book node to above bookDetails.xml document.
private void modifyXML()
{
// load the existing XML document
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath(XMLManager.GetFilePath()));
XmlNode book, title, author, year, price, category;
XmlAttribute id, lang;
// element with category attribute
book = doc.CreateElement("book");
id = doc.CreateAttribute("id");
id.Value = getNewBookID().ToString();
book.Attributes.Append(id);
// element
title = doc.CreateElement("title");
title.InnerText = txtTitle.Text.Trim();
book.AppendChild(title);
// element
author = doc.CreateElement("author");
author.InnerText = txtAuthor.Text.Trim();
book.AppendChild(author);
// element
year = doc.CreateElement("year");
year.InnerText = txtYear.Text.Trim();
book.AppendChild(year);
// element
price = doc.CreateElement("price");
price.InnerText = txtPrice.Text.Trim();
book.AppendChild(price);
// element
category = doc.CreateElement("category");
category.InnerText = drpCategory.SelectedItem.Text;
book.AppendChild(category);
XmlNode lastNode = doc.SelectSingleNode("bookstore/book[last()]");
lastNode.ParentNode.InsertAfter(book,lastNode);
doc.Save(Server.MapPath(XMLManager.GetFilePath()));
}
First load the existing file into a XML documents and then create book element with required attributes and child elements. After that find the last book node in the XML file by using XPath and insert the new book node after the last node. Then save the updated XML document by using Save method.
The following code shows getNewBookID method which returns the new ID for a book.
private int getNewBookID()
{
int result = 0;
if (File.Exists(Server.MapPath(XMLManager.GetFilePath())))
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath(XMLManager.GetFilePath()));
XmlNode node = doc.SelectSingleNode("bookstore/book[last()]");
int currentNode = Convert.ToInt32(node.Attributes["id"].Value);
result = currentNode + 1;
}
else
result = 1;
return result;
}
First the application checks for the file. If it does not exists then simply return the value 1 because we will create a new book with the ID 1. If the file exists, then load the existing file to new XML file using Load method. Then get the last XML node of the file using XPath. you can use either bookstore/book[last()]or //book[last()] to select the last book node. More XPath syntax can be found from Here.
Then get the value of the ID attribute of the last node and increase it by one and return the result as new book ID.
View XML Data in a Gridview Control
First add a Gridview control to the HTML page and add bound fields to represent the data. In here I have added 5 bound columns to represent book Id, Author, Year, Price and category. Value of the DataField column should be equal to names of your XML file nodes and attributes.
Apart from the bound fields I have added two button fields to delete and update Gridview rows. The command name delete will fire the onrowdeleting event and command name update will fire the onrowupdating event. Also please note that the DataKeyNames property has set to ID attribute of the book element which is use when updating and deleting an existing node.
Following code shows how to bind the created XML file to gridview control using ReadXml method of a DataSet object.
private void bindDataToGrid()
{
if (File.Exists(Server.MapPath(XMLManager.GetFilePath())))
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath(XMLManager.GetFilePath()));
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
lblError.Text = "File does not exists";
}
Data Grid View with XML Data
Delete an XML Node
When user clicks on the delete link the application will fire the GridView1_RowDeleting event. The following code sample shows how to remove a book node from an XML document by using book ID attribute.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
if (File.Exists(Server.MapPath(XMLManager.GetFilePath())))
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath(XMLManager.GetFilePath()));
XmlNode node = doc.SelectSingleNode("bookstore/book[@id='" + index.ToString() + "']");
node.ParentNode.RemoveChild(node);
doc.Save(Server.MapPath(XMLManager.GetFilePath()));
bindDataToGrid();
}
}
First get the ID of the book that wants to remove by using gridview dataKeys property. Then load the XML file to a new XML document and find the appropriate node by using XPath. Then you can use the RemoveChild method to remove that note from the XML document. Then use the Save method to save updated XML document to the disc. Please note you have to bindDateToGrid method in order to view the updated data grid view.
Update an Existing XML Node
First I will show you how to select an existing book from the above data grid view and redirect it to another page using query string. Then I will display the selected book in edit mode where users can change the existing data and can update the book.
The following code demonstrate how to select a book from the gridview.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
Response.Redirect(string.Format("XML.aspx?id={0}", index.ToString()));
}
When user clicks on the Edit link in the data grid view, the RowUpdating event will fire and we can find the selected book ID using DataKeys property. Then we redirect the use to another page to display the selected book details where user can edit them and update that details.
Read a Node from XML file
The following code shows how to read a particular book node from the XML file and show the details in the web page.
loadXML method requires book Id as a parameter. First load the XML file and then search the XML node where id equals to the parameter. I have used the XPath to select the required node. Then I have bind the values of child nodes and values of attributes to page controls. Please not I have a hidden field called hdnID to store the book ID because I need that value when updating the record back to the XML file.
Now the following code shows how to save the above node with modified values to the XML document.
protected void btnUpdate_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath(XMLManager.GetFilePath()));
XmlNode book, title, author, year, price, category;
XmlAttribute id, lang;
// element with Id attribute
book = doc.CreateElement("book");
id = doc.CreateAttribute("id");
id.Value = hdnID.Value;
book.Attributes.Append(id);
// element
title = doc.CreateElement("title");
title.InnerText = txtTitle.Text.Trim();
book.AppendChild(title);
// element
author = doc.CreateElement("author");
author.InnerText = txtAuthor.Text.Trim();
book.AppendChild(author);
// element
year = doc.CreateElement("year");
year.InnerText = txtYear.Text.Trim();
book.AppendChild(year);
// element
price = doc.CreateElement("price");
price.InnerText = txtPrice.Text.Trim();
book.AppendChild(price);
category = doc.CreateElement("category");
category.InnerText = drpCategory.SelectedItem.Text;
book.AppendChild(category);
XmlNode oldNode = doc.SelectSingleNode(string.Format("bookstore/book[@id='{0}']",hdnID.Value));
oldNode.ParentNode.ReplaceChild(book,oldNode);
doc.Save(Server.MapPath(XMLManager.GetFilePath()));
Response.Redirect("ViewXML.aspx");
}
Search XML file using LINQ
In the above code first we create a Book node with required attributes and child nodes. Then we select the node that we want to update by using XPath. After that we replace the existing node with our newly created node and save the XML document.
Abstract – The aim of this paper to demonstrate the evolution of integration patterns by identifying the advantages and disadvantages in each phase and identify the affects of enterprise service bus to the modern business world by discovering it is core features and advantages. Keywords: Enterprise Service Bus (ESB), Service Oriented Architecture (SOA), Message-Oriented Middleware (MOM), Enterprise Application Integration (EAI).
Introduction A large enterprise could have their branches and warehouses in different geographical locations spreading all over the world. These branches and warehouse can have their own applications and web sites. These applications and websites should interact with each other in order to provide best service to the end-users. Also they might have to interact with external business process and also third party components as well. Future more existing applications need to be modified according to new requirements and need to create new applications and merge them with existing application. Therefore application integration process can not be omitted inside a large enterprise and it should be capable to handle all the kind of different approaches as explained above.
Evolution of integration patterns Historical way of system integration was point-to-point integration. As the figure states in this scenario each pair of component must have unique communication interface. Main advantage is easy to set up and efficient [O'Brien 2008]. The main drawback is when increase the number of components, it increase the system complexity [O'Brien 2008]. This is also known as n2 problem. That means for each new system add to this architecture that needs to be integrated, solution end up with a total of n2 integration points [Brooks-Bilson 2007]. This leads to high maintenance cost and lack of flexibility. Furthermore it is bind with low scalability, which means to extend an existing function or to add a new function; each and every component should be upgraded. It will take relatively high cost plus more time.
To address above drawbacks hub and spoke integration or Enterprise Application Integration (EAI) introduced. As the figure shows, in this mechanism there is a centralized component which is known as hub or message broker. All the components are connected each other through the hub. The message broker is capable to store the messages and transform the messages to different formats. Therefore sender and receiver should not be online to exchange messages and also they can use their own message formats. The main advantage of this architecture is loose coupling. Furthermore the entire configuration can be done within the centralized point, which increases the scalability plus reduce the time and cost. [Menge 2007] The main disadvantage of this scenario is lack of interoperability. The solution is only supports to the subsets of developed vendor. It is unable to interact with other solutions which are developed by another vendor or internally developed solution. Another drawback is this architecture does not capable to handle components which are in a large geographical area. Also they are expensive and heavyweight plus most of the traditional EAI solutions were unsuccessful in the industry [Mulesoft]. Mulesoft.org revealed that 70 percent of EAI projects ultimately failed in year 2003. This architecture has a performance issue as well [O'Brien 2008]. When system expanding hub requires more processing power and disk space in order to perform and it is affect to the cost.
Enterprise Service Bus Therefore modern business world requires a solution which supports interoperability, highly scalable, lightweight and with high performance for low cost. The approach is Enterprise Service Bus (ESB). According to the Menge [2007] “Enterprise Service Bus is an open standards, message based, distributed integration infrastructure that provides routing, invocation and mediation services to facilitate the interactions of disparate distributed applications and services in a secure and reliable manner”.
ESB also contains a centralized component as EAI to facilitate communication, but this architecture has designed to reduce the functionalities of the centralized component and distribute them among components called service containers within the network. These service containers can be routers, transformers or application adaptors.
ESB core features ESB supports location transparency, which means message receiver does not need to know message origin in order to receive a message. ESB also can transform the format of a message. This allows both sender and receiver to use their existing formats because ESB transform the message. ESB is able to merge and aggregate messages. ESB can combine several messages and build a one message and vice versa. ESB can do the message re sequence, which means it can collect related but out of order messages and rearrange them in to correct order. ESB can do content-based message routing that is ESB can make the decision of the receiver based on the message content and sender does not need to specify the message receiver [Menge 2007]. According to above message routing features, ESB solution is ideal for complex business processes.
ESB provides well secured platform to communicate. That means message content can be encrypt and decrypt, and also it facilitates the authentication and access control mechanism [Menge 2007]. This means ESB also address a main concern, which is security in the business industry.
Usually ESB solution come up with set of adapters which can be use to connect widely use industrial application packages such as Enterprise Resource Planning (ERP), Supply Change Management (SCM), Customer Relationship Management (CRM) [Menge 2007]. Therefore ESB solution is high scaleable and flexible.
ESB solution also facilitates to monitor the system performance and allow to handles errors. System configuration and administration can be done by central location [Mulesoft]. These features increase the maintainability of the system.
ESB Advantages Apart from the above core features ESB solution contains significant advantages as well. The foremost advantage is ESB supports Service Oriented Architecture (SOA). Therefore an organization can expand their business process by plug-in reusable service to existing ESB solution. For an instance an organization can expand their existing Enterprise Resource Planning system by plug-in Customer Relationship Management (CRM) system and a Supply Chain Management (SCM) system which are developed by using SOAP or REST web services. These web services can be run on different operating systems with different databases and can be developed by using different programming languages. Furthermore they can locate in different geographical locations. These Service component can be adopt, upgrade or modify without interrupting to each other as they behave independently.
ESB Limitations There are few limitations as well. This solution is recommended if there are three or more components to integrate and need to integrate more components in future. Therefore this is not suitable for small or medium size business process integration. The main disadvantage is that ESB solutions are vendor specific [Mason 2009], which means features of a solution is depend on vendors as ESB does not contains a features specification. Therefore consumers should be aware of features before implement an ESB.
Conclusion Today business process model should interact with different kind of components and services which are locate in different locations as they have complex business requirements. Enterprise Service Bus provides an ideal platform to manipulate this integration by using Service Oriented Architecture. ESB contains many features and advantages which can be use to empower today business world. But it is also contains some limitations as well, therefore before construct an ESB solution, it is mandatory to conduct a proper research inside an organization.
References Falko Menge (2007), Enterprise Service Bus, [online] Free and open sourse software conference. Last accessed data 03 December 2010 at: http://programm.froscon.de/2007/attachments/15-falko_menge_-_enterpise_service_bus.pdf
Mulesoft, Understanding Enterprise Application Integration - The Benefits of ESB for EAI [online]. MuleSoft Inc. Last accessed data 03 December 2010 at: http://www.mulesoft.org/enterprise-application-integration-eai-and-esb
Rob Brooks-Bilson (2007), The Evolution of Integration Architecture: An Introduction to the Enterprise Service Bus (ESB), [online]. digitalnature.ro. Last accessed data 03 December 2010 at: http://rob.brooks-bilson.com/index.cfm/2007/12/14/The-Evolution-of-Integration-Architecture--An-Introduction-to-the-Enterprise-Service-Bus-ESB
Ross Mason (2009), To ESB or not to ESB, [online], MuleSoft Inc. Last accessed data 03 December 2010 at: http://blogs.mulesoft.org/to-esb-or-not-to-esb/
Russell O'Brien (2008), Integration Architecture Explained, [online]. Hubpages Inc. Last accessed data 03 December 2010 at: http://hubpages.com/hub/Integration-Architecture-Explained
* above article wrote by Kasun P Kularatne for Sheffield Hallam University postgraduate course under web services module
In this article I am going to explain how to create a simple shopping cart with lambda expressions and generic list. To archive this I am going to create two classes called Product and Basket. Product class supposes to store all the product information and basket class suppose to store list of the products. The following figure shows my product class
Then I am going to create next class, class Basket. In this class I got three properties
Getters and setters are look like follows
For the totalAmount I eliminated setter and for the get the total amount I used lambda expression
I am going to retrieve item count as follows
Apart from that I have a method to remove products from the basket and I am using lambda expressions for that as well.
You can download Product class from here and Basket class from here.
Now let’s see how to use these two classes in the real world.
create an instance of basket class
create an instance of Product class and add product details
Add product instance to basket instance.
Add basket instance to session variable for future use.
This code will work fine for the first time. But the second time when user clicks on the AddToBasket button it will create new instance. To avoid such a situation you should always check whether the basket is created or not. If created you can add second product to the existing basket, if not you have to create a new basket as above. Complete code snippet will look like follows