Friday, October 29, 2010

Global.asax file Info

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.SessionState" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        Application["Hits"] = 0;
        Application["HitsCount"] = 0;
        Application["Sessions"] = 0;
        Application["TerminatedSessions"] = 0;
    }
    //The BeginRequest event is fired for every hit to every page in the site
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        Application.Lock();
        Application["Hits"] = (int)Application["Hits"] + 1;
        Application.UnLock();
    }
    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown
        SmtpClient smtpClient = new SmtpClient();
        string strUname = ConfigurationManager.AppSettings["smtpuser"].ToString();
        string strPassword = ConfigurationManager.AppSettings["smtppass"].ToString();
        smtpClient.Credentials = new NetworkCredential(strUname, strPassword);
        smtpClient.Send("BlankSolution Error", "abc@abc.com", "Application Down", Server.GetLastError().Message);
    }

    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs
        try
        {
            SmtpClient smtpClient = new SmtpClient();
            string strUname = ConfigurationManager.AppSettings["smtpuser"].ToString();
            string strPassword = ConfigurationManager.AppSettings["smtppass"].ToString();
            smtpClient.Credentials = new NetworkCredential("abc@abc.com", "JUShah12$");
            smtpClient.Send("BlankSolution error", "abc@abc.com", Server.GetLastError().Message, Server.GetLastError().InnerException.StackTrace);
            // Response.Redirect("~/ErrorPage/ErrorPage.aspx");
        }
        catch (Exception)
        {

        }
    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Application.Lock();
        Application["Sessions"] = (int)Application["Sessions"] + 1;
        Application["HitsCount"] = (int)Application["HitsCount"] + 1;

        Session["AdminID"] = "";
        Session["AdminEmail"] = "";
        Session["AdminRole"] = "";
        Session["AdminFullName"] = "";

        Session["CenterID"] = "";
        Session["CenterName"] = "";
       
        Application.UnLock();
    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.
        Application.Lock();
        Application["TerminatedSessions"] = (int)Application["TerminatedSessions"] + 1;
        Application.UnLock();
    }
   
</script>

Encrypt and Decrypt class

 #region Encrypt
        public string Encrypt(string simpletext, string keys)
        {
            try
            {
                XCryptEngine xe = new XCryptEngine();

                xe.Algorithm = XCrypt.XCryptEngine.AlgorithmType.DES; //DES = Data Encryption Standard

                string cipher = xe.Encrypt(simpletext, keys);
                if (cipher != null)
                    return (cipher);
                else
                    return null;
            }

            catch (Exception ex)
            {
                return null;
            }
        }
        #endregion

        #region Decrypt
        public string Decrypt(string simpletext, string keys)
        {
            try
            {
                XCryptEngine xe = new XCryptEngine();

                xe.Algorithm = XCrypt.XCryptEngine.AlgorithmType.DES;

                //  Console.WriteLine(xe.Decrypt(ciphertext, Days));
                simpletext = simpletext.Replace(" ", "+");
                string cipertext = xe.Decrypt(simpletext, keys);
                if (cipertext != null)
                    return (cipertext);
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        #endregion

Thursday, October 28, 2010

101 LINQ Samples

http://msdn.microsoft.com/en-us/vcsharp/aa336746

JQuery Example

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="frmTestJQuery.aspx.cs" Inherits="Account_frmTestJQuery" %>

<!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>
    <style type="text/css">
        .clsLbl
        {
            color: Blue;
        }
       
        .clsVis
        {
            display: none;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center">
        Hello Welcome...
        <table>
            <tr>
                <td>
                    <asp:Label ID="lblUsername" runat="server" Text="Username" />
                </td>
                <td>
                    <input type="text" id="txtUsername" runat="server" value="Hello" />
                </td>
            </tr>

            <tr>
                <td>
                    <asp:Label ID="lblUsername1" runat="server" Text="Username1" />
                </td>
                <td>
                    <asp:TextBox ID="txtUsername1" runat="server" Text="write your Username here"></asp:TextBox>
                </td>
            </tr>

            <tr>
                <td>
                    <asp:Label ID="lblTest" runat="server" Text="Test" />
                </td>
                <td>
                    <input type="text" id="txtTest" isgridtext="True" value="Test" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lblUserPhone" runat="server" Text="Phone" />
                </td>
                <td>
                    <input type="text" id="txtPhone" runat="server" />
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input id="Button1" type="button" class="clsButton" value="Submit" runat="server" />
                </td>
            </tr>
            <tr>
                <td id="tdTestID" runat="server" colspan="2" align="center">
                    <span id="spnTest" runat="server">abcd</span>
                    <!-- whatever HTML control we can write here to alert for strTestID of jquery Function -->
                </td>
            </tr>
            <tr>
                <td id="td1" runat="server" colspan="2" align="center">
                    <a href="http://www.google.com" target="_blank">www.Google.com</a>
                </td>
            </tr>
        </table>
        <div id="dvUserInfo" align="center">
            <table border="1">
                <tr>
                    <td>
                        <asp:Label ID="lblCheck" runat="server" Text="Check" />
                    </td>
                </tr>
            </table>
            <table border="1">
                <tr>
                    <td>
                        <div id="divUserDetail">
                            Show User Detail</div>
                    </td>
                </tr>
            </table>
            <table border="0">
                <tr>
                    <td>
                        &nbsp;
                    </td>
                </tr>
            </table>
            <table border="1">
                <tr>
                    <td>
                        <asp:DropDownList ID="ddlDropDown1" runat="server">
                            <asp:ListItem Value="Home_1">Home</asp:ListItem>
                            <asp:ListItem Value="Office_1">Office</asp:ListItem>
                            <asp:ListItem Value="FarmHouse_1">FarmHouse</asp:ListItem>
                            <asp:ListItem Value="Food_1">Food1</asp:ListItem>
                            <asp:ListItem Value="Food_2">Food2</asp:ListItem>
                        </asp:DropDownList>
                    </td>
                    <td>
                        <!--<div id="dvForNewDropDown">
                        </div> -->

                        <asp:DropDownList ID="ddlDropDown2" runat="server">
                        </asp:DropDownList>

                    </td>

                    <td>
                        <!--<div id="dvForNewDropDownNot">
                        </div> -->

                        <asp:DropDownList ID="ddlDropDownNot" runat="server">
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>
                        <input id="btnSave" type="button" class="clsButton" value="Save" runat="server"  />
                    </td>
                    <td>
                        <input id="btnNewDropDownClone" type="button" class="clsButton" value="Drop down Clone" runat="server" />
                    </td>
                    <td>
                        <input id="btnNewDropDownWithNot" type="button" class="clsButton" value="Not Drop down Clone" runat="server" />
                    </td>
                </tr>
            </table>
        </div>
    </div>
    </form>
</body>
<script src="../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

    $(document).ready(function () {
        //Code goes here

        //alert($("#txtUsername").val()); // ID
        //alert($("#txtUsername1").val()); // ID
        //alert($("input").val());  // Control
        //alert($("div").val());    // Control
        //alert($("div input").val()); // Inner Control
        //alert($(".clsButton").val());  // class

        //alert($("input[type='button']").val()); // Selection on standard attributes
        //alert($("input[type='text']").val()); // Selection on standard attributes
        //alert($("input[ID='txtUsername1']").val()); // Selection on standard attributes
        //alert($("input[value='Submit']").val()); // Selection on standard attributes

        //alert($("input[IsGridText='True']").val()); // Selection on custome attributes



        //--Functions

        // VAL()
        //var strUserName = $("#txtPhone").val();  // VAL()
        //$("#txtPhone").val("079232323");         // VAL()


        // HTML()
        //var strTestID = $("#tdTestID").html();
        //alert(strTestID);
        //$("#tdTestID").html("<a id='aHref' href='' OnClick='alert(1)'> Click Here </a>");

        // TEXT      the main difference between Text and Html is that .. Html will get all the html and text will get only text value.
        //var strTestID = $("#tdTestID").text();
        //alert(strTestID);


        // Attr (attribute)
        //var IsGridText = $("#txtTest").attr("IsGridText");
        //alert(IsGridText);
        //$("#txtTest").attr("IsGridText", "False");
        //$("#txtTest").attr({ IsGridText: 'True', IsSelected: 'True' });

        // Css (style sheet)
        //var varUsername = $("#txtUsername").css("color");
        //alert(varUsername);
        //$("#txtUsername").css("color", "red");
        //$("#txtUsername").css({ 'height': '150px', 'width' : '150px' });


        // Each
        //$("input").each(function () {
        //    alert($(this).val());
        // })

        //$("input[type='TEXT']").each(function () {
        //    alert($(this).val());
        //})


        // toggleClass()
        //$("#dvUserInfo").toggleClass("Content");

        // height()
        //$("#dvUserInfo").height();

        // hide()
        //$("#dvUserInfo").hide();

        // show()
        //$("#dvUserInfo").show();


        // appendTo
        //$("<div>Hello</div>").appendTo("#<%= lblCheck.ClientID %>");
        //alert($("#<%= lblCheck.ClientID %>").html())
        //$("#<%= lblCheck.ClientID %>").append("<div>Hello</div>");


        // change()
        //$("#txtUsername").change(function () {
        //   alert('Change Check...');
        //});

        //click()
        //$("a").click(function () {
        //    alert('Hi');
        //});

        //dblclick()
        //$("a").dblclick(function () {
        //  alert('Hi');
        //});

        //focus()
        //$("#txtUsername1").focus();

        //focusIn()
        //$("#txtUsername").focusIn(function());

        //hover()
        //$("#lblCheck").hover(function () {
        //  alert('Hover Check');
        //});

        //keydown()
        //$("#txtUsername").keydown(function () {
        //  alert('Key Down Check function... Hello 123 Hello 123');
        //});


        //keyup()
        //$("#txtUsername").keyup(function () {
        //   alert('Hi');
        //});

        //keypress ()
        //$("#txtUsername").keypress(function () {
        //alert('Hi');
        //});

        //mousedown()
        //$("#txtUsername").mousedown(function () {
        //    alert('Hi');
        //});

        //mouseup()
        //$("#txtUsername").mouseup(function () {
        //  alert('Hi');
        //});

        //mousemove()
        //$("#txtUsername").mousemove(function () {
        //  alert('Hi');
        //});


        /*
        //Get
        .val()
        .html()
        .text()


        //Set
        .val(1)
        .html(1)
        .text(1)

        //Get
        .attr("Class")
        .css("Height")

        //Set
        .attr("Class", "clsUserInfo")
        .css("Color", "#CCC")
        */

        //-- will have to ask about  haseClass(), toggleClass(), height(), innerHeight(), outerHeight(), width(), innerWidth (), outerWidth () ,
        //-- fadeIn(), fadeOut(), appendTo   

        // toggleClass
        $("#<%= lblCheck.ClientID %>").click(function () {
            $(this).toggleClass("clsLbl");  //-- Color Change css applied
            $("#divUserDetail").toggleClass("clsVis"); //-- div Visible On/Off css applied
        });


        // Change()
        //$("#ddlDropDown1").change(function () {
        // alert($("#ddlDropDown1").val());
        //});


        // click
        $("#btnSave").click(function () {
            alert($("#<%= ddlDropDown1.ClientID %>").val());
        });

        // Clone
        $("#btnNewDropDownClone").click(function () {
            //$("#ddlDropDown1").clone().appendTo("#dvForNewDropDown");
            $("#ddlDropDown2").html("");
            $("#ddlDropDown1 option").clone().appendTo("#ddlDropDown2");
        });

        // Not
        $("#btnNewDropDownWithNot").click(function () {
            $("#ddlDropDownNot").html("");
            $("#ddlDropDown1 option").not("[value*='Food']").clone().appendTo("#ddlDropDownNot");
            //$("#ddlDropDown1").find("!option[value*='Food']").clone().appendTo("#ddlDropDownNot"); // -- But not working
        });


    });

</script>
</html>

Tuesday, October 26, 2010

JQuery

JQuery


Ready
-----------------------------------
$(document).ready(function(){
    alert('hi');
})

$(document).ready(FormSetting)
Function FormSetting()
{
    alert('hi');
}
-----------------------------------

Selection Criteria
-----------------------------------
=> ID
   $("#txtUserName")

=> Control
   $("input")
   $("div")

=> Inner Control
   $("div div input")

=> Class
   $(".button")

=> Selection on standard attributes
   $("input[type='button']")

=> Selection on custome attributes
   <input type="text" IsGridText="True" />
   $("input[IsGridText ='True']")
-----------------------------------



       //Get
            .val()
            .html()
            .text()

       //Set
            .val(1)
            .html(1)
            .text(1)

       //Get
            .attr("Class")
            .css("Height")

       //Set
            .attr("Class", "clsUserInfo")
            .css("Color", "#CCC")



------------------------------------

Functions
-----------------------------------
=> VAL()
   Var strUserName = $("#txtUserName).val();
   $("#txtUserName).val("jsd24");

=> HTML()
   Var strInnerHtml = $("#divUserInfo).html();
   $("#divUserInfo).html("<a href='#'     OnClick='Alert(1)'>Click Me</a>");

=> Attr ( attribute)
   var IsGridText = $("#txtUserName").attr("IsGridText");
   $("#txtUserName").attr("IsGridText", "False");
   $("#txtUserName").attr({IsGridText:'True', IsSelected:'True'});

=> Css (style sheet)
   var color = $("#txtUserName").css("color");
   $("#txtUserName").css("color", "red");
   $("#txtUserName").css({'width': '100px', 'height':'25px'});

=> Each
   $("input").each(function() { $(this).val("jd"); })

=> addClass()
   $("input[type='button']").addClass("button");

=> removeClass()
   $("input[type='button']").removeClass("button");

=> haseClass()
   $("#txtUserName").haseClass("UserName");
   $("#txtUserName").haseClass("EmailID");

=> toggleClass()
   $("#divUserInfo").toggleClass("Content");

=> height()
   $("#divUserInfo").height();

=> innerHeight()
   $("#divUserInfo").innerHeight();

=> outerHeight()
   $("#divUserInfo").outerHeight();

=> width()
   $("#divUserInfo").width();

=> innerWidth ()
   $("#divUserInfo").innerWidth ();

=> outerWidth ()
   $("#divUserInfo").outerWidth ();

=> fadeIn()
   $("#divUserInfo").fadeIn();

=> fadeOut()
   $("#divUserInfo").fadeOut ();

=> hide()
   $("#divUserInfo").hide();

=> show()
   $("#divUserInfo").show();

=> appendTo   
$("Hello").appendTo("#divUserInfo");

=> clone
$("#divUserInfo").clone().appendTo("#divUserInfo1");

=> not
$("#ddlProductList option").not("[value*='Computer']").clone().appendTo("#ddlFilterList");
-----------------------------------

Multiple Action in single line
-----------------------------------
$("#txtUserName").val("JSD24").css("color", "green").attr("IsSelected", "true")
-----------------------------------

Events
-----------------------------------
=> change()
   $("#txtUserName").change(function(){});
  
=> click()
   $("a").click(function(){});

=> dblclick()
   $("a").dblclick(function(){});

=> focus()
   $("#txtUserName").focus();

=> focusIn()
   $("#txtUserName").focusIn(function());

=> focusOut()
   $("#txtUserName").focusOut(function());

=> hover()
   $("#txtUserName").hover(function());

=> keydown()
   $("#txtUserName").keydown(function());

=> keyup()
   $("#txtUserName").keyup(function());

=> keypress ()
   $("#txtUserName").keypress(function());

=> mousedown()
   $("#txtUserName").mousedown(function());

=> mouseup()
   $("#txtUserName").mouseup(function());

=> mousemove()
   $("#txtUserName").mousemove(function());
-----------------------------------

AJAX / JSON
-----------------------------------
$.ajax({
        url : "test.html",
        type:"GET" ,         //Post
        data : { id : "2", pid : "1" },
        context: document.body,
        datatype : "html"        //JSON, XML
        success : handleResponse,
        error : handleError
});

Function handleResponse(data)
{
    alert(data);
}

Function handleError(msg)
{
    alert(msg);
}
-----------------------------------

XML Insert : Sql

DECLARE @XML AS XML = '<FileList>
       <FileInfo FileSrNo="0" FilePath="11" />
       <FileInfo FileSrNo="11" FilePath="1" />
       <FileInfo FileSrNo="2" FilePath="11" >
        <OtherInfo FileSrNo="222" FilePath="1122" >
         <FName>Ankit</FName>
         <LName>Somani</LName>
        </OtherInfo>
       </FileInfo>
      </FileList>'

SELECT FileInfo.value('@FileSrNo', 'INT') AS FileSrNo
 , FileInfo.value('@FilePath', 'VARCHAR(500)') AS FilePath
FROM @XML.nodes('/FileList/FileInfo')e(FileInfo)

SELECT FileInfo.value('@FileSrNo', 'INT') AS FileSrNo
 , FileInfo.value('@FilePath', 'VARCHAR(500)') AS FilePath
FROM @XML.nodes('/FileList/FileInfo/OtherInfo')e(FileInfo)

SELECT FileInfo.value('.', 'VARCHAR(25)') AS FName
FROM @XML.nodes('/FileList/FileInfo/OtherInfo/FName')e(FileInfo)

SELECT FileInfo.value('.', 'VARCHAR(25)') AS LName
FROM @XML.nodes('/FileList/FileInfo/OtherInfo/LName')e(FileInfo)

SELECT FileInfo.value('@FileSrNo', 'INT') AS FileSrNo
 , FileInfo.value('@FilePath', 'VARCHAR(500)') AS FilePath
 , FName.value('.', 'VARCHAR(25)') AS FName
 , LName.value('.', 'VARCHAR(25)') AS LName
FROM @XML.nodes('/FileList/FileInfo/OtherInfo')e(FileInfo)
 CROSS APPLY FileInfo.nodes('FName')ef(FName)
 CROSS APPLY FileInfo.nodes('LName')el(LName)



Out Put :

FileSrNo  FilePath
0             11
11           1
2             11
-----------------------------
FileSrNo   FilePath
222           1122
-----------------------------
FName
Ankit
-----------------------------
LName
Somani
-----------------------------
FileSrNo    FilePath    FName    LName
222            1122        Ankit       Somani


=========================================

SP:
==

ALTER PROCEDURE [dbo].[spInfoSave]
(
    @AID    VARCHAR(12),
    @XML    XML
)
AS
BEGIN
    SET NOCOUNT ON
   
    MERGE tblTEST
    USING
    (
        SELECT LinkInfo.value('@LinkSrNo', 'TINYINT') AS LinkSrNo
             , LinkInfo.value('@LinkPath', 'VARCHAR(500)') AS LinkPath
        FROM @XML.nodes('/LinkList/LinkInfo')e(LinkInfo)
    ) AS tblSrc
        ON tblSrc.LinkSrNo = tblTEST.LinkSrNo
            AND tblTEST.AID = @AID
    WHEN MATCHED THEN
        UPDATE
        SET  LinkPath = tblSrc.LinkPath
           
    WHEN NOT MATCHED THEN
        INSERT (
                      AID
                    , LinkSrNo
                    , LinkPath
                )
        VALUES (
                      @AID
                    , tblSrc.LinkSrNo
                    , tblSrc.LinkPath
                )
    WHEN NOT MATCHED BY SOURCE AND tblTEST.AID = @AID
        THEN DELETE;
END

XML Read 2

using System.Windows.Forms;
using System.Xml;
using System.Net;
using System.IO;


XmlDocument objXmlDocument = new XmlDocument();
                TextReader trs = new StreamReader(Application.StartupPath + "\\LastPostID.txt");

                string strLastInsertedId = trs.ReadLine();
                trs.Close();
                TextWriter tsw1 = new StreamWriter(Application.StartupPath + "\\Status.txt",true);
                tsw1.WriteLine(strLastInsertedId + " : " + DateTime.Now.ToString());
                tsw1.Close();

                label3.Text = strLastInsertedId;
                label3.Refresh();

                //clsSettings.GetSettingValue((int)clsCommon.Settings.LastPostId);

                string strXML = GetXML(strLastInsertedId);
                objXmlDocument.LoadXml(strXML);

                XmlNodeList objXmlNodeList = objXmlDocument.GetElementsByTagName("listing");

                if (objXmlNodeList != null)
                {
                    string strId = string.Empty;
                    string strTitle = string.Empty;
                    string strupdatedDate = string.Empty;
                    string strPrice = string.Empty;
                    string strPType = string.Empty;
                    string strURL = string.Empty;
                    string strCity = string.Empty;
                    string strState = string.Empty;

                    for (int i = 0; i < objXmlNodeList.Count; i++)
                    {
                        strId = string.Empty;
                        strTitle = string.Empty;
                        strupdatedDate = string.Empty;
                        strPrice = string.Empty;
                        strPType = string.Empty;
                        strURL = string.Empty;
                        strCity = string.Empty;
                        strState = string.Empty;

                        if (objXmlNodeList[i]["title"] != null)
                        {
                            strTitle = objXmlNodeList[i]["title"].InnerText.ToString();
                        }

           }

        }


 private string GetXML(string strStartFrom)
        {
            try
            {
                string strurl = "http://scrape100.iscrape.org/export/xml/?id=" + strStartFrom;
                HttpWebRequest objHttpWebRequest = (HttpWebRequest)WebRequest.Create(strurl);
                objHttpWebRequest.Method = "Get";
                objHttpWebRequest.ContentLength = 0;
                HttpWebResponse objHttpWebResponse = (HttpWebResponse)objHttpWebRequest.GetResponse();
                Stream objResponseStream = objHttpWebResponse.GetResponseStream();
                Encoding objEncoding = Encoding.GetEncoding("utf-8");
                StreamReader objStreamReader = new StreamReader(objResponseStream, objEncoding);
                string strHtmlOutput = objStreamReader.ReadToEnd();
                return strHtmlOutput;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

XML Read 1

using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Text.RegularExpressions;


string strFileName = "";
                strFileName = DateTime.Now.ToBinary().ToString() + "_" + System.IO.Path.GetFileName(fupXMLUpload.PostedFile.FileName);
                string SaveLocation = Server.MapPath("XMLFiles") + "\\" + strFileName;
                fupXMLUpload.PostedFile.SaveAs(SaveLocation);

                XmlTextReader reader = new XmlTextReader(SaveLocation);
                reader.WhitespaceHandling = WhitespaceHandling.None;
                XmlDocument xmlDoc = new XmlDocument();
                //Load the file into the XmlDocument
                xmlDoc.Load(reader);
                //Close off the connection to the file.
                reader.Close();
               

                string strXMLDoc = xmlDoc.InnerXml.ToString();
                XmlNode xnod = xmlDoc.DocumentElement;
                XmlNodeList objXmlNodeList = xmlDoc.GetElementsByTagName("VCHLEDNARREXPLOSION");

                Regex regDate = new Regex("<DSPVCHDATE>([^<]*)</DSPVCHDATE>");
                MatchCollection oMCDate = regDate.Matches(strXMLDoc);

                Regex regAmount = new Regex("<DSPVCHCRAMT>([^<]*)</DSPVCHCRAMT>");
                MatchCollection oMCAmount = regAmount.Matches(strXMLDoc);

                Regex regNameBatchInfo = new Regex("<VCHLEDNARREXPLOSION>([^,]*),\\s*[^,]*,\\s*[^;]*;([^\\s]*)\\s*[^<]*</VCHLEDNARREXPLOSION>");
                MatchCollection oMCNameBatchInfo = regNameBatchInfo.Matches(strXMLDoc);

                string strDate = string.Empty;
                int intDateIndex = 0;

                string strAmount = string.Empty;
                int intAmountIndex = 0;

                string strName = string.Empty;
                string strBatchNo = string.Empty;
                int intNameBatchIndex = 0;

                string[] strArrDate;

                //for (int j = 0; j < objXmlNodeList.Count; j++)
                for (int j = 0; j < oMCNameBatchInfo.Count; j++)
                {
                    strDate = oMCDate[intDateIndex].Groups[1].Value;
                    strArrDate = strDate.Split('-');
                    oCATDDR.CatDtl_DateOfJoining = Convert.ToDateTime(strArrDate[1] + "-" + strArrDate[0] + "-" + strArrDate[2]);
                    intDateIndex = intDateIndex + 2;

                    strAmount = oMCAmount[intAmountIndex].Groups[1].Value;
                    oCATDDR.CatDtl_Fees = Convert.ToDecimal(strAmount);
                    //intAmountIndex = intAmountIndex + 2;
                    intAmountIndex = intAmountIndex + 1;

                    strName = oMCNameBatchInfo[intNameBatchIndex].Groups[1].Value;

                    //if ("RAVI BHADRESA" == strName)
                    //{
                    //    string strHello = "";
                    //}

                    strBatchNo = oMCNameBatchInfo[intNameBatchIndex].Groups[2].Value;

                    oCATDDR.CatDtl_StudentName = strName;
                    oCATDDR.CatDtl_BatchNo = strBatchNo;
                    intNameBatchIndex = intNameBatchIndex + 1;

                    if (oCATDetail_CDO.CATDtl_Insert(oCATDDR))
                    {
                        fnMessage(true, "Record Inserted Successfully.");
                    }
                    else
                    {
                        fnMessage(true, "Record Record already Exist.");
                    }

                }

Thursday, October 21, 2010

Sql - Xml Ex

DECLARE @XML AS XML = '<FileList>
       <FileInfo FileSrNo="0" FilePath="11" />
       <FileInfo FileSrNo="11" FilePath="1" />
       <FileInfo FileSrNo="2" FilePath="11" >
        <OtherInfo FileSrNo="222" FilePath="1122" >
         <FName>Ankit</FName>
         <LName>Somani</LName>
        </OtherInfo>
       </FileInfo>
      </FileList>'

SELECT  FileInfo.value('@FileSrNo', 'INT') AS FileSrNo
 , FileInfo.value('@FilePath', 'VARCHAR(500)') AS FilePath
FROM @XML.nodes('/FileList/FileInfo')e(FileInfo)

SELECT FileInfo.value('@FileSrNo', 'INT') AS FileSrNo
 , FileInfo.value('@FilePath', 'VARCHAR(500)') AS FilePath
FROM @XML.nodes('/FileList/FileInfo/OtherInfo')e(FileInfo)
SELECT FileInfo.value('.', 'VARCHAR(25)') AS FName
FROM @XML.nodes('/FileList/FileInfo/OtherInfo/FName')e(FileInfo)
SELECT FileInfo.value('.', 'VARCHAR(25)') AS LName
FROM @XML.nodes('/FileList/FileInfo/OtherInfo/LName')e(FileInfo)
SELECT FileInfo.value('@FileSrNo', 'INT') AS FileSrNo
 , FileInfo.value('@FilePath', 'VARCHAR(500)') AS FilePath
 , FName.value('.', 'VARCHAR(25)') AS FName
 , LName.value('.', 'VARCHAR(25)') AS LName
FROM @XML.nodes('/FileList/FileInfo/OtherInfo')e(FileInfo)
 CROSS APPLY FileInfo.nodes('FName')ef(FName)
 CROSS APPLY FileInfo.nodes('LName')el(LName)

-------------------------------
Out Put
-------------------------------
FileSrNo   FilePath
0               11
11             1
2               11
-------------------------------
FileSrNo  FilePath
222          1122
-------------------------------
FName
Ankit
-------------------------------
LName
Somani
-------------------------------
FileSrNo  FilePath  FName  LName
222          1122      Ankit      Somani