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.
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.
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!
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.
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.
TODO:
Have you ever wanted to POST SOAP to a .Net Webservice?
SOLUTION:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://myservice.com/myservice.asmx");
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\"><soapenv:Body>YOUR SOAP BODY HERE</soapenv:Body></soapenv:Envelope>";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytesToWrite = encoding.GetBytes(xmlString);
request.Method = "POST";
request.ContentLength = bytesToWrite.Length;
request.ContentType = "application/soap+xml; charset=UTF-8; action=\"http://myservice.com/MyMethod\"";
request.UserAgent = "Axis2";
request.Host = "myservice.com";
Stream newStream = request.GetRequestStream();
newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
newStream.Close();
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}
catch (WebException ex)
{
Console.WriteLine(ex);
WebResponse errRsp = ex.Response;
using (StreamReader rdr = new StreamReader(errRsp.GetResponseStream()))
{
Console.WriteLine(rdr.ReadToEnd());
}
}
NOTES:
No notes apply to this topic.
TODO:
Have you ever wanted to scroll to the last row of a DataGridView?
SOLUTION:
//add a row to the grid
dgvMyGrid.Rows.Add(rowdata);
//set the current cell, which will scroll to it
dgvMyGrid.CurrentCell = dgvMyGrid.Rows[dgvMyGrid.RowCount - 1].Cells[0];
NOTES:
There are no notes on this topic.
TODO:
Have youever wanted to find 2 words when parsing data, remove them, even though there may be a varying number of spaces between the words?
SOLUTION:
//set our test input string
string data = "what is thought is 1. the data is"; //our test string
//Now match on "is thought is" phrase with any number of SPACES between words
Match match = Regex.Match(data, "is\\s{1,}thought\\s{1,}is");
//Display if it was OK
Console.WriteLine("Success: " + match.Success);
//Display the index
Console.WriteLine("Index: " + match.Index);
//Display the length of the matched string
Console.WriteLine("Length: " + match.Length);
//Now grab everything AFTER the matched string
Console.WriteLine("Trimmed: " + data.Substring(match.Index +match.Length));
NOTES:
The output is:
Success: True
Index: 5
Length: 19
Trimmed: 1. the data is
TODO:
Have you ever wanted to get the elapsed seconds between 2 dates?
SOLUTION:
int elapsed_seconds = DateTime.Now.Subtract(MyDate).TotalSeconds;
NOTES:
There are no notes ont his topic
TODO:
Have you ever wanted to search a document for nodes with a certain name, and get their associated value?
SOLUTION:
string productCode = "";
//get a node list of all products with a venue id of 278652
XmlNodeList events = myDocument.DocumentElement.SelectNodes("product[VenueID='278652']");
//go through each node and get the product code
foreach (XmlNode eventNode in events)
{
productCode = eventNode.SelectSingleNode("product_code").InnerText;
//do some other stuff here...
}
NOTES:
No notes on this topic.