Thursday, November 3, 2011

XML Manipulation using .NET (C#) PART II

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 Potter
    J K. Rowling
    2005
    29.99
    CHILDREN
  
  
    Everyday Italian
    Giada De Laurentiis
    2005
    30.00
    COOKING
  
  
    XQuery Kick Start
    James McGovern
    2010
    49.99
    WEB
  



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.
GridView1.DataSource = searchByPrice(main, 10, 30);
            GridView1.DataBind();

Sunday, October 30, 2011

XML Manipulation using .NET (C#) PART I

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 Potter
    J K. Rowling
    2005
    29.99
    CHILDREN
  
  
    Everyday Italian
    Giada De Laurentiis
    2005
    30.00
    COOKING
  
  
    XQuery Kick Start
    James McGovern
    2010
    49.99
    WEB
  

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);           

            // <author> element
            author = doc.CreateElement("author");
            author.InnerText = txtAuthor.Text.Trim();
            book.AppendChild(author);

            // <year> element
            year = doc.CreateElement("year");
            year.InnerText = txtYear.Text.Trim();
            book.AppendChild(year);

            // <price> element
            price = doc.CreateElement("price");
            price.InnerText = txtPrice.Text.Trim();
            book.AppendChild(price);

            // <category>
            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()));
        }
</pre>

First create an XML document called <b>doc</b> by using <b> XMLDocument </b> class and then define necessary XML nodes and attributes. <br />
In here I have 7 XML nodes (elements) and 1 attribute called ID to store book ID.  <br />

After that create the XML root element called bookstore and append it to the XML document <b>doc</b>. Then create the <b>book</b> element with <b>ID</b> attribute and append it as a child of root element. Please note the value of the book id receive from a private method called <b>getNewBookID</b> and code for this method can be found latter part of the article. <br />

Then create the other child elements of the <b>book</b> element and append them to the <b>book</b> element. 

After creating the XML document it can be saved by using <b>Save</b> method. In here I have consumed <b>GetFilePath</b> static method of our <b> XMLManager </b> 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 <b>bookDetails</b>.

<br /><br />
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.
<br /><br />

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. 
 
<pre class="brush: csharp">
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;

            // <book> element with category attribute
            book = doc.CreateElement("book");
            id = doc.CreateAttribute("id");
            id.Value = getNewBookID().ToString();
            book.Attributes.Append(id);

            // <title> element
            title = doc.CreateElement("title");
            title.InnerText = txtTitle.Text.Trim();
            book.AppendChild(title);
            
            // <author> element
            author = doc.CreateElement("author");
            author.InnerText = txtAuthor.Text.Trim();
            book.AppendChild(author);

            // <year> element
            year = doc.CreateElement("year");
            year.InnerText = txtYear.Text.Trim();
            book.AppendChild(year);

            // <price> element
            price = doc.CreateElement("price");
            price.InnerText = txtPrice.Text.Trim();
            book.AppendChild(price);

            // <category> 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()));
        }
</pre>

First load the existing file into a XML documents and then create <b>book</b> 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 <b>Save</b> method.

<br /><br />
The following code shows <b>getNewBookID</b> method which returns the new ID for a book.

<pre class="brush: csharp">
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;
        }
</pre>

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 <b>Load</b> method. Then get the last XML node of the file using XPath. you can use either <b>bookstore/book[last()]</b>or <b>//book[last()]</b> to select the last book node. More XPath syntax can be found from <a href="http://www.w3schools.com/xpath/xpath_syntax.asp" target="_blank">Here</a>. <br />

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. 

<br /><br />
<b>View XML Data in a Gridview Control</b> <br />
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 <b>DataField</b> column should be equal to names of your XML file nodes and attributes. 

<pre class="brush: csharp">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="id" 
                    onrowdeleting="GridView1_RowDeleting" 
                    onrowupdating="GridView1_RowUpdating">
                    <Columns>
                        <asp:BoundField HeaderText="ID" DataField="id" />
                        <asp:BoundField HeaderText="Author" DataField="author" />
                        <asp:BoundField HeaderText="Year" DataField="year" />
                        <asp:BoundField HeaderText="Price" DataField="price" />                        
                        <asp:BoundField HeaderText="Category" DataField="category" />
                        <asp:ButtonField ButtonType="Link" CommandName="delete" Text="delete" />   
                        <asp:ButtonField ButtonType="Link" CommandName="update" Text="edit" />                     
                    </Columns>
                </asp:GridView>
</pre>

Apart from the bound fields I have added two button fields to delete and update Gridview rows. The command name <b>delete</b> will fire the <b>onrowdeleting</b> event and command name <b>update</b> will fire the <b>onrowupdating</b> event. Also please note that the <b> DataKeyNames</b> property has set to <b>ID</b> attribute of the book element which is use when updating and deleting an existing node. <br />

Following code shows how to bind the created XML file to gridview control using <b>ReadXml</b> method of a DataSet object. 

<pre class="brush: csharp">
        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";
        }
</pre>

<br /><br />
<b>Data Grid View with XML Data</b><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSjMjs8lxrtVErCiiHZFwbbfE_0CzzfH_FE-hETed7JZAxcVDo9zLU7UnHHEOr8kvexibPdjDTkZ_ocDqCg4clG3jUYv0h7KPZuATB_JqVjZitBgOw2yNcxziKsFpRWxgx18Wv5pxkwbTA/s1600/gridview_xml.JPG" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="104" width="375" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSjMjs8lxrtVErCiiHZFwbbfE_0CzzfH_FE-hETed7JZAxcVDo9zLU7UnHHEOr8kvexibPdjDTkZ_ocDqCg4clG3jUYv0h7KPZuATB_JqVjZitBgOw2yNcxziKsFpRWxgx18Wv5pxkwbTA/s400/gridview_xml.JPG" /></a></div>
<br /><br />

<br /><br />
<b>Delete an XML Node  </b> <br />
When user clicks on the delete link the application will fire the <b>GridView1_RowDeleting</b> event. The following code sample shows how to remove a book node from an XML document by using book ID attribute.

<pre class="brush: csharp">
 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();
            }
        }
</pre>

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. 

<br/ ><br />
<b>Update an Existing XML Node </b> <br />
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. <br />

The following code demonstrate how to select a book from the gridview. 

<pre class="brush: csharp">
 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()));
        }
</pre>

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. 

<br/ ><br />
<b>Read a Node from XML file </b> <br />
The following code shows how to read a particular book node from the XML file and show the details in the web page. 

<pre class="brush: csharp">
private void loadXML(int id)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath(XMLManager.GetFilePath()));

            XmlNode node = doc.SelectSingleNode(string.Format("bookstore/book[@id='{0}']",id));
            if (node != null)
            {
                txtTitle.Text = node["title"].InnerText;
                txtAuthor.Text = node["author"].InnerText;
                txtYear.Text = node["year"].InnerText;
                txtPrice.Text = node["price"].InnerText;
                drpCategory.Items.FindByText(node["category"].InnerText).Selected=true;
                hdnID.Value = node.Attributes["id"].Value;
            }
        }
</pre>

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. 

<br/ ><br />
Now the following code shows how to save the above node with modified values to the XML document. 

<pre class="brush: csharp">
          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;

            // <book> element with Id attribute
            book = doc.CreateElement("book");
            id = doc.CreateAttribute("id");
            id.Value = hdnID.Value;
            book.Attributes.Append(id);

            // <title> element
            title = doc.CreateElement("title");
            title.InnerText = txtTitle.Text.Trim();
            book.AppendChild(title);
            
            // <author> element
            author = doc.CreateElement("author");
            author.InnerText = txtAuthor.Text.Trim();
            book.AppendChild(author);

            // <year> element
            year = doc.CreateElement("year");
            year.InnerText = txtYear.Text.Trim();
            book.AppendChild(year);

            // <price> 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");
        }
</pre>

<br/ ><br />
<b>Search XML file using LINQ </b> <br />

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. 

<script type="text/javascript">
     SyntaxHighlighter.all()
</script>
<div style='clear: both;'></div>
</div>
<div class='post-footer'>
<div class='post-footer-line post-footer-line-1'>
<span class='post-author vcard'>
Posted by
<span class='fn' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'>
<meta content='https://www.blogger.com/profile/00966916158670098102' itemprop='url'/>
<a class='g-profile' href='https://www.blogger.com/profile/00966916158670098102' rel='author' title='author profile'>
<span itemprop='name'>Kasun Kularatne</span>
</a>
</span>
</span>
<span class='post-timestamp'>
at
<meta content='http://kasunkularatne.blogspot.com/2011/10/xml-manipulation-using-net-c.html' itemprop='url'/>
<a class='timestamp-link' href='https://kasunkularatne.blogspot.com/2011/10/xml-manipulation-using-net-c.html' rel='bookmark' title='permanent link'><abbr class='published' itemprop='datePublished' title='2011-10-30T04:02:00-07:00'>4:02 AM</abbr></a>
</span>
<span class='post-comment-link'>
<a class='comment-link' href='https://kasunkularatne.blogspot.com/2011/10/xml-manipulation-using-net-c.html#comment-form' onclick=''>
No comments:
  </a>
</span>
<span class='post-icons'>
<span class='item-control blog-admin pid-1919009760'>
<a href='https://www.blogger.com/post-edit.g?blogID=7709464623091465853&postID=2946624625076777494&from=pencil' title='Edit Post'>
<img alt='' class='icon-action' height='18' src='https://resources.blogblog.com/img/icon18_edit_allbkg.gif' width='18'/>
</a>
</span>
</span>
<div class='post-share-buttons goog-inline-block'>
<a class='goog-inline-block share-button sb-email' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=2946624625076777494&target=email' target='_blank' title='Email This'><span class='share-button-link-text'>Email This</span></a><a class='goog-inline-block share-button sb-blog' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=2946624625076777494&target=blog' onclick='window.open(this.href, "_blank", "height=270,width=475"); return false;' target='_blank' title='BlogThis!'><span class='share-button-link-text'>BlogThis!</span></a><a class='goog-inline-block share-button sb-twitter' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=2946624625076777494&target=twitter' target='_blank' title='Share to Twitter'><span class='share-button-link-text'>Share to Twitter</span></a><a class='goog-inline-block share-button sb-facebook' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=2946624625076777494&target=facebook' onclick='window.open(this.href, "_blank", "height=430,width=640"); return false;' target='_blank' title='Share to Facebook'><span class='share-button-link-text'>Share to Facebook</span></a><a class='goog-inline-block share-button sb-pinterest' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=2946624625076777494&target=pinterest' target='_blank' title='Share to Pinterest'><span class='share-button-link-text'>Share to Pinterest</span></a>
</div>
</div>
<div class='post-footer-line post-footer-line-2'>
<span class='post-labels'>
</span>
</div>
<div class='post-footer-line post-footer-line-3'>
<span class='post-location'>
</span>
</div>
</div>
</div>
</div>

          </div></div>
        

          <div class="date-outer">
        
<h2 class='date-header'><span>Wednesday, September 21, 2011</span></h2>

          <div class="date-posts">
        
<div class='post-outer'>
<div class='post hentry uncustomized-post-template' itemprop='blogPost' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'>
<meta content='7709464623091465853' itemprop='blogId'/>
<meta content='3424383869882035321' itemprop='postId'/>
<a name='3424383869882035321'></a>
<h3 class='post-title entry-title' itemprop='name'>
<a href='https://kasunkularatne.blogspot.com/2011/09/web-accessibility.html'>Web Accessibility</a>
</h3>
<div class='post-header'>
<div class='post-header-line-1'></div>
</div>
<div class='post-body entry-content' id='post-body-3424383869882035321' itemprop='description articleBody'>
I did this research as an artifact for my MSc dissertation "Dynamic Software Development Platform" which can be accessed from <a href="http://myportfoliodissertation.blogspot.com"> here </a>

<embed src="http://embedit.in/raSEfQfMXV.swf" height="800" width="600" type="application/x-shockwave-flash" allowFullScreen="true">
<div style='clear: both;'></div>
</div>
<div class='post-footer'>
<div class='post-footer-line post-footer-line-1'>
<span class='post-author vcard'>
Posted by
<span class='fn' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'>
<meta content='https://www.blogger.com/profile/00966916158670098102' itemprop='url'/>
<a class='g-profile' href='https://www.blogger.com/profile/00966916158670098102' rel='author' title='author profile'>
<span itemprop='name'>Kasun Kularatne</span>
</a>
</span>
</span>
<span class='post-timestamp'>
at
<meta content='http://kasunkularatne.blogspot.com/2011/09/web-accessibility.html' itemprop='url'/>
<a class='timestamp-link' href='https://kasunkularatne.blogspot.com/2011/09/web-accessibility.html' rel='bookmark' title='permanent link'><abbr class='published' itemprop='datePublished' title='2011-09-21T03:03:00-07:00'>3:03 AM</abbr></a>
</span>
<span class='post-comment-link'>
<a class='comment-link' href='https://kasunkularatne.blogspot.com/2011/09/web-accessibility.html#comment-form' onclick=''>
No comments:
  </a>
</span>
<span class='post-icons'>
<span class='item-control blog-admin pid-1919009760'>
<a href='https://www.blogger.com/post-edit.g?blogID=7709464623091465853&postID=3424383869882035321&from=pencil' title='Edit Post'>
<img alt='' class='icon-action' height='18' src='https://resources.blogblog.com/img/icon18_edit_allbkg.gif' width='18'/>
</a>
</span>
</span>
<div class='post-share-buttons goog-inline-block'>
<a class='goog-inline-block share-button sb-email' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=3424383869882035321&target=email' target='_blank' title='Email This'><span class='share-button-link-text'>Email This</span></a><a class='goog-inline-block share-button sb-blog' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=3424383869882035321&target=blog' onclick='window.open(this.href, "_blank", "height=270,width=475"); return false;' target='_blank' title='BlogThis!'><span class='share-button-link-text'>BlogThis!</span></a><a class='goog-inline-block share-button sb-twitter' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=3424383869882035321&target=twitter' target='_blank' title='Share to Twitter'><span class='share-button-link-text'>Share to Twitter</span></a><a class='goog-inline-block share-button sb-facebook' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=3424383869882035321&target=facebook' onclick='window.open(this.href, "_blank", "height=430,width=640"); return false;' target='_blank' title='Share to Facebook'><span class='share-button-link-text'>Share to Facebook</span></a><a class='goog-inline-block share-button sb-pinterest' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=3424383869882035321&target=pinterest' target='_blank' title='Share to Pinterest'><span class='share-button-link-text'>Share to Pinterest</span></a>
</div>
</div>
<div class='post-footer-line post-footer-line-2'>
<span class='post-labels'>
</span>
</div>
<div class='post-footer-line post-footer-line-3'>
<span class='post-location'>
</span>
</div>
</div>
</div>
</div>

          </div></div>
        

          <div class="date-outer">
        
<h2 class='date-header'><span>Wednesday, February 2, 2011</span></h2>

          <div class="date-posts">
        
<div class='post-outer'>
<div class='post hentry uncustomized-post-template' itemprop='blogPost' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'>
<meta content='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWLxClIhSDu1V3vUtL7D7xups9LZoCKpmQxeAxtaAr00YH3jqLjP4-6llwhwfyiBQwy8DD0U9wi4ZvT1ctRBGwWBjKmBpZyLeGZIann43enG3VV1fpytzPrLi3HSr3Hv81AMuFUEKy8sQv/s400/blog008.JPG' itemprop='image_url'/>
<meta content='7709464623091465853' itemprop='blogId'/>
<meta content='2056549441116328229' itemprop='postId'/>
<a name='2056549441116328229'></a>
<h3 class='post-title entry-title' itemprop='name'>
<a href='https://kasunkularatne.blogspot.com/2011/02/evolution-of-integration-patterns-and.html'>Evolution of integration patterns and why Enterprise Service Bus (ESB) suit for modern business world</a>
</h3>
<div class='post-header'>
<div class='post-header-line-1'></div>
</div>
<div class='post-body entry-content' id='post-body-2056549441116328229' itemprop='description articleBody'>
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.<br />Keywords: Enterprise Service Bus (ESB), Service Oriented Architecture (SOA), Message-Oriented Middleware (MOM), Enterprise Application Integration (EAI).<br /><br />Introduction<br />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.<br /><br />Evolution of integration patterns<br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWLxClIhSDu1V3vUtL7D7xups9LZoCKpmQxeAxtaAr00YH3jqLjP4-6llwhwfyiBQwy8DD0U9wi4ZvT1ctRBGwWBjKmBpZyLeGZIann43enG3VV1fpytzPrLi3HSr3Hv81AMuFUEKy8sQv/s1600/blog008.JPG"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5569174986671255410" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWLxClIhSDu1V3vUtL7D7xups9LZoCKpmQxeAxtaAr00YH3jqLjP4-6llwhwfyiBQwy8DD0U9wi4ZvT1ctRBGwWBjKmBpZyLeGZIann43enG3VV1fpytzPrLi3HSr3Hv81AMuFUEKy8sQv/s400/blog008.JPG" style="float: left; margin-top: 0px; margin-right: 10px; margin-bottom: 10px; margin-left: 0px; cursor: pointer; width: 178px; height: 200px; " /></a>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.<br /><br />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 <a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEga2DbzMYc6vtDJNgq-nTiAREXoCDGdfM6Z5mv6b-SPf_P6Oe6jp4V5IyTNvrnRjNbNZw-QIcW61j_zYLFBJKU-CC0SC3-CRXowSUYOhGt_VGygeO9Gkn1714dUtd6-m2reDv77O0L870UK/s1600/blog009.JPG"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5569175471759000866" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEga2DbzMYc6vtDJNgq-nTiAREXoCDGdfM6Z5mv6b-SPf_P6Oe6jp4V5IyTNvrnRjNbNZw-QIcW61j_zYLFBJKU-CC0SC3-CRXowSUYOhGt_VGygeO9Gkn1714dUtd6-m2reDv77O0L870UK/s400/blog009.JPG" style="float: left; margin-top: 0px; margin-right: 10px; margin-bottom: 10px; margin-left: 0px; cursor: pointer; width: 178px; height: 200px; " /></a>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.<br /><br />Enterprise Service Bus<br />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”.<br /><br />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.<br /><br />ESB core features<br />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.<br /><br />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.<br /><br />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.<br /><br />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.<br /><br />ESB Advantages<br />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.<br /><br />ESB Limitations<br />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.<br /><br />Conclusion<br />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.<br /><br /><br />References<br />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<br /><br />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<br /><br />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<br /><br />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/<br /><br />Russell O'Brien (2008), Integration Architecture Explained, [online]. Hubpages Inc. Last accessed data 03 December 2010 at: http://hubpages.com/hub/Integration-Architecture-Explained<br /><br />* above article wrote by Kasun P Kularatne for Sheffield Hallam University postgraduate course under web services module
<div style='clear: both;'></div>
</div>
<div class='post-footer'>
<div class='post-footer-line post-footer-line-1'>
<span class='post-author vcard'>
Posted by
<span class='fn' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'>
<meta content='https://www.blogger.com/profile/00966916158670098102' itemprop='url'/>
<a class='g-profile' href='https://www.blogger.com/profile/00966916158670098102' rel='author' title='author profile'>
<span itemprop='name'>Kasun Kularatne</span>
</a>
</span>
</span>
<span class='post-timestamp'>
at
<meta content='http://kasunkularatne.blogspot.com/2011/02/evolution-of-integration-patterns-and.html' itemprop='url'/>
<a class='timestamp-link' href='https://kasunkularatne.blogspot.com/2011/02/evolution-of-integration-patterns-and.html' rel='bookmark' title='permanent link'><abbr class='published' itemprop='datePublished' title='2011-02-02T11:19:00-08:00'>11:19 AM</abbr></a>
</span>
<span class='post-comment-link'>
<a class='comment-link' href='https://kasunkularatne.blogspot.com/2011/02/evolution-of-integration-patterns-and.html#comment-form' onclick=''>
No comments:
  </a>
</span>
<span class='post-icons'>
<span class='item-control blog-admin pid-1919009760'>
<a href='https://www.blogger.com/post-edit.g?blogID=7709464623091465853&postID=2056549441116328229&from=pencil' title='Edit Post'>
<img alt='' class='icon-action' height='18' src='https://resources.blogblog.com/img/icon18_edit_allbkg.gif' width='18'/>
</a>
</span>
</span>
<div class='post-share-buttons goog-inline-block'>
<a class='goog-inline-block share-button sb-email' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=2056549441116328229&target=email' target='_blank' title='Email This'><span class='share-button-link-text'>Email This</span></a><a class='goog-inline-block share-button sb-blog' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=2056549441116328229&target=blog' onclick='window.open(this.href, "_blank", "height=270,width=475"); return false;' target='_blank' title='BlogThis!'><span class='share-button-link-text'>BlogThis!</span></a><a class='goog-inline-block share-button sb-twitter' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=2056549441116328229&target=twitter' target='_blank' title='Share to Twitter'><span class='share-button-link-text'>Share to Twitter</span></a><a class='goog-inline-block share-button sb-facebook' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=2056549441116328229&target=facebook' onclick='window.open(this.href, "_blank", "height=430,width=640"); return false;' target='_blank' title='Share to Facebook'><span class='share-button-link-text'>Share to Facebook</span></a><a class='goog-inline-block share-button sb-pinterest' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=2056549441116328229&target=pinterest' target='_blank' title='Share to Pinterest'><span class='share-button-link-text'>Share to Pinterest</span></a>
</div>
</div>
<div class='post-footer-line post-footer-line-2'>
<span class='post-labels'>
</span>
</div>
<div class='post-footer-line post-footer-line-3'>
<span class='post-location'>
</span>
</div>
</div>
</div>
</div>

          </div></div>
        

          <div class="date-outer">
        
<h2 class='date-header'><span>Friday, January 28, 2011</span></h2>

          <div class="date-posts">
        
<div class='post-outer'>
<div class='post hentry uncustomized-post-template' itemprop='blogPost' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'>
<meta content='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjS3tFgKa_bIKwNi6P5uLhwjYTbOGFMf8-7thDirGbXwTAM6yLemjSumWIckPB3Q2qgqfBfsk9e498gATOOxRUKI7CWXAR7tKgyrWD5oES30i894LsnOFgbw4lShMr7YAsaPZ5ZpsBx2vb_/s400/blog001.JPG' itemprop='image_url'/>
<meta content='7709464623091465853' itemprop='blogId'/>
<meta content='3008066261580577836' itemprop='postId'/>
<a name='3008066261580577836'></a>
<h3 class='post-title entry-title' itemprop='name'>
<a href='https://kasunkularatne.blogspot.com/2011/01/net-shopping-cart-c-with-lambda.html'>.NET shopping cart (c#) with lambda expressions</a>
</h3>
<div class='post-header'>
<div class='post-header-line-1'></div>
</div>
<div class='post-body entry-content' id='post-body-3008066261580577836' itemprop='description articleBody'>
In this article I am going to explain how to create a simple shopping cart with lambda expressions and generic list.<br />To archive this I am going to create two classes called Product and Basket.<br />Product class supposes to store all the product information and basket class suppose to store list of the products.<br />The following figure shows my product class<br /><br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjS3tFgKa_bIKwNi6P5uLhwjYTbOGFMf8-7thDirGbXwTAM6yLemjSumWIckPB3Q2qgqfBfsk9e498gATOOxRUKI7CWXAR7tKgyrWD5oES30i894LsnOFgbw4lShMr7YAsaPZ5ZpsBx2vb_/s1600/blog001.JPG"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5567341768403390738" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjS3tFgKa_bIKwNi6P5uLhwjYTbOGFMf8-7thDirGbXwTAM6yLemjSumWIckPB3Q2qgqfBfsk9e498gATOOxRUKI7CWXAR7tKgyrWD5oES30i894LsnOFgbw4lShMr7YAsaPZ5ZpsBx2vb_/s400/blog001.JPG" style="display:block; margin:0px; text-align:left;cursor:pointer; cursor:hand;width: 307px; height: 400px;" /></a><br /><br />Then I am going to create next class, class Basket. In this class I got three properties<br /><br /><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitIonq_EQCftpcScC9Higp4ZS3qeiTD31qwvh_AF3mz8ODe5mSyYviDzMdwxQRTHBY6i13bCm_uQG1J-ESd-gC-SZsrNwnr4_tqMx3PnfRTiv9ZoabPWsmnKpx2vl7BnF96gb6Z2wANAaW/s1600/blog002.JPG"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5567342931899210002" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitIonq_EQCftpcScC9Higp4ZS3qeiTD31qwvh_AF3mz8ODe5mSyYviDzMdwxQRTHBY6i13bCm_uQG1J-ESd-gC-SZsrNwnr4_tqMx3PnfRTiv9ZoabPWsmnKpx2vl7BnF96gb6Z2wANAaW/s400/blog002.JPG" style="float: left; margin-top: 0px; margin-right: 10px; margin-bottom: 10px; margin-left: 0px; cursor: pointer; width: 261px; height: 62px; " /></a><br /><br /><br /><div><br />Getters and setters are look like follows<br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhT9kAccQKPAN6QX9IV3lflRy8xf1Rvj-3-T0jBTfY8CnwrRHv_1Sv-MfF5y7GUnwmrTspdSvomy64XQfdLKX6bu40RTeTWSWSN-9bWR5zKO5dmCuecvTkuzL5PaPl2stqBg324d-kfPeIM/s1600/blog003.JPG"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5567343459923999858" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhT9kAccQKPAN6QX9IV3lflRy8xf1Rvj-3-T0jBTfY8CnwrRHv_1Sv-MfF5y7GUnwmrTspdSvomy64XQfdLKX6bu40RTeTWSWSN-9bWR5zKO5dmCuecvTkuzL5PaPl2stqBg324d-kfPeIM/s400/blog003.JPG" style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 261px; height: 101px;" /></a><br /><br /><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div>For the totalAmount I eliminated setter and for the get the total amount I used lambda expression<br /><br /></div><div><span class="Apple-style-span" style="color: rgb(0, 0, 238); -webkit-text-decorations-in-effect: underline; "><img alt="" border="0" id="BLOGGER_PHOTO_ID_5567343798185441666" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEje2rQ6-v7Gng1ezcc-1psTY_c9SPG1V8N0JgAtxfc3AorOMAHQl3XBVWbdwGQ8se6gXqsXX7No5RyLJ_FFzqpap3CovDz8_3i4LhiT_aEWwwXfwRLFXIJqqj3_Koy6ebhS81tEcO0Qodk0/s400/blog004.JPG" style="float: left; margin-top: 0px; margin-right: 10px; margin-bottom: 10px; margin-left: 0px; cursor: pointer; width: 400px; height: 62px; " /></span></div><div><span class="Apple-style-span"><br /></span></div><div><span class="Apple-style-span"><br /></span></div><div><span class="Apple-style-span"><br /></span></div><div><span class="Apple-style-span" style="-webkit-text-decorations-in-effect: underline; "></span><span class="Apple-style-span"><br /></span><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitIonq_EQCftpcScC9Higp4ZS3qeiTD31qwvh_AF3mz8ODe5mSyYviDzMdwxQRTHBY6i13bCm_uQG1J-ESd-gC-SZsrNwnr4_tqMx3PnfRTiv9ZoabPWsmnKpx2vl7BnF96gb6Z2wANAaW/s1600/blog002.JPG"></a>I am going to retrieve item count as follows<br /><br /></div><div><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYqqTZ53am9cHQ42HaveDIqN_zI1OVtls4J3zkZNbxc8Cg_K4sW1Or515Y7nX3j9uTgoe5CkpXCYqbmh8wVnq5gVDgkNP2DkJZjhqxrtckg787rQoDb2hmW3YKctBL18B-9aMASrxttYxV/s1600/blog005.JPG"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5567345872534596370" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYqqTZ53am9cHQ42HaveDIqN_zI1OVtls4J3zkZNbxc8Cg_K4sW1Or515Y7nX3j9uTgoe5CkpXCYqbmh8wVnq5gVDgkNP2DkJZjhqxrtckg787rQoDb2hmW3YKctBL18B-9aMASrxttYxV/s400/blog005.JPG" style="cursor: pointer; width: 330px; height: 95px; " /></a></div><div><p class="MsoNormal">Apart from that I have a method to remove products from the basket and I am using lambda expressions for that as well.</p><p class="MsoNormal"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLILsPvcaGtn0Du8dUoJbydX4nMxVzWr4-7CVAfq4O5HJ-TG0_KV4qHnfTM-2IQ0T8j0EkTdp2a2fLYVcNz1bL2yKx_gQzoxrdoXRa7JJpFsez-sK1um6AjjBa5rUwEor5v0LIbcn9srvo/s1600/blog005.JPG"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5567346323507319794" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLILsPvcaGtn0Du8dUoJbydX4nMxVzWr4-7CVAfq4O5HJ-TG0_KV4qHnfTM-2IQ0T8j0EkTdp2a2fLYVcNz1bL2yKx_gQzoxrdoXRa7JJpFsez-sK1um6AjjBa5rUwEor5v0LIbcn9srvo/s400/blog005.JPG" style="cursor: pointer; width: 400px; height: 56px; " /></a><br /></p><p class="MsoNormal"></p><p class="MsoNormal">You can download Product class from here and Basket class from here.</p>  <p class="MsoNormal">Now let’s see how to use these two classes in the real world.</p>  <p class="MsoNormal"><o:p> </o:p></p>  <ol style="margin-top:0in" start="1" type="1">  <li class="MsoNormal" style="mso-list:l0 level1 lfo1;tab-stops:list .5in">create      an instance of basket class</li>  <li class="MsoNormal" style="mso-list:l0 level1 lfo1;tab-stops:list .5in">create      an instance of Product class and add product details</li>  <li class="MsoNormal" style="mso-list:l0 level1 lfo1;tab-stops:list .5in">Add      product instance to basket instance. </li>  <li class="MsoNormal" style="mso-list:l0 level1 lfo1;tab-stops:list .5in">Add      basket instance to session variable for future use. </li> </ol>  <span style="font-size:12.0pt;font-family:"Times New Roman";mso-fareast-font-family: "Times New Roman";mso-ansi-language:EN-US;mso-fareast-language:EN-US; mso-bidi-language:AR-SA"><span class="Apple-style-span" style="font-family: Georgia, serif; "><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtfsn5Zq84tkgw95TctE92rgW1rGw7_dFRO7rot2AQAh_616J40uvys5UohfyXAWr39wSheVrcreg4vUss6r1IHviln1tfnmWdKyVNef5CrxmFNBSef_GoLl4-tyLTtSf_fCtJ4kTxZFab/s1600/blog006.JPG"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5567347902000482994" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtfsn5Zq84tkgw95TctE92rgW1rGw7_dFRO7rot2AQAh_616J40uvys5UohfyXAWr39wSheVrcreg4vUss6r1IHviln1tfnmWdKyVNef5CrxmFNBSef_GoLl4-tyLTtSf_fCtJ4kTxZFab/s400/blog006.JPG" style="cursor: pointer; width: 400px; height: 202px; " /></a></span><!--[endif]--></span><p></p></div><div><span><p class="MsoNormal"><span class="Apple-style-span">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</span></p><p class="MsoNormal"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpOUZTc82K7yJwcSP7HOHPVoP0LVpM_DlNsbls4UeW_p6PPilzEUOwjlHzkox1jw1qn0hHk2P4f9cUI4uJX91JDC92T1A7NlPYCIUfHCAUzHNiqa1Ds1f8TnuL9tFgFrKnB5vCzNQCMnu6/s1600/blog007.JPG"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5567349447078204754" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpOUZTc82K7yJwcSP7HOHPVoP0LVpM_DlNsbls4UeW_p6PPilzEUOwjlHzkox1jw1qn0hHk2P4f9cUI4uJX91JDC92T1A7NlPYCIUfHCAUzHNiqa1Ds1f8TnuL9tFgFrKnB5vCzNQCMnu6/s400/blog007.JPG" style="cursor: pointer; width: 400px; height: 350px; " /></a></p><p class="MsoNormal" style="font-family: 'Times New Roman'; font-size: 12pt; "> </p></span></div>
<div style='clear: both;'></div>
</div>
<div class='post-footer'>
<div class='post-footer-line post-footer-line-1'>
<span class='post-author vcard'>
Posted by
<span class='fn' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'>
<meta content='https://www.blogger.com/profile/00966916158670098102' itemprop='url'/>
<a class='g-profile' href='https://www.blogger.com/profile/00966916158670098102' rel='author' title='author profile'>
<span itemprop='name'>Kasun Kularatne</span>
</a>
</span>
</span>
<span class='post-timestamp'>
at
<meta content='http://kasunkularatne.blogspot.com/2011/01/net-shopping-cart-c-with-lambda.html' itemprop='url'/>
<a class='timestamp-link' href='https://kasunkularatne.blogspot.com/2011/01/net-shopping-cart-c-with-lambda.html' rel='bookmark' title='permanent link'><abbr class='published' itemprop='datePublished' title='2011-01-28T12:37:00-08:00'>12:37 PM</abbr></a>
</span>
<span class='post-comment-link'>
<a class='comment-link' href='https://kasunkularatne.blogspot.com/2011/01/net-shopping-cart-c-with-lambda.html#comment-form' onclick=''>
No comments:
  </a>
</span>
<span class='post-icons'>
<span class='item-control blog-admin pid-1919009760'>
<a href='https://www.blogger.com/post-edit.g?blogID=7709464623091465853&postID=3008066261580577836&from=pencil' title='Edit Post'>
<img alt='' class='icon-action' height='18' src='https://resources.blogblog.com/img/icon18_edit_allbkg.gif' width='18'/>
</a>
</span>
</span>
<div class='post-share-buttons goog-inline-block'>
<a class='goog-inline-block share-button sb-email' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=3008066261580577836&target=email' target='_blank' title='Email This'><span class='share-button-link-text'>Email This</span></a><a class='goog-inline-block share-button sb-blog' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=3008066261580577836&target=blog' onclick='window.open(this.href, "_blank", "height=270,width=475"); return false;' target='_blank' title='BlogThis!'><span class='share-button-link-text'>BlogThis!</span></a><a class='goog-inline-block share-button sb-twitter' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=3008066261580577836&target=twitter' target='_blank' title='Share to Twitter'><span class='share-button-link-text'>Share to Twitter</span></a><a class='goog-inline-block share-button sb-facebook' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=3008066261580577836&target=facebook' onclick='window.open(this.href, "_blank", "height=430,width=640"); return false;' target='_blank' title='Share to Facebook'><span class='share-button-link-text'>Share to Facebook</span></a><a class='goog-inline-block share-button sb-pinterest' href='https://www.blogger.com/share-post.g?blogID=7709464623091465853&postID=3008066261580577836&target=pinterest' target='_blank' title='Share to Pinterest'><span class='share-button-link-text'>Share to Pinterest</span></a>
</div>
</div>
<div class='post-footer-line post-footer-line-2'>
<span class='post-labels'>
Labels:
<a href='https://kasunkularatne.blogspot.com/search/label/c%23' rel='tag'>c#</a>,
<a href='https://kasunkularatne.blogspot.com/search/label/lambda%20expressions' rel='tag'>lambda expressions</a>,
<a href='https://kasunkularatne.blogspot.com/search/label/shopping%20cart' rel='tag'>shopping cart</a>
</span>
</div>
<div class='post-footer-line post-footer-line-3'>
<span class='post-location'>
</span>
</div>
</div>
</div>
</div>

        </div></div>
      
</div>
<div class='blog-pager' id='blog-pager'>
<span id='blog-pager-newer-link'>
<a class='blog-pager-newer-link' href='https://kasunkularatne.blogspot.com/' id='Blog1_blog-pager-newer-link' title='Newer Posts'>Newer Posts</a>
</span>
<a class='home-link' href='https://kasunkularatne.blogspot.com/'>Home</a>
</div>
<div class='clear'></div>
<div class='blog-feeds'>
<div class='feed-links'>
Subscribe to:
<a class='feed-link' href='https://kasunkularatne.blogspot.com/feeds/posts/default' target='_blank' type='application/atom+xml'>Posts (Atom)</a>
</div>
</div>
</div></div>
</div>
</div>
<div class='column-left-outer'>
<div class='column-left-inner'>
<aside>
</aside>
</div>
</div>
<div class='column-right-outer'>
<div class='column-right-inner'>
<aside>
<div class='sidebar section' id='sidebar-right-1'><div class='widget BlogArchive' data-version='1' id='BlogArchive1'>
<h2>Blog Archive</h2>
<div class='widget-content'>
<div id='ArchiveList'>
<div id='BlogArchive1_ArchiveList'>
<ul class='hierarchy'>
<li class='archivedate expanded'>
<a class='toggle' href='javascript:void(0)'>
<span class='zippy toggle-open'>

        ▼ 
      
</span>
</a>
<a class='post-count-link' href='https://kasunkularatne.blogspot.com/2011/'>
2011
</a>
<span class='post-count' dir='ltr'>(5)</span>
<ul class='hierarchy'>
<li class='archivedate expanded'>
<a class='toggle' href='javascript:void(0)'>
<span class='zippy toggle-open'>

        ▼ 
      
</span>
</a>
<a class='post-count-link' href='https://kasunkularatne.blogspot.com/2011/11/'>
November
</a>
<span class='post-count' dir='ltr'>(1)</span>
<ul class='posts'>
<li><a href='https://kasunkularatne.blogspot.com/2011/11/xml-manipulation-using-net-c-part-ii.html'>XML Manipulation using .NET (C#) PART II</a></li>
</ul>
</li>
</ul>
<ul class='hierarchy'>
<li class='archivedate collapsed'>
<a class='toggle' href='javascript:void(0)'>
<span class='zippy'>

        ► 
      
</span>
</a>
<a class='post-count-link' href='https://kasunkularatne.blogspot.com/2011/10/'>
October
</a>
<span class='post-count' dir='ltr'>(1)</span>
<ul class='posts'>
<li><a href='https://kasunkularatne.blogspot.com/2011/10/xml-manipulation-using-net-c.html'>XML Manipulation using .NET (C#) PART I</a></li>
</ul>
</li>
</ul>
<ul class='hierarchy'>
<li class='archivedate collapsed'>
<a class='toggle' href='javascript:void(0)'>
<span class='zippy'>

        ► 
      
</span>
</a>
<a class='post-count-link' href='https://kasunkularatne.blogspot.com/2011/09/'>
September
</a>
<span class='post-count' dir='ltr'>(1)</span>
<ul class='posts'>
<li><a href='https://kasunkularatne.blogspot.com/2011/09/web-accessibility.html'>Web Accessibility</a></li>
</ul>
</li>
</ul>
<ul class='hierarchy'>
<li class='archivedate collapsed'>
<a class='toggle' href='javascript:void(0)'>
<span class='zippy'>

        ► 
      
</span>
</a>
<a class='post-count-link' href='https://kasunkularatne.blogspot.com/2011/02/'>
February
</a>
<span class='post-count' dir='ltr'>(1)</span>
<ul class='posts'>
<li><a href='https://kasunkularatne.blogspot.com/2011/02/evolution-of-integration-patterns-and.html'>Evolution of integration patterns and why Enterpri...</a></li>
</ul>
</li>
</ul>
<ul class='hierarchy'>
<li class='archivedate collapsed'>
<a class='toggle' href='javascript:void(0)'>
<span class='zippy'>

        ► 
      
</span>
</a>
<a class='post-count-link' href='https://kasunkularatne.blogspot.com/2011/01/'>
January
</a>
<span class='post-count' dir='ltr'>(1)</span>
<ul class='posts'>
<li><a href='https://kasunkularatne.blogspot.com/2011/01/net-shopping-cart-c-with-lambda.html'>.NET shopping cart (c#) with lambda expressions</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class='clear'></div>
</div>
</div></div>
</aside>
</div>
</div>
</div>
<div style='clear: both'></div>
<!-- columns -->
</div>
<!-- main -->
</div>
</div>
<div class='main-cap-bottom cap-bottom'>
<div class='cap-left'></div>
<div class='cap-right'></div>
</div>
</div>
<footer>
<div class='footer-outer'>
<div class='footer-cap-top cap-top'>
<div class='cap-left'></div>
<div class='cap-right'></div>
</div>
<div class='fauxborder-left footer-fauxborder-left'>
<div class='fauxborder-right footer-fauxborder-right'></div>
<div class='region-inner footer-inner'>
<div class='foot no-items section' id='footer-1'></div>
<table border='0' cellpadding='0' cellspacing='0' class='section-columns columns-2'>
<tbody>
<tr>
<td class='first columns-cell'>
<div class='foot section' id='footer-2-1'><div class='widget Profile' data-version='1' id='Profile1'>
<h2>About Me</h2>
<div class='widget-content'>
<a href='https://www.blogger.com/profile/00966916158670098102'><img alt='My photo' class='profile-img' height='80' src='//2.bp.blogspot.com/_cr0-P_sClrk/S032Xj4wxYI/AAAAAAAAAAQ/3lC4vCoeSD4/S220-s80/DSC00055.JPG' width='60'/></a>
<dl class='profile-datablock'>
<dt class='profile-data'>
<a class='profile-name-link g-profile' href='https://www.blogger.com/profile/00966916158670098102' rel='author' style='background-image: url(//www.blogger.com/img/logo-16.png);'>
Kasun Kularatne
</a>
</dt>
</dl>
<a class='profile-link' href='https://www.blogger.com/profile/00966916158670098102' rel='author'>View my complete profile</a>
<div class='clear'></div>
</div>
</div></div>
</td>
<td class='columns-cell'>
<div class='foot no-items section' id='footer-2-2'></div>
</td>
</tr>
</tbody>
</table>
<!-- outside of the include in order to lock Attribution widget -->
<div class='foot section' id='footer-3' name='Footer'><div class='widget Attribution' data-version='1' id='Attribution1'>
<div class='widget-content' style='text-align: center;'>
Simple theme. Powered by <a href='https://www.blogger.com' target='_blank'>Blogger</a>.
</div>
<div class='clear'></div>
</div></div>
</div>
</div>
<div class='footer-cap-bottom cap-bottom'>
<div class='cap-left'></div>
<div class='cap-right'></div>
</div>
</div>
</footer>
<!-- content -->
</div>
</div>
<div class='content-cap-bottom cap-bottom'>
<div class='cap-left'></div>
<div class='cap-right'></div>
</div>
</div>
</div>
<script type='text/javascript'>
    window.setTimeout(function() {
        document.body.className = document.body.className.replace('loading', '');
      }, 10);
  </script>

<script type="text/javascript" src="https://www.blogger.com/static/v1/widgets/4140855455-widgets.js"></script>
<script type='text/javascript'>
window['__wavt'] = 'AOuZoY4eQdKAfZm51oyHsh3Xdj3h2MDr-Q:1726558944031';_WidgetManager._Init('//www.blogger.com/rearrange?blogID\x3d7709464623091465853','//kasunkularatne.blogspot.com/2011/','7709464623091465853');
_WidgetManager._SetDataContext([{'name': 'blog', 'data': {'blogId': '7709464623091465853', 'title': 'Code [A]lpha', 'url': 'https://kasunkularatne.blogspot.com/2011/', 'canonicalUrl': 'http://kasunkularatne.blogspot.com/2011/', 'homepageUrl': 'https://kasunkularatne.blogspot.com/', 'searchUrl': 'https://kasunkularatne.blogspot.com/search', 'canonicalHomepageUrl': 'http://kasunkularatne.blogspot.com/', 'blogspotFaviconUrl': 'https://kasunkularatne.blogspot.com/favicon.ico', 'bloggerUrl': 'https://www.blogger.com', 'hasCustomDomain': false, 'httpsEnabled': true, 'enabledCommentProfileImages': true, 'gPlusViewType': 'FILTERED_POSTMOD', 'adultContent': false, 'analyticsAccountNumber': '', 'encoding': 'UTF-8', 'locale': 'en', 'localeUnderscoreDelimited': 'en', 'languageDirection': 'ltr', 'isPrivate': false, 'isMobile': false, 'isMobileRequest': false, 'mobileClass': '', 'isPrivateBlog': false, 'isDynamicViewsAvailable': true, 'feedLinks': '\x3clink rel\x3d\x22alternate\x22 type\x3d\x22application/atom+xml\x22 title\x3d\x22Code [A]lpha - Atom\x22 href\x3d\x22https://kasunkularatne.blogspot.com/feeds/posts/default\x22 /\x3e\n\x3clink rel\x3d\x22alternate\x22 type\x3d\x22application/rss+xml\x22 title\x3d\x22Code [A]lpha - RSS\x22 href\x3d\x22https://kasunkularatne.blogspot.com/feeds/posts/default?alt\x3drss\x22 /\x3e\n\x3clink rel\x3d\x22service.post\x22 type\x3d\x22application/atom+xml\x22 title\x3d\x22Code [A]lpha - Atom\x22 href\x3d\x22https://www.blogger.com/feeds/7709464623091465853/posts/default\x22 /\x3e\n', 'meTag': '', 'adsenseHostId': 'ca-host-pub-1556223355139109', 'adsenseHasAds': false, 'adsenseAutoAds': false, 'boqCommentIframeForm': true, 'loginRedirectParam': '', 'view': '', 'dynamicViewsCommentsSrc': '//www.blogblog.com/dynamicviews/4224c15c4e7c9321/js/comments.js', 'dynamicViewsScriptSrc': '//www.blogblog.com/dynamicviews/5702e3d62c3de6e9', 'plusOneApiSrc': 'https://apis.google.com/js/platform.js', 'disableGComments': true, 'interstitialAccepted': false, 'sharing': {'platforms': [{'name': 'Get link', 'key': 'link', 'shareMessage': 'Get link', 'target': ''}, {'name': 'Facebook', 'key': 'facebook', 'shareMessage': 'Share to Facebook', 'target': 'facebook'}, {'name': 'BlogThis!', 'key': 'blogThis', 'shareMessage': 'BlogThis!', 'target': 'blog'}, {'name': 'Twitter', 'key': 'twitter', 'shareMessage': 'Share to Twitter', 'target': 'twitter'}, {'name': 'Pinterest', 'key': 'pinterest', 'shareMessage': 'Share to Pinterest', 'target': 'pinterest'}, {'name': 'Email', 'key': 'email', 'shareMessage': 'Email', 'target': 'email'}], 'disableGooglePlus': true, 'googlePlusShareButtonWidth': 0, 'googlePlusBootstrap': '\x3cscript type\x3d\x22text/javascript\x22\x3ewindow.___gcfg \x3d {\x27lang\x27: \x27en\x27};\x3c/script\x3e'}, 'hasCustomJumpLinkMessage': false, 'jumpLinkMessage': 'Read more', 'pageType': 'archive', 'pageName': '2011', 'pageTitle': 'Code [A]lpha: 2011'}}, {'name': 'features', 'data': {}}, {'name': 'messages', 'data': {'edit': 'Edit', 'linkCopiedToClipboard': 'Link copied to clipboard!', 'ok': 'Ok', 'postLink': 'Post Link'}}, {'name': 'template', 'data': {'name': 'Simple', 'localizedName': 'Simple', 'isResponsive': false, 'isAlternateRendering': false, 'isCustom': false, 'variant': 'pale', 'variantId': 'pale'}}, {'name': 'view', 'data': {'classic': {'name': 'classic', 'url': '?view\x3dclassic'}, 'flipcard': {'name': 'flipcard', 'url': '?view\x3dflipcard'}, 'magazine': {'name': 'magazine', 'url': '?view\x3dmagazine'}, 'mosaic': {'name': 'mosaic', 'url': '?view\x3dmosaic'}, 'sidebar': {'name': 'sidebar', 'url': '?view\x3dsidebar'}, 'snapshot': {'name': 'snapshot', 'url': '?view\x3dsnapshot'}, 'timeslide': {'name': 'timeslide', 'url': '?view\x3dtimeslide'}, 'isMobile': false, 'title': 'Code [A]lpha', 'description': ':: Impossible is not a fact. It\x27s an opinion ::', 'url': 'https://kasunkularatne.blogspot.com/2011/', 'type': 'feed', 'isSingleItem': false, 'isMultipleItems': true, 'isError': false, 'isPage': false, 'isPost': false, 'isHomepage': false, 'isArchive': true, 'isLabelSearch': false, 'archive': {'year': 2011, 'rangeMessage': 'Showing posts from 2011'}}}]);
_WidgetManager._RegisterWidget('_NavbarView', new _WidgetInfo('Navbar1', 'navbar', document.getElementById('Navbar1'), {}, 'displayModeFull'));
_WidgetManager._RegisterWidget('_HeaderView', new _WidgetInfo('Header1', 'header', document.getElementById('Header1'), {}, 'displayModeFull'));
_WidgetManager._RegisterWidget('_BlogView', new _WidgetInfo('Blog1', 'main', document.getElementById('Blog1'), {'cmtInteractionsEnabled': false, 'lightboxEnabled': true, 'lightboxModuleUrl': 'https://www.blogger.com/static/v1/jsbin/2675689289-lbx.js', 'lightboxCssUrl': 'https://www.blogger.com/static/v1/v-css/13464135-lightbox_bundle.css'}, 'displayModeFull'));
_WidgetManager._RegisterWidget('_BlogArchiveView', new _WidgetInfo('BlogArchive1', 'sidebar-right-1', document.getElementById('BlogArchive1'), {'languageDirection': 'ltr', 'loadingMessage': 'Loading\x26hellip;'}, 'displayModeFull'));
_WidgetManager._RegisterWidget('_ProfileView', new _WidgetInfo('Profile1', 'footer-2-1', document.getElementById('Profile1'), {}, 'displayModeFull'));
_WidgetManager._RegisterWidget('_AttributionView', new _WidgetInfo('Attribution1', 'footer-3', document.getElementById('Attribution1'), {}, 'displayModeFull'));
</script>
</body>
</html>