Thursday, February 9, 2012

XML Value generation and convertions


  private int GetAvailableBids(string referralScheme, decimal moneyLevel)
    {
        int freeBids=0;
        DataSet dsScheme = new DataSet();
        XmlDocument XmlDocumentObject = new XmlDocument();
        string MembershipFile = string.Empty;
        //SubscriptionFileName = Server.MapPath(ConfigurationManager.AppSettings["ImageFolder"].ToString()) + "Subscription.xml";
        MembershipFile = HttpContext.Current.Server.MapPath("~\\App_Data\\Files\\MembershipSheme.xml");
        XmlDocumentObject.Load(MembershipFile);

        XmlNodeList Nodelist = XmlDocumentObject.SelectNodes("/Membership/SignupBids/" + referralScheme);
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

        string strXML = "<MembershipSheme>";
        strXML = strXML + Nodelist.Item(0).InnerXml;
        strXML = strXML + "</MembershipSheme>";
        doc.LoadXml(strXML);
        dsScheme.ReadXml(new System.IO.StringReader(doc.OuterXml));

        if (dsScheme != null)
        {
            if (dsScheme.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in dsScheme.Tables[0].Rows)
                {
                   decimal moneyLevelxml = Convert.ToDecimal(dr["price"]);
                   if (moneyLevel == moneyLevelxml)
                   {
                       freeBids = Convert.ToInt32(dr["value"]);
                   }

                }
            }
        }

        if (referralScheme.ToUpper() == "RESIDUAL")
        {
            freeBids = freeBids / 12;
        }
        return (freeBids);
    }

Core Ajax Code To Get Value From Other Page Load Event



<script type = "text/javascript" language="javascript">
var RedirectPath = '<%= "http://" + Request.ServerVariables["HTTP_HOST"].ToString() + Request.ApplicationPath+"/Ajax/checkuser.aspx" %>';
        function GetName(source, args) {
     
        var current_path = window.location;
        if(current_path.toString().substr(0,5) == "https")
        {
           RedirectPath = '<%= "https://" + Request.ServerVariables["HTTP_HOST"].ToString() + Request.ApplicationPath+"/Ajax/checkuser.aspx" %>';      
        }

          hdnrefuserexit =  document.getElementById("<%=hdnrefuserexit.ClientID %>");
          txtReferredBy = document.getElementById("<%=txtReferralID.ClientID %>");
          lableMessage = document.getElementById("<%=lblError1.ClientID %>");
           referralID = txtReferredBy.value;
         
            if(referralID!="")
            {
           
                $.ajax({
                    type: "POST",
                    url: RedirectPath,
                    data: "q=" + referralID+"&t=referral" ,
                    success: function(response) {
                               
                        if(response !="failed")
                        {
                          if(response=="false")
                          {
                           
                             lableMessage.innerHTML  = "Referral User does not exist";
                             lableMessage.style.color = "Red";
                             hdnrefuserexit.value = "false";
                             txtReferredBy.focus();
                             args.IsValid = false;
                          }
                          else
                          {
                             lableMessage.innerHTML  = response.toString();
                             lableMessage.style.color = "Green";      
                             hdnrefuserexit.value = "true";                
                             args.IsValid = true;
                          }
                        }
                        else if(response =="failed")
                        {          
                       
                          lableMessage.innerHTML  = "Referral User does not exist";
                          lableMessage.style.color = "Red";
                          txtReferredBy.focus();
                          hdnrefuserexit.value = "false";
                          args.IsValid= false;
                        }
                        else
                        {                        
                          lableMessage.innerHTML  = "Referral User does not exist";
                          lableMessage.style.color = "Red";
                          txtReferredBy.focus();
                          hdnrefuserexit.value = "false";
                          args.IsValid = false;
                        }                
                    }
                });
              }
              else
              {
                hdnrefuserexit.value="true;"
                lableMessage.innerHTML  = "";
                args.IsValid = true;
              }
         
        }

<script type/>




<table>

<tr id="trReferral" runat="server" style="visibility: hidden;">
                                                                                <td align="right" valign="top" class="input_label_right">
                                                                                    Referee UserID
                                                                                </td>
                                                                                <td align="left" valign="top">
                                                                                    <asp:TextBox ID="txtReferralID" CssClass="input_value" ValidationGroup="step1" runat="server" />
                                                                                    &nbsp;
                                                                                    <asp:CustomValidator ID="CustomValidator2" ValidationGroup="step1" ControlToValidate="txtReferralID"
                                                                                        SetFocusOnError="true" ClientValidationFunction="GetName" runat="server" Display="Dynamic"
                                                                                        Visible="true" ErrorMessage="Referral User does not exist" />
                                                                                    <asp:Label ID="lblError1" runat="server" Text="" ForeColor="Green" Visible="true"></asp:Label>
                                                                                </td>
                                                                            </tr>
</table>




Anoth Page  checkuser.aspx in Ajax folder 
code in this file below.



using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
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 DataObjects.General;

public partial class Ajax_checkuser : System.Web.UI.Page
{

    #region Page Members
    string SearchUserName = string.Empty;
    #endregion

    #region  Events

    /// <summary>
    /// Page Load Event
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        string SearchKey = Convert.ToString(Request.Form["q"]);
        if (!string.IsNullOrEmpty(SearchKey))
        {

            string searchType = Convert.ToString(Request.Form["t"]);
            if (!string.IsNullOrEmpty(searchType))
            {
                if (searchType == "referral")
                {
                  GetUserName(SearchKey);
                }
                else if (searchType == "registration")
                {
                    CheckUsersExists(SearchKey);
                }    
            }
        }
    }



    #endregion

    #region Methods


    /// <summary>
    /// Get Provider Name by Referral ID Asyncronusly
    /// </summary>
    private void GetUserName(string SearchKey)
    {
        try
        {
            DataTable dt = PaperTab.BusinessObjects.User.UsersBo.GetUserByUserName(SearchKey);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    string firstName = Convert.ToString(dt.Rows[0]["FirstName"]);
                    string lastName = Convert.ToString(dt.Rows[0]["LastName"]);
                    SearchUserName = firstName + " " + lastName;

                    Response.Write(SearchUserName);
                }
                else
                {
                    Response.Write("false");
                }
            }
            else
            {
                Response.Write("failed");
            }
        }
        catch (Exception ex)
        {
            SearchUserName = string.Empty;
            Response.Write("failed");
        }
        finally
        {
         
        }

    }


    /// <summary>
    ///
    /// </summary>
    /// <param name="SearchKey"></param>
    private void CheckUsersExists(string SearchKey)
    {
        try
        {
            DataTable dt = PaperTab.BusinessObjects.User.UsersBo.GetUserByUserName(SearchKey);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    Response.Write("true");
                }
                else
                {
                    Response.Write("false");
                }
            }
            else
            {
                Response.Write("failed");
            }
        }
        catch (Exception ex)
        {
            SearchUserName = string.Empty;
            Response.Write("failed");
        }
        finally
        {
         
        }
    }
    #endregion


}



Tuesday, January 10, 2012

Bind GridView with XML data


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
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.Xml.XPath;
using System.Xml;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("XMLFile.xml"));
        DataTable dt=ds.Tables[0];
        GridView1.DataSource = ds;
        GridView1.DataBind();
     }

}

Monday, January 9, 2012

How To Bind Gridview with SQL Server data


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Management;
using System.Web.Configuration; // this namespace is use to access web.config file. 
using System.Data.SqlClient;  
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connectionstring = Convert.ToString(WebConfigurationManager.AppSettings["Connection"]);
      //we access the connection string from web.config's app sating  tag 
        SqlConnection con = new SqlConnection(connectionstring);
        con.Open();
        SqlCommand com = new SqlCommand("select * from a", con);
        SqlDataAdapter da = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();

    }
}

web.config file  as 


<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
<appSettings>
<add key="Connection" value="server=MUKHERJE-52893C;Initial Catalog=Data; Integrated Security=true"/>
</appSettings>
</configuration>



Tuesday, November 29, 2011

Get Data From Store procedure parameter one by one by Come saparation

ALTER PROCEDURE [dbo].[SP_ORDER_INSERT] 
(
    @COMPANYID   INT,
 @CUSTOMERID   VARCHAR(50),
    @PRODUCTID   VARCHAR(100),
 @QUANTITY   INT,
 @PRICE    VARCHAR(200),
    @PRODUCTPRICE       VARCHAR(200),
-- @TOTALPRICE   DECIMAL(18,2),
 @TAX    DECIMAL(18,2),
 @SHIPPING   DECIMAL(18,2),
 @GRANDTOTAL   DECIMAL(18,2),
 @NOTES    NTEXT,
 @STATUS    VARCHAR(10),
 @ERRORMESSAGE       VARCHAR(MAX),
 @CREATEDBY   VARCHAR(50),
    @SHIPPINGCARRIER    VARCHAR(50),
 @TRACKINGNUMBER     VARCHAR(50),
 @PRODUCTCOLOR       VARCHAR(MAX),
 @PRODUCTSIZE        VARCHAR(MAX),
 @ORDERQTY           VARCHAR(MAX)
)
AS
BEGIN
 DECLARE @COUNTER AS INT
 DECLARE @PID  AS INT
 DECLARE @PRC  AS DECIMAL(18,2)
 DECLARE @PCOLOR     AS  VARCHAR(50)
 DECLARE @PSIZE      AS  VARCHAR(50)
 DECLARE @Pqty      AS   VARCHAR(20)
BEGIN TRY
 INSERT INTO [DBO].[ORDER]
           ( [COMPANYID],
    [CUSTOMERID],
    [QUANTITY],
    [PRICE],
    [TAX],
    [SHIPPING],
    [GRANDTOTAL],
    [NOTES],
    [CREATEDAT],
    [UPDATEDAT],
    [ErrorMessage],
    [STATUS],
    [SHIPPINGCARRIER],
    [TRACKINGNUMBER]
 
   )
    VALUES
           ( @COMPANYID,
    @CUSTOMERID,
    @QUANTITY,
    @PRICE,
    @TAX,
    @SHIPPING,
    @GRANDTOTAL,
    @NOTES,
       GETDATE(),
                '',  
    @ERRORMESSAGE,
    @STATUS,
    @SHIPPINGCARRIER,
                @TRACKINGNUMBER
           )
         
         
SELECT @COUNTER = [dbo].[FN_SPLIT_STRING](@PRODUCTID,',',0)------ this "FN_SPLIT_STRING" Function used      --------------------------------------------------------------------------------to count the number data separated by comma
 WHILE ( @COUNTER > 1) ---------------------------- While Loop Start
 BEGIN
  SET @COUNTER = @COUNTER - 1
  SELECT @PID = [dbo].[FN_SPLIT_STRING](@PRODUCTID,',',@COUNTER)--- Fetch --------------------------The  Data in @COUNTER Position in @PRODUCTID parameter
--  SELECT @PRC = [dbo].[FN_SPLIT_STRING](@PRICE,',',@COUNTER)
  SELECT @PRC = [dbo].[FN_SPLIT_STRING](@PRODUCTPRICE,',',@COUNTER)
  SELECT @PCOLOR = [dbo].[FN_SPLIT_STRING](@PRODUCTCOLOR,',',@COUNTER)
  SELECT @PSIZE = [dbo].[FN_SPLIT_STRING](@PRODUCTSIZE,',',@COUNTER)
        SELECT @Pqty    =   [dbo].[FN_SPLIT_STRING](@ORDERQTY,',',@COUNTER)
      
  INSERT INTO [DBO].[PRODUCTORDER]
      ( [ORDERID],
     [COMPANYID],
     [PRODUCTID],
     [QUANTITY],
     [PRODUCTPRICE],
     [ProductSize],
     [ProductColor],
     [CREATEDBY],
     [CREATEDAT],
     [UPDATEDBY],
     [UPDATEDAT]
    )
  VALUES
      ( IDENT_CURRENT('ORDER'),
     1,
     @PID,
     @Pqty,
     @PRC,
     @PSIZE,
     @PCOLOR,
     @CUSTOMERID,
     GETDATE(),
     '',
     ''
    )
 END

END TRY
BEGIN CATCH
END CATCH
BEGIN TRAN
 IF XACT_STATE() =0
 BEGIN
  COMMIT TRAN
 END
 ELSE
 BEGIN
 ROLLBACK TRAN
 END
END

Stored Procedure With While Loop

ALTER PROCEDURE [dbo].[sp_ORDER_INSERT]  
(
    @COMPANYID   INT,
 @CUSTOMERID   VARCHAR(50),
    @PRODUCTID   VARCHAR(100),
 @QUANTITY   INT,
 @PRICE    VARCHAR(200),
    @PRODUCTPRICE       VARCHAR(200),
-- @TOTALPRICE   DECIMAL(18,2),
 @TAX    DECIMAL(18,2),
 @SHIPPING   DECIMAL(18,2),
 @GRANDTOTAL   DECIMAL(18,2),
 @NOTES    NTEXT,
 @STATUS    VARCHAR(10),
 @ERRORMESSAGE       VARCHAR(MAX),
 @CREATEDBY   VARCHAR(50),
    @SHIPPINGCARRIER    VARCHAR(50),
 @TRACKINGNUMBER     VARCHAR(50),
 @PRODUCTCOLOR       VARCHAR(MAX),
 @PRODUCTSIZE        VARCHAR(MAX),
 @ORDERQTY           VARCHAR(MAX)
)
AS
BEGIN
 DECLARE @COUNTER AS INT
 DECLARE @PID  AS INT
 DECLARE @PRC  AS DECIMAL(18,2)
 DECLARE @PCOLOR     AS  VARCHAR(50)
 DECLARE @PSIZE      AS  VARCHAR(50)
 DECLARE @Pqty      AS   VARCHAR(20)
BEGIN TRY
 INSERT INTO [DBO].[ORDER]
           ( [COMPANYID],
    [CUSTOMERID],
    [QUANTITY],
    [PRICE],
    [TAX],
    [SHIPPING],
    [GRANDTOTAL],
    [NOTES],
    [CREATEDAT],
    [UPDATEDAT],
    [ErrorMessage],
    [STATUS],
    [SHIPPINGCARRIER],
    [TRACKINGNUMBER]
  
   )
    VALUES
           ( @COMPANYID,
    @CUSTOMERID,
    @QUANTITY,
    @PRICE,
    @TAX,
    @SHIPPING,
    @GRANDTOTAL,
    @NOTES,
       GETDATE(),
                '',   
    @ERRORMESSAGE,
    @STATUS,
    @SHIPPINGCARRIER,
                @TRACKINGNUMBER
           )
          
          
SELECT @COUNTER = [dbo].[FN_SPLIT_STRING](@PRODUCTID,',',0)------ this "FN_SPLIT_STRING" Function used      --------------------------------------------------------------------------------to count the number data separated by comma
 WHILE ( @COUNTER &gt; 1) ---------------------------- While Loop Start
 BEGIN
  SET @COUNTER = @COUNTER - 1
  SELECT @PID = [dbo].[FN_SPLIT_STRING](@PRODUCTID,',',@COUNTER)--- Fetch --------------------------The  Data in @COUNTER Position in @PRODUCTID parameter
--  SELECT @PRC = [dbo].[FN_SPLIT_STRING](@PRICE,',',@COUNTER)
  SELECT @PRC = [dbo].[FN_SPLIT_STRING](@PRODUCTPRICE,',',@COUNTER)
  SELECT @PCOLOR = [dbo].[FN_SPLIT_STRING](@PRODUCTCOLOR,',',@COUNTER)
  SELECT @PSIZE = [dbo].[FN_SPLIT_STRING](@PRODUCTSIZE,',',@COUNTER)
        SELECT @Pqty    =   [dbo].[FN_SPLIT_STRING](@ORDERQTY,',',@COUNTER)
       
  INSERT INTO [DBO].[PRODUCTORDER]
      ( [ORDERID],
     [COMPANYID],
     [PRODUCTID],
     [QUANTITY],
     [PRODUCTPRICE],
     [ProductSize],
     [ProductColor],
     [CREATEDBY],
     [CREATEDAT],
     [UPDATEDBY],
     [UPDATEDAT]
    )
  VALUES
      ( IDENT_CURRENT('ORDER'),
     1,
     @PID,
     @Pqty,
     @PRC,
     @PSIZE,
     @PCOLOR,
     @CUSTOMERID,
     GETDATE(),
     '',
     ''
    )
 END

END TRY
BEGIN CATCH
END CATCH
BEGIN TRAN
 IF XACT_STATE() =0
 BEGIN
  COMMIT TRAN
 END
 ELSE
 BEGIN
 ROLLBACK TRAN
 END
END

SQL Optimization

  SQL Optimization  1. Add where on your query  2. If you remove some data after the data return then remove the remove condition in the sel...