Tuesday, May 24, 2011

Check If A String Value Is Numeric or Not

Following is the example for testing string value as number or not
            string str123 = "1245"
               Double res = 0;
            bool b12=Double.TryParse(str123, out res);
this will return true. for the above example. If however, str123="123ab" then the above code will return false.

             

Friday, May 20, 2011

How to merge two diffrent Hashtable in asp.net

//Method return an XML
  public Hashtable GetSimpleCollection()
    {
        Hashtable XMLmappingHash = new Hashtable();
        ////Test XML parser....
        XmlTextReader testXMlReader = XMLparse();
        //Load the Loop
        while (!testXMlReader.EOF)
        {
            //Go to the name tag
            testXMlReader.Read();
            //if not start element exit while loop
            //if (!testXMlReader.IsStartElement())
            //{
            //    break; // TODO: might not be correct. Was : Exit While
            //}
            string nodetype = testXMlReader.Name;
            string attributeValue = string.Empty;
            if (nodetype == "excelcol")
            {
               
                while (testXMlReader.MoveToNextAttribute())
                {
                    attributeValue = testXMlReader.Value;
                }
                XMLmappingHash.Add(testXMlReader.ReadElementString("excelcol"), attributeValue);
            }
          
        }
       
        return XMLmappingHash;
    }

// Another Mehtod return hashtable
 public Hashtable GetCompositeHashtable()
    {
        string val =string.Empty;
        StringBuilder sb;
        Hashtable CompHashtable=new Hashtable();
        XmlDocument XMLRead = new XmlDocument(); // Create instance of XmlDocument class    
        //XMLRead.Load(Server.MapPath("Page1.xml")); // Load Xml file
        XMLRead.Load("D:\\Work\\GetExcelSheetNames\\XMLFile.xml");
        XmlNodeList nodes = XMLRead.SelectNodes(@"excelMapping/tableName");
        foreach (XmlNode node in nodes)
        {
            XmlNodeList nodes2list = node.ChildNodes;
            for (int i = 0; i < nodes2list.Count; i++)
            {
              
                string key = "comp1" + i;
                string Nodetype = nodes2list[i].Name;
                if (Nodetype == "excelsComposite")
                {
                    XmlNode CompositeNode = nodes2list.Item(i);
                    XmlNodeList CompNodeChild = CompositeNode.ChildNodes;
                    sb = new StringBuilder();
                    foreach (XmlNode CompChild in CompNodeChild)
                    {
                        if (CompChild.Attributes["operation"].Value == "Add")
                        {
                        
                            foreach (XmlNode CompChildNodeValue in CompChild)
                            {
                                //sb = sb.Append("SUM");
                                sb = sb.Append(CompChildNodeValue.InnerText);
                               sb= sb.Append(",");
                              
                            }
                            if (sb.Length!=0)
                            {
                                sb.Remove(sb.Length - 1, 1);
                               
                            }
                         
                        }
                        if (CompChild.Attributes["operation"].Value == "Divide")
                        {
                            sb = sb.Append(CompChild.InnerText);
                            //val = "(x1+x2)/x3";
                        }
                      
                        //string ControlID = n2a.InnerText.Trim();
                        // string ControlType = n2a.Attributes["ControlType"].Value;
                        // string AccessMode = n2a.Attributes["AccessType"].Value;
                        // AddControl(ControlType, ControlID, AccessMode);
                    }
                    CompHashtable.Add(key, sb);
                
                }
            }
        }
        return CompHashtable;
               
    }

////Method that merge two diffrent Hashtables

 public Hashtable GetCompleteCollection()
    {
        string HashKey = string.Empty;
        string HashValue = string.Empty;
        Hashtable DatafieldHashmap = new Hashtable();
        Hashtable CompHashMap = new Hashtable();
        DatafieldHashmap = GetSimpleCollection();
        CompHashMap = GetCompositeHashtable();
        IDictionaryEnumerator Hashmap = CompHashMap.GetEnumerator();
        while (Hashmap.MoveNext())
        {
            HashKey = Hashmap.Key.ToString();
            HashValue = Hashmap.Value.ToString();
            DatafieldHashmap.Add(HashKey,HashValue);
        }
        return DatafieldHashmap;
    }

//// Call this on page load like this

 Hashtable XMLCollectionreturn = new Hashtable();
     
   XMLCollectionreturn = GetCompleteCollection();

How to read and return an XML in asp.net

public XmlTextReader XMLparse()
    {
        XmlTextReader m_xmlr = null;
        //Create the XML Reader
        m_xmlr = new XmlTextReader("D:\\Work\\GetExcelSheetNames\\XMLFile.xml");
        //Disable whitespace so that you don't have to read over whitespaces
        m_xmlr.WhitespaceHandling = WhitespaceHandling.None;
        //read the xml declaration and advance to family tag
        m_xmlr.Read();
        //read the family tag
        m_xmlr.Read();
        //Load the Loop
        while (!m_xmlr.EOF)
        {
            //Go to the name tag
            m_xmlr.Read();
            //if not start element exit while loop
            if (!m_xmlr.IsStartElement())
            {
                break; // TODO: might not be correct. Was : Exit While
            }
            //Get the Gender Attribute Value
            string genderAttribute = m_xmlr.GetAttribute("gender");
            //Read elements firstname and lastname
            m_xmlr.Read();
            //Get the firstName Element Value
            string firstNameValue = m_xmlr.ReadElementString("firstname");
            //Get the lastName Element Value
            string lastNameValue = m_xmlr.ReadElementString("lastname");
            //Write Result to the Console
            Response.Write("Gender: " + genderAttribute + " FirstName: " + firstNameValue + " LastName: " + lastNameValue);
            // Console.Write(Constants.vbCrLf);
        }
        //close the reader
        m_xmlr.Close();
        return m_xmlr;
    }

Thursday, April 21, 2011

How to make and use Split function in sql Server

1. Create a Function in SQL as follows:

Create FUNCTION dbo.StringSplit
(
@SplitStr nvarchar(2000),
@SplitChar nvarchar(20)
)
RETURNS @RtnValue table
(
Data nvarchar(2000)
)
AS
BEGIN
Declare @Count int
Set @Count = 1
While (Charindex(@SplitChar,@SplitStr)>0)
Begin
Insert Into @RtnValue (Data)
Select
Data = ltrim(rtrim(Substring(@SplitStr,1,Charindex(@SplitChar,@SplitStr)-1)))
Set @SplitStr = Substring(@SplitStr,Charindex(@SplitChar,@SplitStr)+1,len(@SplitStr))
Set @Count = @Count + 1
End
Insert Into @RtnValue (Data)
Select Data = ltrim(rtrim(@SplitStr))
Return
END

2. you need to pass two parameter one is string and otherone is spliting character
here is example

select * from SplitString('Contact-No-Deal\Email\08-30-2010\SP10000175-08-30-2010-16-56-28-5322-BalanceRequest.doc', '\')

output will be like this:

Contact-No-Deal
Email
08-30-2010
SP10000175-08-30-2010-16-56-28-5322-BalanceRequest.doc

Tuesday, March 8, 2011

Dynamically passing dates between clause

Create PROCEDURE dbo.test
(
@Table nvarchar(50),
@Field nvarchar(50),
@BeginDate DateTime,
@EndDate DateTime
)
AS
DECLARE @Sql nvarchar(1000)
SET @Sql = 'SELECT ' + @Table + '.* FROM ' + @Table + ' WHERE ' + @Field + ' BETWEEN ''' + convert(nvarchar(20), @BeginDate) + ''' AND ''' + convert(nvarchar(20), @EndDate) + ''''
EXEC sp_executesql @Sql

Wednesday, March 2, 2011

function which will return st, th, nd and rd with date in SQL SERVER

1.create a function as below
create function [dbo].[get_tidy_date]
(
    @date datetime = null
)
returns nvarchar(50)
as begin
     
    declare @d int,
    @m nvarchar(15),
    @y nvarchar(4),
    @end nvarchar(1),
    @return nvarchar(50)
 
    if @date is null
        set @date=getdate()
    select @d=datepart(d, @date), @m=datename(m, @date), @Y=
datename(yyyy,@date), @end=right(convert(nvarchar(2), @d),1)
    set @return=
        convert(nvarchar(2), @d)
        +case
            when @d in(11, 12, 13) then 'th'
            when @end='1' then 'st'
            when @end='2' then 'nd'
            when @end='3' then 'rd'
            else 'th'  
        end
        +' '+@m+' '+@y
    return @return
 
end


2.Call this function as follows:

SELECT dbo.get_tidy_date(GETDATE())

Output is like this
2nd March 2011

Gridview Sorting with up and down arrow + paging

1. Add Gridview and enable sorting and write sortexpression field

      <asp:GridView ID="grdCompany" runat="server" AutoGenerateColumns ="False"
        DataKeyNames="ID,TraceStatus,CaseRefNo" Width="100%"
        onrowdatabound="grdCompany_RowDataBound" AllowPaging="True" AllowSorting="True"
              onrowcreated="grdCompany_RowCreated" onsorting="grdCompany_Sorting"
              onpageindexchanging="grdCompany_PageIndexChanging">
        <Columns>
        <asp:hyperlinkfield headertext="Reference No." datatextfield="CaseRefNo"  SortExpression="CaseRefNo"
                ItemStyle-Width="80px"
                datanavigateurlformatstring="viewcase.aspx?refid={0}&TraceType=C"
                datanavigateurlfields="CaseRefNo" >
            <HeaderStyle ForeColor="White" />
            <ItemStyle Width="80px" />
            </asp:hyperlinkfield>
        <%--<asp:BoundField DataField="CompanyName1" HeaderText="Company Name" ItemStyle-Width ="100px" /> 
        <asp:BoundField DataField="PropertyName1" HeaderText="Property Name" ItemStyle-Width ="100px" />  --%>
        <asp:TemplateField HeaderText="Company Name/ <br/>Property Name" SortExpression="CompanyName1">
        <ItemTemplate>
          <%#Eval("CompanyName1")%>
          <br />
          <%#Eval("PropertyName1") %>
        </ItemTemplate>
            <HeaderStyle ForeColor="White" />
        </asp:TemplateField> <asp:TemplateField HeaderText="Trace Level<br/>Date of Submission" SortExpression="Tracelevel">
        <ItemTemplate>
          <%#Eval("Tracelevel")%>
          <br />
          <%#Eval("DOS")%>
        </ItemTemplate>
                <HeaderStyle ForeColor="White" />
        </asp:TemplateField>
        <%--<asp:BoundField DataField="Tracelevel" HeaderText="Trace Level" ItemStyle-Width ="100px" /> 
        <asp:BoundField DataField="DOS" HeaderText="Date of Submission" ItemStyle-Width ="100px" /> 
        <asp:BoundField DataField="TraceStatus" HeaderText="Status" ItemStyle-Width ="100px" />  --%>
        <asp:TemplateField HeaderText="Status" SortExpression="TraceStatus">
        <ItemTemplate>
          <asp:Label ID="lblStatus" runat="server" Text='<% #Eval("TraceStatus") %>' ></asp:Label>
          <asp:HyperLink ID="vwReport" runat="server" Text="View Report"></asp:HyperLink>
        </ItemTemplate>
            <HeaderStyle ForeColor="White" />
        </asp:TemplateField>
        </Columns>
        <HeaderStyle CssClass ="t-heading"   height="35px" /> <RowStyle CssClass ="b-table-text-inside3" height="30px" />
        </asp:GridView>



2. write following code in code behind page.

DataView dv = new DataView();
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";


//Write a method which return view
  private DataView bindgridSort()
    {
        clsCase objCase = new clsCase();
        objCase.pClientId = clsSessions.sesUserID;
        objCase.pTraceType = "C";

        DataSet dsCase = new DataSet();
        dsCase = objCase.GetAllCases();


        if (dsCase.Tables[0].Rows.Count > 0)
        {
            if (ViewState["sortExpr"] != null)
            {
                dv = new DataView(dsCase.Tables[0]);
                dv.Sort = (string)ViewState["sortExpr"];
            }
            else
                dv = dsCase.Tables[0].DefaultView;
        }
        else
        {
            lblMsg.Text = "No Details Found.";
        }

        return dv;

// Add row_created events

protected void grdCompany_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            int sortColumnIndex = GetSortColumnIndex();
            if (sortColumnIndex != -1)
            {
                AddSortImage(sortColumnIndex, e.Row);
            }
        }
    }

// Add sorting event
 protected void grdCompany_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortExpression = e.SortExpression;
        ViewState["SortExpression"] = sortExpression;

        if (GridViewSortDirection == SortDirection.Ascending)
        {
            GridViewSortDirection = SortDirection.Descending;
            SortGridView(sortExpression, DESCENDING);
        }
        else
        {
            GridViewSortDirection = SortDirection.Ascending;
            SortGridView(sortExpression, ASCENDING);
        }
    }



 private int GetSortColumnIndex()
    {
        // Iterate through the Columns collection to determine the index
        // of the column being sorted.
        foreach (DataControlField field in grdCompany.Columns)
        {
            if (field.SortExpression == (string)ViewState["SortExpression"])
            {
                return grdCompany.Columns.IndexOf(field);
            }
        }
        return -1;
    }
    private void AddSortImage(int columnIndex, GridViewRow headerRow)
    {
        // Create the sorting image based on the sort direction.
        Image sortImage = new Image();

        if (GridViewSortDirection == SortDirection.Ascending)
        {
            sortImage.ImageUrl = "Images/uparrow.gif";
            sortImage.AlternateText = "Ascending Order";
            sortImage.ImageAlign = ImageAlign.Top;
            sortImage.ImageAlign = ImageAlign.Middle;

        }
        else
        {
            sortImage.ImageUrl = "Images/downarrow.gif";
            sortImage.ImageAlign = ImageAlign.AbsBottom;
            sortImage.ImageAlign = ImageAlign.Middle;
            sortImage.AlternateText = "Descending Order";
        }
        // Add the image to the appropriate header cell.

        // headerRow.Cells[columnIndex].Controls.Add(space);
        headerRow.Cells[columnIndex].Controls.Add(sortImage);

    }
    private SortDirection GridViewSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;
            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value; }
    }
    private void SortGridView(string sortExpression, string direction)
    {
        DataView dv = bindgridSort();
        dv.Sort = sortExpression + direction;
        grdCompany.DataSource = dv;
        grdCompany.DataBind();
    }

    protected void grdCompany_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdCompany.PageIndex = e.NewPageIndex;
        BindCaseDetails("C");
    }