How To Create a Guid Without Dashes Using C#



TODO

Have you ever wanted a Guid and did not want the dashes?

 

SOLUTION:

 

string batchId = Guid.NewGuid().ToString("N");

 

 

NOTES:

There are no notes on this topic.

How To Iterate A Hashtable Using C#



TODO:

Have you ever wanted to iterate a Hashtable?

 

SOLUTION:

Hashtable myHashTable = new Hashtable();

myHashTable.Add("ES", 1);
myHashTable.Add("EN", 2);
myHashTable.Add("FR", 4);
myHashTable.Add("RU", 3);

//now go through our hash
foreach (object obj in myHashTable.Keys)
{
     //check for the value is 4
     if ((int)myHashTable[obj] == 4)
     {
          //do something
     }

     Console.WriteLine(String.Format("Key: {0}, Value: {1}", obj, myHashTable[obj]));
}

 

NOTES:

The application of this example may not make sense, but it was to illustrate how to iterate a Hashtable, and analyse the value of a key.  A real life applicaiton could be that I have a document that has 4 sections.  A source delivers it in numerous languages, and each language may or may not have all of the sections populated.  I need to keep track of which lanugage has populated sections, so that I can display the most populated version of the document.  In this case I would store the language in the Hashtable as the Key, and then when I get a section, I can simply increment the Value for the Key (in this case the language).  When my loading of the document is complete I can then get the Language for the most populated section, and then do things, like display a flag or somethine else.

How To Serialize An Object Using C#



TODO:

Have you ever wanted to Serialize an object using C#?  The method I created below, will allow you to pass in an object and turn it into an XML Document.

 

SOLUTION:

/// <summary>
/// 
/// </summary>
/// <param name="myObject"></param>
/// <returns></returns>
public static XmlDocument MakeXmlDocumentFromObject(Object myObject)
{
     UTF8Encoding encoding = new UTF8Encoding();
     XmlDocument returnObject = new XmlDocument();

     try
     {
          //create our serializer
          XmlSerializer xmlSerial = new XmlSerializer(myObject.GetType());

          //get it....
          using (MemoryStream memStream = new MemoryStream())
          {
               //serialize the object
               xmlSerial.Serialize(memStream, myObject);

               //load the XML now, and we will return it....
               returnObject.LoadXml(encoding.GetString(memStream.GetBuffer()));
          }

          return returnObject;
     }
     catch (Exception)
     {
          return null;
     }
}

 

NOTES:

There are no notes on this subject.

How to Transform XML Using XSLT And Deserialize The Result Using C#



TODO:

Have you ever wanted to load an XML Document, transform it using XSLT, and conver the result into a Class object?  This is handly so that you could take XML in various formats, use XSLT to transform it, and load it into Classes that your system knows about.

 

SOLUTION:

Dog myDog = new Dog();
XmlSerializer xmlSerial = new XmlSerializer(typeof(Dog));   //create the xmlserializer for class Dog
XmlDocument myXMLDocument = new XmlDocument();              //create the xml document
StringBuilder output = new StringBuilder();                 //create the string builder for the output
XslCompiledTransform myXslTrans = new XslCompiledTransform();  //create the xsl obj for transformation
XmlWriterSettings writerSettings = new XmlWriterSettings();    //create the writer settings object, as we want to omit XML declaration
writerSettings.OmitXmlDeclaration = true;                      //now set the omit flag to true
myXMLDocument.Load(@"c:\DogInput.xml");

//load xslt file
myXslTrans.Load(xsltfile);

//create an xmlwriter of out data
using (XmlWriter transformedData = XmlWriter.Create(output, writerSettings))
{
     //transform the document
     myXslTrans.Transform(myXMLDocument, transformedData);

     //now turn the string builder into an obj
     using (StringReader xmlString = new StringReader(output.ToString()))
     {
          myDog = (Dog)(xmlSerial.Deserialize(xmlString));
     }
}

 

NOTES:

Dog is a class i created to illustrate this task, you will put your classname in place of it.  The variable "xsltfile" is the path to your XSLT file.

How To Read A Web Page using C#



TODO:

Have you ever wanted to read a web page into a string using C#?

 

SOLUTION:

 

public string ReadPage(string sUrl)
{
       HttpWebRequest req = null;
       HttpWebResponse res = null;
       try
       {
             req = (HttpWebRequest)WebRequest.Create(sUrl);
             res = (HttpWebResponse)req.GetResponse();
             using (StreamReader sReader = new StreamReader(res.GetResponseStream()))
             {
                  return sReader.ReadToEnd();
             }
       }
       catch (Exception x)
       {
             LastErrorMessage = x.ToString();
             LastErrorMessageFriendly = x.Message;
             return "";
       }
}

 

 

NOTES:

There are no notes on this topic.

How To Create A Table From A SELECT Statement



TODO:

Have you ever wanted to create a table from the results of a SELECT statement?

 

SOLUTION:

 

select * into newtable_tmp from oldtable

 

 

NOTES:

This statement will select all columns and records from the table "oldtable", and create a new table called "newtable_tmp" that contains the results of the SELECT statement.

How To Call A SQL Server Stored Procedure And Use Output Paramaters In C#



TODO:

Have you ever wanted to call a stored procedure, and use an output parameter in C#?

 

SOLUTION:

 

using (SqlConnection myConnection = new SqlConnection(<YOUR CONNECTION STRING>))
{
    string _Number = "D3R42ed"; //test number to lookup
    long _ReturnId = -1;  //test value for the output param

    //do the command stuff now
    using (SqlCommand UserInfoCmd = new SqlCommand())
    {
        UserInfoCmd.CommandType = CommandType.StoredProcedure;
        UserInfoCmd.CommandTimeout = 30;
                       
        UserInfoCmd.CommandText = "usp_myStoredProcedure";  //your stored procedure name here
        UserInfoCmd.Parameters.Add("@Number", System.Data.SqlDbType.VarChar, 25).Value = _Number;  //set the number parameter
        
        SqlParameter outparm = UserInfoCmd.Parameters.Add("@ReturnValue", System.Data.SqlDbType.BigInt, 0); //Add the parameter
        outparm.Direction = ParameterDirection.Output;  //tell it, it is an OUTPUT param
        
        myConnection.Open();  //open the connection
        UserInfoCmd.Connection = myConnection;  //set the connection

        //harvest abstract here
        using (SqlDataReader myReader = UserInfoCmd.ExecuteReader())  //now execute the command
        {
            //see if we can read
            if (myReader.Read())
            {
                string SomeName = myReader.IsDBNull(0) ? "" : myReader.GetSqlString(0).Value.Trim();  //get some test value from the SP select statement

                myReader.Close();  //VERY IMPORTANT, CLOSE BEFORE ACCESSING OUTPUT PARAMS
                _ReturnId = Convert.ToInt64(UserInfoCmd.Parameters["@ReturnValue"].Value);  //now get the output param value            
            }
        }
    }
}

 

 

NOTES:

Be sure to close the SqlDataReader before accessing the output parameters!

How To Find a Node At Any Level In An XML Document



TODO:

Have you ever wanted to find a Node, named "CustomerName" for example anywhere in an XML Document?

 

SOLUTION:

 

XmlNodeList customerNameNodes = MyXMLDocument.SelectNodes("//CustomerName");

 

NOTES:

There are no notes on this topic.

How To Copy All Nodes Of An XML Document And Add An Atrribute To Each Node



TODO:

Have you ever wanted to copy all nodes of an xml document, and add an attribute to each node?

 

SOLUTION:

 

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl">
  <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
  <xsl:template match="*">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:attribute name="dirty">true</xsl:attribute>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

 

 

NOTES:

I had a problem, in that I had an Object that had over 50+ properties.  When I took in XML and deserialized it, I did not know what nodes were supplied.  I wanted to allow folks to pass in just the parts of the document they wanted to update, but had no notion of "dirty".  This will add a "dirty" attribute to all nodes, which allows me to easily grab only the dirty ones, and update my database accordingly.

How To Pass A Parameter To A Custom User Control In BlogEngine.net 2.5



TODO:

Have you ever wanted to use a Custom Control in BlogEngine.net, and also pass a parameter to that UserControl?

 

SOLUTION:

Create a Page or Post, and put the following line right into the editor.

 

ERROR - UNABLE TO LOAD CONTROL : ~/User Controls/MyGallery.ascx ImageDir=/blah/blah; MyOtherProp=blah;

 

 

NOTES:

The example above loads the MyGallery.ascx control from the "User Controls" directory, and set the properties on the UserControl named "ImageDir" and "MyOtherProp".

The above example assumes you have created the properties "ImageDir" and "MyOtherProp" on your UserControl.