a developer's notes – a semi-technical web development BLOG

April 11, 2013

Parsing a Query String into an array with JavaScript

Filed under: Javascript / JQuery — Duy Nguyen @ 9:50 pm
Tags: , , , , , , , , ,

This brilliant method belongs to Joe Zim’s JavaScript Blog.

Here is the function.

    var parseQueryString = function( queryString ) {
        var params = {}, queries, temp, i, l;
     
        // Split into key/value pairs
        queries = queryString.split("&");
     
        // Convert the array of strings into an object
        for ( i = 0, l = queries.length; i < l; i++ ) {
            temp = queries[i].split('=');
            params[temp[0]] = temp[1];
        }
     
        return params;
    };

Using the function.

   function Test() {
        var qstring = "apple=7sf&orange=242&bananna=47614&cherry=8139";
        var myNewArray = parseQueryString(qstring);
    }

As you can see, you now have an array of all of your query strings!

parseQstring

May 15, 2012

How to convert a List of Strings into a List of Ints?

Filed under: C# — Duy Nguyen @ 2:25 pm
Tags: , , , , , , ,

Just use the foreach loop to convert each element and add to a new list.

        private static void ConvertStringListToIntList()
        {
            List<string> myStringList = new List<string>(){"0", "1", "2", "20", "16"};
            
            //does not work the way we want because they are strings
            myStringList.Sort();

            foreach (object o in myStringList)
            {
                Console.WriteLine(o); //output 0,1,16,2,20
            }

            List<int> myintList = new List<int>();

            foreach (var stringNubmer in myStringList)
            {
                int number = Convert.ToInt32(stringNubmer);
                myintList.Add(number);
            }

            //sorts the way we want because they are ints now
            myintList.Sort();

            Console.Write("\n"); //new line
            foreach (object o in myintList)
            {
                Console.WriteLine(o); //output 0,1,2,16,20
            }
        }

May 4, 2012

Creating and reading an XML String in C#

Filed under: C# — Duy Nguyen @ 2:11 pm
Tags: , , , ,

This is how to create an XML String with xmlTextWriter in .NET 4.0:

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);

xmlTextWriter.WriteStartElement("MYELEMENT");
xmlTextWriter.WriteAttributeString("my_attribute", "myValue");
xmlTextWriter.WriteElementString("ID", "myId");
xmlTextWriter.WriteEndElement();  //closing xml tag for ID
xmlTextWriter.WriteEndElement(); //closing xml tag for MYELEMENT

xmlTextWriter.Close();

return stringWriter.ToString();

Your XML:

<MYELEMENT my_attribute="myValue">
<ID>myId</ID>
<MYELEMENT>

Reading in XML with XmlTextReader

<filter>
	<sort by="teamName" direction="asc"/>
	<expressions>
		<expression type="nvarchar" field="teamName" operator="like" value="001"/>
	</expressions>
</filter>

private static void ReadXmlWithXmlTextReader(string xml)
{
	XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(xml));
	string sortFieldBy = string.Empty;
	string sortDirection = string.Empty;
	string filtertype = string.Empty;
	string filterField = string.Empty;
	string filterOperator = string.Empty;
	string filterValue = string.Empty;

	//  Loop over the XML file
	while (xmlTextReader.Read())
	{
		if (xmlTextReader.NodeType == XmlNodeType.Element)
		{
			if (xmlTextReader.Name == "sort")
			{
				sortFieldBy = xmlTextReader.GetAttribute("by");
				sortDirection = xmlTextReader.GetAttribute("direction");
			}

			if(xmlTextReader.Name == "expression")
			{
				filtertype = xmlTextReader.GetAttribute("type");
				filterField = xmlTextReader.GetAttribute("field");
				filterOperator = xmlTextReader.GetAttribute("operator");
				filterValue = xmlTextReader.GetAttribute("value");
			}
		}
	}
	xmlTextReader.Close();
}

In .NET 3.5: XDocument

XDocument doc = new XDocument(
    new XElement("root",
                 new XAttribute("name", "value"),
                 new XElement("child", "text node")));

From MSDN, “There are not many scenarios that require you to create an XDocument. Instead, you can usually create your XML trees with an XElement root node. Unless you have a specific requirement to create a document (for example, because you have to create processing instructions and comments at the top level, or you have to support document types), it is often more convenient to use XElement as your root node.”
Check this out.

XElement xml = new XElement("contacts",
                    new XElement("contact", 
                        new XAttribute("contactId", "2"),
                        new XElement("firstName", "Barry"),
                        new XElement("lastName", "Gottshall")
                    ),
                    new XElement("contact", 
                        new XAttribute("contactId", "3"),
                        new XElement("firstName", "Armando"),
                        new XElement("lastName", "Valdes")
                    )
                );
Console.WriteLine(xml);

Your XML:

<contacts>
  <contact contactId="2">
    <firstName>Barry</firstName>
    <lastName>Gottshall</lastName>
  </contact>
  <contact contactId="3">
    <firstName>Armando</firstName>
    <lastName>Valdes</lastName>
  </contact>
</contacts>

.NET version 3.0 or lower: XmlDocument

static private void BuildXmlForProc(List<int> mainIds)
{
	//ELEMENT CONSTANTS
	const string XML_DOCUMENT_ROOT_ELEMENT = "mids";
	const string MAIN_ID_ELEMENT = "mid";

	XmlDocument xmlDocument = new XmlDocument();
	XmlElement root = xmlDocument.CreateElement(XML_DOCUMENT_ROOT_ELEMENT);
	xmlDocument.AppendChild(root);

	foreach (var id in mainIds)
	{
		XmlElement mainId = xmlDocument.CreateElement(MAIN_ID_ELEMENT);
		mainId.InnerText = "4033";
		root.AppendChild(mainId);    
	}
}

<mids>
	<mid>4033</mid>
</mids>

You can always use the string builder class. http://www.devx.com/tips/Tip/41390

var stringBuilder = new StringBuilder();
stringBuilder.Append("<filter>");
stringBuilder.Append("<expressions>");

const string fieldType = "type=\"nvarchar\"";
const string filterOperator = "operator=\"LIKE\"";

if (filterParams != null)
{
	foreach (var filterParam in filterParams)
	{
		stringBuilder.Append("<expression " + fieldType +  " field=\"" + filterParam.Field + "\" " + filterOperator +  " value=\"" + filterParam.Data.Value + "\" />");
	}
}

stringBuilder.Append("</expressions>");
stringBuilder.Append("</filter>");

return stringBuilder.ToString();
<filter>
	<sort by="teamName" direction="asc"/>
	<expressions>
		<expression type="nvarchar" field="teamName" operator="like" value="001"/>
	</expressions>
</filter>

January 24, 2012

Method to get the count of a string occurrence in a string

Filed under: C# — Duy Nguyen @ 10:08 pm
Tags: , , , , , , , , ,
        /// <summary>
        /// Contains static text methods.
        /// </summary>
        public static class TextTool
        {
            /// <summary>
            /// Count occurrences of strings.
            /// </summary>
            public static int CountStringOccurrences(string text, string pattern)
            {
                // Loop through all instances of the string 'text'.
                int count = 0;
                int i = 0;
                while ((i = text.IndexOf(pattern, i)) != -1)
                {
                    i += pattern.Length;
                    count++;
                }
                return count;
            }
        }

September 5, 2011

Two ways to get an Enum with a string

Filed under: C# — Duy Nguyen @ 2:33 pm
Tags: , , ,

Two ways to get an Enum. Consider the following Enum:

 public enum MyEnumType
    {
        Default = 0,
        First,
        Second,
        Third,
    }

How to get an Enum type from a string equivalent to the Enum value?

(MyEnumType)Enum.ToObject(typeof(MyEnumType), Convert.ToInt16('1'));

// Gives you MyEnumType.First

How to get an Enum type from a string equivalent to the Enum name?

(MyEnumType)Enum.Parse(typeof(MyEnumType), 'Second', true); 

//passing in true as the third parameter makes it not case-sensitive
// Gives you MyEnumType.Second

How to get a value from an Enum?

int enumVal = (int)MyEnumType;

Convert comma separated string of ints to int array

Filed under: Javascript / JQuery — Duy Nguyen @ 1:47 pm
Tags: , , , , , , ,

From StackOverflow:
http://stackoverflow.com/questions/1763613/convert-comma-separated-string-of-ints-to-int-array/1763682#1763682

private static int[] StringToIntArray(string myNumbers)
{
    List<int> myIntegers = new List<int>();
    Array.ForEach(myNumbers.Split(",".ToCharArray()), s =>
    {
        int currentInt;
        if (Int32.TryParse(s, out currentInt))
            myIntegers.Add(currentInt);
    });
    return myIntegers.ToArray();
}

And some code to test:

static void Main(string[] args)
{
    string myNumbers = "1,2,3,4,5";
    int[] myArray = StringToIntArray(myNumbers);
    Console.WriteLine(myArray.Sum().ToString()); // sum is 15.

    myNumbers = "1,2,3,4,5,6,bad";
    myArray = StringToIntArray(myNumbers);
    Console.WriteLine(myArray.Sum().ToString()); // sum is 21

    Console.ReadLine();
}

Create a free website or blog at WordPress.com.