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 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!

Handy C# Regular Expressions



TODO:

Have you ever been looking for handy RegExp's.  I have grabbed a few I use from time to time and have put them below.

 

SOLUTION:

 

//Find first non-digit
Regex firstNonDigitIndexRegexp = new Regex(@"\D",RegexOptions.RightToLeft);

//Test if a string ends with a digit
Regex endsWithDigitRegexp = new Regex(@"\d$");      

//Test if a string starts with a digit
Regex startsWithDigitRegexp = new Regex(@"^\d");

//Find the last digit in a string
Regex lastDigitIndexRegexp = new Regex(@"\d", RegexOptions.RightToLeft);

//Test if a string contains only digits
Regex numbersOnlyRegExp = new Regex(@"\D");

//Validate an email address
public bool ValidateEmail(string  EmailAddress)
{
     string patternToMatch = @"^([a-zA-Z0-9_\+\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
     System.Text.RegularExpressions.Match match = Regex.Match(EmailAddress, patternToMatch, RegexOptions.IgnoreCase);
     return match.Success;
}

// Validate a URL
public static bool IsUrlValid(string url)
{
     //ensure we have a valid prefix
     if(!Regex.IsMatch(url, @"^(http|https)\:(\\\\|//)", RegexOptions.IgnoreCase))            
          url = String.Concat("http://", url);   //default to http

     string pattern = @"^(http|https)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$";
     Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
     return reg.IsMatch(url);
}

 

 

NOTES:

No notes apply on this topic.