Saturday 22 November 2014

Linq to XML Example 1



Hi guys, today I will show you one demo on LINQ to XML, this is very very helpful for the beginners who are trying to learn LINQ. Here I have prepared one demo like I have a xml file with list of employees, when a user give the employee ID it should populate the employee Name.
First Create a XML File
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee>
    <ID>001</ID>
    <Name>Rohit</Name>
  </Employee>
  <Employee>
    <ID>002</ID>
    <Name>Sam</Name>
  </Employee>
  <Employee>
    <ID>003</ID>
    <Name>Jonshon</Name>
  </Employee>
  <Employee>
    <ID>004</ID>
    <Name>Rocky</Name>
  </Employee>
</Employees>

Then design the page like this
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        Enter ID :
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
&nbsp;
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
   
    </div>
    </form>
</body>
</html>

Now write the following code in the aspx.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        XElement obj = XElement.Load(Server.MapPath("~/XMLFile.xml"));
      
       string employeeName= obj.Descendants("Employee")
                            .Where(x => (string)x.Element("ID") == TextBox1.Text)
                            .Select(x=>(string)x.Element("Name")).SingleOrDefault();
       if (!string.IsNullOrEmpty(employeeName))
       {
           Label1.Text = employeeName;
       }
       else
       {
           Label1.Text = "No Employee";
       }
    }
}

Demo
 

CACHING JS, IMAGES AND STATIC CONTENTS IN IIS



Hi guys, i got one question in asp.net forum, like how to cache images and js files , I preferably using IIS for caching all the static contents. So here I will demonstrate you how to configure the iis to cache all the static contents.

Step 1 Open IIS


Step 2 Go to the feature view and double click the Output Caching

Step 3 Right click and click on add

Step 4 Give the extentsion name and check the User-Mode caching
 Step 5 Click on OK