Thursday, 29 September 2011

Split a string in array by a string delimiter in C#


private static string[] SplitString(string valueString, string delimiter)
{
        string[] RetVal;
        int Index = 0;
        string Value;
        List<string> SplittedList = new List<string>();

        while (true)
        {
            Index = valueString.IndexOf(delimiter);
            if (Index == -1)
            {
                if (!string.IsNullOrEmpty(valueString))
                {
                    SplittedList.Add(valueString);
                }
                break;
            }
            else
            {
                Value = valueString.Substring(0, Index);
                valueString = valueString.Substring(Index + delimiter.Length);
                SplittedList.Add(Value);
               
            }

        }

        RetVal = SplittedList.ToArray();

        return RetVal;
}

Parse an XML string/file for a single node in C#


string myXMl = "<Employees>" +
                 "<Employee ID='1' Name='Ravi'" +
                      "Address='Pandav Nagar'" +
                      "City='New Delhi' Zip='110092'>" +
                 "</Employee>" +
               "</Employees>";

XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(myXMl);

XmlNode xmlNode = xDoc.SelectSingleNode("/Employees/Employee[@ID='1']");

string Name =
xmlNode.Attributes["Name"].Value;//Outputs: Ravi
string Address =
xmlNode.Attributes["Address"].Value;//Outputs: Pandav Nagar
string City =
xmlNode.Attributes["City"].Value;//Outputs: New Delhi
string Zip =
xmlNode.Attributes["Zip"].Value; //Outputs: 110092

Parse an XML string/file in C#


The following code shows a simple method of parsing through an XML string/file. We can get the parent name, child name, attributes etc. from the XML. The namespace System.Xml would be the only additional namespace that we would be using.
string myXMl = "<Employees>" +
                 "<Employee ID='1' Name='Ravi'" +
                      "Address='Pandav Nagar'" +
                      "City='New Delhi' Zip='110092'>" +
                 "</Employee>" +
               "</Employees>";

XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(myXMl);

XmlNodeList xNodeList = xDoc.SelectNodes("Employees/child::node()");
foreach (XmlNode xNode in xNodeList)
{
  if (xNode.Name == "Employee")
  {
    string ID = xNode.Attributes["ID"].Value; //Outputs: 1
   
string Name = xNode.Attributes["Name"].Value; //Outputs: Ravi
   
string Address = xNode.Attributes["Address"].Value; //Outputs: Pandav Nagar
   
string City = xNode.Attributes["City"].Value; //Outputs: New Delhi
   
string Zip = xNode.Attributes["Zip"].Value; //Outputs: 110092
 
}
}




Lets look at another XML:
string myXMl = "<root>" +
                 "<parent1>Some Data</parent1>" +
                 "<parent2>" +
                   "<Child1 id='1' name='d1'>data1</Child1>" +
                   "<Child2 id='2' name='d2'>data2</Child2>" +
                 "</parent2>" +
               "</root>";

XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(myXMl);
XmlNodeList xNodeList = xDoc.SelectNodes("root/child::node()");

//Traverse the entire XML nodes.
foreach (XmlNode xNode in xNodeList)
{
    //Looks for any particular nodes
   
if (xNode.Name == "parent1")
    {
        //some traversing....
   
}

    if (xNode.Name == "parent2")
    {
        //If the parent node has child nodes then
        //traverse the child nodes
       
foreach (XmlNode xNode1 in xNode.ChildNodes)
        {
           string childNodeName = xNode1.Name;      //Ouputs: Child1
          
string childNodeData = xNode1.InnerText; //Outputs: data1

           //Loop through each attribute of the child nodes
          
foreach (XmlAttribute xAtt in xNode1.Attributes)
           {
               string attrName = xAtt.Name;   //Outputs: id
              
string attrValue = xAtt.Value; //Outputs: 1
          
}
        }
    }
}

Wednesday, 28 September 2011

Custom Date Formatting in C#


Every object has a method called ToString that returns a string representation of the object. The ToString method can accept a string parameter, which tells the object how to format itself – in the String.Format call, the formatting string is passed after the position, for example, “{0:##}”.
The text inside the curly braces is {index[,alignment][:formatString]}. If alignment is positive, the text is right-aligned in a field the given number of spaces; if it’s negative, it’s left-aligned.

Specifier
Type
Example
Example Output
dd
Day
{0:dd}
10
ddd
Day name
{0:ddd}
Tue
dddd
Full day name
{0:dddd}
Tuesday
f, ff, …
Second fractions
{0:fff}
932
gg, …
Era
{0:gg}
A.D.
hh
2 digit hour
{0:hh}
10
HH
2 digit hour, 24hr format
{0:HH}
22
mm
Minute 00-59
{0:mm}
38
MM
Month 01-12
{0:MM}
12
MMM
Month abbreviation
{0:MMM}
Dec
MMMM
Full month name
{0:MMMM}
December
ss
Seconds 00-59
{0:ss}
46
tt
AM or PM
{0:tt}
PM
yy
Year, 2 digits
{0:yy}
2
yyyy
Year
{0:yyyy}
2002
zz
Timezone offset, 2 digits
{0:zz}
-5
zzz
Full timezone offset
{0:zzz}
-05:00
:
Separator
{0:hh:mm:ss}
10:43:20
/
Separator
{0:dd/MM/yyyy}
10/12/2002

 

Ex:
string.Format("{0:yyyy-MM-dd}", DateTime.Today.Date)
Output:
2011-09-28