Escolar Documentos
Profissional Documentos
Cultura Documentos
Here's a fasttrack arrangement of code samples for learning C#. 1. Code Samples: 1. The obligatory example for any language,
2. 3. 4. 5. 6. 7. 8. 9. using System; public class HelloWorld { public static void Main(string[] args) { Console.Write("Hello World!"); } }
10. Raw CSharp compiler You can compile c# using the command line version
C:>csc HelloWorld.cs
You can get Nant, a build tool like the old 'make', from http://sourceforge.net/projects/nant. 11. Reading Stuff 1. Read an entire file into a string
2. using System; 3. namespace PlayingAround { 4. class ReadAll { 5. public static void Main(string[] args) { 6. string contents = System.IO.File.ReadAllText(@"C:\t1"); 7. Console.Out.WriteLine("contents = " + contents); 8. } 9. } 10. }
21. 22. 23. 24. 25. 26. 28. 29. 30. 31. 32. 33.
} return contents;
39. Read a file line by line with no error checking Useful if the file may be really large.
StreamReader sr = new StreamReader("fileName.txt"); string line; while((line= sr.ReadLine()) != null) { Console.WriteLine("xml template:"+line); } if (sr != null)sr.Close(); "using" block //should be in a "finally" or
12. Writing Stuff 1. Easy writing all text to a file WriteAllText will create the file if it doesn't exist, otherwise overwrites it. It will also close the file.
using System; namespace PlayingAround { class ReadAll { public static void Main(string[] args) { string myText = "Line1" + Environment.NewLine + "Line2" + Environment.NewLine; System.IO.File.WriteAllText(@"C:\t2", myText); } } }
20. Access files with "using" "using" does an implicit call to Dispose() when the using block is complete. With files this will close the file. The following code shows that using does indeed close the file, otherwise 5000 open files would cause problems.
using System; using System.IO; class Test { private static void Main() { for (int i = 0; i < 5000; i++) { using (TextWriter w = File.CreateText("C:\\tmp\\test\\log" + i + ".txt")) { string msg = DateTime.Now + ", " + i; w.WriteLine(msg); Console.Out.WriteLine(msg); } } Console.In.ReadLine(); } }
29. 30.
);
Console.Write("\n{0}<{1}",levelDepth,xmlElement.Name
XmlAttributeCollection xmlAttributeCollection = xmlElement.Attributes; 31. foreach(XmlAttribute x in xmlAttributeCollection) 32. { 33. Console.Write(" {0}='{1}'",x.Name,x.Value); 34. } 35. Console.Write(">"); 36. XmlNodeList xmlNodeList = xmlElement.ChildNodes; 37. ++level; 38. foreach(XmlNode x in xmlNodeList) 39. { 40. if(x.NodeType == XmlNodeType.Element) 41. { 42. writeTree((XmlNode)x, level); 43. } 44. else if(x.NodeType == XmlNodeType.Text) 45. { 46. Console.Write("\n{0} {1}",levelDepth, (x.Value).Trim()); 47. } 48. } 49. Console.Write("\n{0}</ {1}>",levelDepth,xmlElement.Name); 50. }
Console.WriteLine(" '{0,8}'","Test"); // produces: Test' 65. Console.WriteLine(" '{0,-8}'","Test");// produces: 'Test ' 66. Console.WriteLine(" '{0:X}'",k); //(in HEX) produces: '10' 67. Console.WriteLine(" '{0:X10}'",k); //(in HEX) produces:'0000000010' 68. Console.WriteLine( 1234567.ToString("#,##0")); // writes with commas: 1,234,567 69.
or
String.Format("{0,8:F3}",this.OnTrack)
Produces:
inside static construtor... Test2 inside regular construtor... i=4
using System; namespace Test2 { class Plane { public double TopSpeed() { return 300.0D; } } class Jet : Plane { public double TopSpeed() { return 900.0D; } } class Airport { static void Main(string[] args) { Plane plane = new Jet(); Console.WriteLine("planes top speed: {0}",plane.TopSpeed()); 54. Console.ReadLine(); 55. } 56. } 57. } 58.
This, oddly enough will print "300" for the planes speed, since TopSpeed() is not virtual. To fix the problem we need to declare the method virtual *and* that the subclass "override"s the method. If we don't set Jet's method to override, we still get "300")
class Plane { public virtual double TopSpeed() { return 300.0D; } } class Jet : Plane { public override double TopSpeed() { return 900.0D; } }
This will not give "900" as the top speed. You can omit the virtual and override methods and be ok as long as you don't expect classes to ever be referred to as a superclass (which is extremely bad practice). For example:
class Plane { public double TopSpeed() { return 300.0D;
} class Airport { [STAThread] static void Main(string[] args) { Plane plane = new Jet(); Console.WriteLine("plane's top speed: {0}",plane.TopSpeed()); Jet jet = new Jet(); Console.WriteLine("jet's top speed: {0}",jet.TopSpeed()); Console.ReadLine(); } }
59. Example of overloading an operator. Note many operators MUST be overloaded as a pair, eg, > , <
60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. public class Plane { public virtual double TopSpeed() { return 300.0D;} public static bool operator>(Plane one, Plane two) { return one.TopSpeed() > two.TopSpeed(); } public static bool operator<(Plane one, Plane two) { return one.TopSpeed() < two.TopSpeed(); } } class Jet : Plane { public override double TopSpeed() { return 900.0D; } public override string ToString() { return "I'm a Jet"; } 72. } 73. class Airport { 74. [STAThread] 75. static void Main(string[] args) { 76. Plane plane = new Jet(); 77. Console.WriteLine("plane's top speed: {0}",plane.TopSpeed()); 78. Jet jet = new Jet(); 79. Console.WriteLine("jet's top speed: {0}",jet.TopSpeed()); 80. Console.WriteLine("Plane > Jet = {0}", plane > jet); 81. Console.ReadLine(); 82. } 83. } 84.
85. Example of using Properties instead of accessor methods. Note the special use of the "value" variable in "set".
86. public class Plane { 87. protected double mySpeed = 300.0D; 88. public double TopSpeed { 89. get {return mySpeed;} 90. set { mySpeed = value; } 91. } 92. } 93. class Jet : Plane { 94. public Jet() { TopSpeed = 900.0D; } 95. } 96. class Airport { 97. [STAThread] 98. static void Main(string[] args) { 99. Plane plane = new Plane(); 100. Console.WriteLine("plane's top speed: {0}",plane.TopSpeed); 101. Jet jet = new Jet(); 102. Console.WriteLine("jet's top speed: {0}",jet.TopSpeed); 103. Console.ReadLine(); 104. } 105. }
106.
107. 108.
To specify a format: dt.ToString("yyyy/MM/dd") The cultural-independent universal format: dt.ToString("u") which prints "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 109.
110. 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122.
123. line
124. 125. 126. 127. 128.
Download a web page and print to console all the urls on the command
using System; using System.Net; using System.Text; using System.IO; namespace Test {
129. 130. 131. 132. 133. 134. 135. 136. 137. ; 138. 139. 140. 141. 142. 143. 144. 145. 146.
class GetWebPage { public static void Main(string[] args) { for(int i=0;ilt;args.Length;i++) { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(args[i]); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse() Stream stream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.ASCII); Console.WriteLine(streamReader.ReadToEnd()); } Console.Read(); } } }
Or you can use a static method to download a web page into a string:
public static string GetWebPageAsString(string url) { HttpWebRequest httpWebRequest =(HttpWebRequest)WebRequest.Create(url); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); Stream stream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.ASCII); return streamReader.ReadToEnd(); }
147.
How to get the content of the page even with errors like 500 or 404 is shown below:
{ public static string GetWebPageAsString(string url)
HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(url); HttpWebResponse httpWebResponse = null; string xml = ""; try { httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse(); } catch (WebException exception) { if (exception.Status == WebExceptionStatus.ProtocolError) { //get the response object from the WebException
httpWebResponse = exception.Response as HttpWebResponse; if (httpWebResponse == null){ return "<Error />";} } } Stream stream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.ASCII); xml = streamReader.ReadToEnd(); //streamReader.Close(); if (httpWebResponse.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception(xml); } } return xml;
148. Use System.Web.HttpUtility.HtmlEncode() to encode strings for display in the browser. Converts "<" to <.
this.Response.Write("<br />xml returned: \"" + HttpUtility.HtmlEncode(xml) + "\"");
149.
150. 151. 152. 153.
What's the units for the argument to Sleep? You can make it more implicit by using TimeSpan.From* format:
Thread.Sleep(TimeSpan.FromMilliseconds(50));
155. using System; 156. class Parse { 157. /// <summary> 158. /// Example of various Parse methods 159. /// </summary> 160. private static void Main() { 161. 162. //all the types in .Net have a Parse method 163. int i = int.Parse("34"); 164. bool b = bool.Parse("true"); 165. double d = double.Parse("234.333"); 166. DateTime dateTime = DateTime.Parse("2008-03-02 12:20am"); 167. 168. //TryParse will return false if the parsing fails 169. int intvalue; 170. bool ok = int.TryParse("42", out intvalue); //ok = True, intvalue = 42 171. ok = int.TryParse("abc", out intvalue); //ok = False, intvalue = 0 172. 173. //ParseExtact takes a format 174. DateTime dt = DateTime.ParseExact("02-03-2008", "dd-MMyyyy", 175. System.Globalization.CultureInfo.CurrentCulture); //dt = 3/2/2008 12:00:00 AM 176. 177. Console.Out.WriteLine("dt = " + dt); 178. Console.In.ReadLine(); 179. } 180. }
181.
182.
Tiny Browser
193. 194.
195.
24. Read an xml file, twist it with an xsl file and then write to a string (no error checking)
25. 26. 27. 28. 29. 30. 31. 32. using using using using System; System.IO; System.Xml; System.Xml.Xsl;
class WriteXMLViaXSL { //read an xml file, twist it with an xsl file and then write to a string (no error checking) 33. public static void Main(string[] args) 34. { 35. XmlDocument xmlDocument = new XmlDocument(); 36. xmlDocument.Load(args[0]); 37. 38. XslTransform xslTransform = new XslTransform(); 39. xslTransform.Load(args[1]); 40. 41. 42. StringWriter stringWriter = new StringWriter(); 43. XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); 44. xmlTextWriter.Formatting = Formatting.Indented; 45. xslTransform.Transform(xmlDocument, null, xmlTextWriter); 46. 47. xmlTextWriter.Flush(); 48. Console.Write(stringWriter.ToString());
49. 50.
51. Another example reading xml and xslt info from two files and transforming with the more modern XslCompiledTransform
52. 53. 54. [Test] public void Transform() { const string xmlFileNameWithPath = @"C:\workfiles\SwitchBoard\SwitchBoardHandler\Tests\Inciden ce1.xml"; 55. const string xslFileNameWithPath = @"C:\workfiles\SwitchBoard\SwitchBoardHandler\xslt\Incidenc e.xslt"; 56. XslCompiledTransform xslCompiledTransform = new XslCompiledTransform(); 57. xslCompiledTransform.Load(xslFileNameWithPath); 58. StringBuilder stringBuilder = new StringBuilder(); 59. StringWriter stringWriter = new StringWriter(stringBuilder); 60. xslCompiledTransform.Transform(xmlFileNameWithPath, null, stringWriter); 61. stringWriter.Close(); 62. Console.Out.WriteLine("sb.ToString() = {0}", stringBuilder.ToString()); 63. }
86.
public static string TransformXmlStringWithXslString(string xmlString, string XSLStylesheet) 87. { 88. //process our xml 89. XmlTextReader xmlTextReader = 90. new XmlTextReader(new StringReader(xmlString)); 91. XPathDocument xPathDocument = new XPathDocument(xmlTextReader); 92. 93. //process the xsl 94. XmlTextReader xmlTextReaderXslt = new XmlTextReader(new StringReader(XSLStylesheet)); 95. XslCompiledTransform xslCompiledTransform = new XslCompiledTransform(); 96. xslCompiledTransform.Load(xmlTextReaderXslt); 97. 98. //handle the output stream 99. StringBuilder stringBuilder = new StringBuilder(); 100. TextWriter textWriter = new StringWriter(stringBuilder); 101. 102. //do the transform 103. xslCompiledTransform.Transform(xPathDocument, null, textWriter); 104. return stringBuilder.ToString(); 105. } 106. ... 107. [Test] 108. public void TransformXmlStringWithXsltString() { 109. KoEndPoint koEndPoint = new KoEndPoint("test",null); 110. string result = koEndPoint.TransformXmlStringWithXslString("<person name='Francis Bacon' />", "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:templ ate match='/'>Person:<xsl:apply-templates select='*' /></xsl:template><xsl:template match='/person'><xsl:valueof select='@name' /></xsl:template></xsl:stylesheet>"); 111. Console.Out.WriteLine("result = " + result); 112. result.ShouldEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?>Person:Francis Bacon"); 113. } 114.
115. file
116. using System; 117. using System.IO; 118. using System.Xml; 119. 120. class CreateXMLDoc 121. { 122. //creates an xml doc programatically and writes to the console and a file 123. public static void Main(string[] args) 124. {
125. XmlDocument xmlDocument = new XmlDocument(); 126. xmlDocument.PrependChild(xmlDocument.CreateXmlD eclaration("1.0", "", "yes")); 127. XmlElement element = xmlDocument.CreateElement("Book"); 128. element.SetAttribute("author","Xenophone"); 129. element.AppendChild(xmlDocument.CreateTextNode("The Persian Expedition")); 130. xmlDocument.AppendChild(element); 131. 132. StringWriter stringWriter = new StringWriter(); 133. XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); 134. xmlTextWriter.Formatting = Formatting.Indented; 135. 136. xmlDocument.WriteTo(xmlTextWriter); 137. xmlTextWriter.Flush(); 138. Console.Write(stringWriter.ToString()); 139. //get the value of the enviromental variable "TEMP" 140. string filename = 141. System.Environment.GetEnvironmentVariable("TEMP ")+"\\Book.xml"; 142. //write to a file in temp directory also 143. xmlDocument.Save(filename); 144. } 145. }
146.
StringBuilder html = new StringBuilder("<table class='xmlTable'>\r\n<tr>"); foreach (var attribute in xmlAttributeCollection) { html.Append("<th>"+attribute.Name+"</th>"); } html.Append("</tr>"); foreach (XElement element in root.Descendants()) { html.Append("\r\n<tr>"); foreach (XAttribute attrib in element.Attributes()) { html.Append("<td>"+attrib.Value+"</td>" ); } html.Append("</tr>"); } html.Append("</table>"); return html.ToString(); } } }
196.
private void Page_Load(object sender, System.EventArgs e) { string survey = Request.Params.Get("survey")); ... } <!--#include file="w:/mydir/data/Xsl/Footer.xsl" -->
201.
202. 203.
} } } }
fileStream.Close();
204.
205. 206. 207. 208. 209. 210. 211. 212. 213. 214. 215. 216. 217. 218.
using System.Collections; using System.Collections.Specialized; ... NameValueCollection collection = Request.QueryString; String[] keyArray = collection.AllKeys; Response.Write("Keys:"); foreach (string key in keyArray) { Response.Write(" " + key +": "); String[] valuesArray = collection.GetValues(key); foreach (string myvalue in valuesArray) { Response.Write("\""+myvalue + "\" "); } }
219.
220. public static string ToHTML(Hashtable hashtable) { 221. string tmp = ""; 222. IDictionaryEnumerator myEnumerator = hashtable.GetEnumerator(); 223. while ( myEnumerator.MoveNext() ) { 224. tmp += "<br />" + myEnumerator.Key+", "+ myEnumerator.Value; 225. } 226. return tmp; 227. } 228. public static string ToHTML(ArrayList arrayList) { 229. StringBuilder tmp = new StringBuilder(); //needs System.Text; 230. foreach ( Object o in arrayList ) { 231. tmp.Append("<br />" + o); 232. } 233. return tmp.ToString(); 234. }
235. How to pass a variable number of arguments to a method using the ''params' method parameter modifier 'params' must be the last parameter in the list.
using System; public class Params { static private void Test(string name, params int[] list) { Console.Write("\n"+name); foreach(int i in list) { Console.Write(i); } }
236.
237. ///<summary> 238. ///executes a system command from inside csharp 239. ///</summary> 240. ///<param name="cmd">a dos type command like "isql ..."</param> 241. 242. ///<param name ="millsecTimeOut">how long to wait on the command</param> 243. 244. public static int executeCommand(string cmd, int millsecTimeOut) { 245. System.Diagnostics.ProcessStartInfo processStartInfo = 246. new System.Diagnostics.ProcessStartInfo("CMD.exe", "/C "+cmd); 247. processStartInfo.CreateNoWindow = true; 248. processStartInfo.UseShellExecute = false; 249. System.Diagnostics.Process process = 250. System.Diagnostics.Process.Start(processStartInfo); 251. process.WaitForExit(millsecTimeOut); //wait for 20 sec 252. int exitCode = process.ExitCode; 253. process.Close(); 254. return exitCode; 255. }
256.
Example of retrieving an XML document from a web service and then applying an XSLT stylesheet on the server side.
public class ScreenerQuestionsToAsk : System.Web.UI.Page { private void Page_Load(object sender, System.EventArgs e) { GetSurveyDescriptorXMLService service = new GetSurveyDescriptorXML Service(); XmlDocument xmlDocument = service.GetAllSurveyDescriptorsAsXMLDoc(); string output = Util.WriteXMLViaXSL(xmlDocument, "w:/mydir/data/Xsl/ScreenerQuestionsToAsk.xsl"); Response.Write(output);
257.
258. public static string ToHTML(XmlNodeList xmlNodeList) { 259. StringWriter stringWriter = new StringWriter(); 260. XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); 261. xmlTextWriter.Formatting = Formatting.Indented; 262. foreach(XmlNode xmlNode in xmlNodeList) { 263. xmlNode.WriteTo(xmlTextWriter); 264. } 265. return stringWriter.ToString(); 266. }
267.
270.
Exit message
271. Console.WriteLine("Initialization failed. sorry.\r\n"); 272. System.Threading.Thread.Sleep(5000); //same as java's Sleep() 273. Environment.Exit(1); //same as java's System.Exit(0);
274.
Tokenize string
275.
Using "Split"
Example of the StringSplitOptions.RemoveEmptyEntries option. This will remove the blank entries from the array.
using System; class Animals { private static void Main() { string[] animals = "monkey,kangaroo,,,wallaby,,devil,,".Split(",".ToCharArray(),Stri ngSplitOptions.RemoveEmptyEntries); foreach (string animal in animals) { Console.Out.WriteLine("animal = " + animal); } Console.In.ReadLine(); } }
276.
Instead of repeatedly calling Add() to initialize an arrayList, AddRange() can be used with the default initializer for an array.
ArrayList ab = new ArrayList(); ab.Add("a"); //old fashioned way ab.Add("b"); ArrayList abcd = new ArrayList(); abcd.AddRange(new string[] {"a","b","c","d"}); // new hip method
277.
Arrays
278.
NUnit
279.
Working with our friend the database 1. Accessing a database Let's return a single string from a database
static public string GetSqlAsString(string sqlText, SqlParameter[] sqlParameters, string databaseConnectionString) { string result = ""; SqlDataReader reader; SqlConnection connection = new SqlConnection(databaseConnectionString); using (connection) { SqlCommand sqlcommand = connection.CreateCommand(); sqlcommand.CommandText = sqlText; if (sqlParameters != null) { sqlcommand.Parameters.AddRange(sqlParameters); } connection.Open(); reader = sqlcommand.ExecuteReader(); if (reader != null) if (reader.Read()) { result = reader.GetString(0); } } return result; }
2. Timeout expired exception If you get the following exception: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) Your command may really taking too long in the database and has been killed. You can increase the default time of 30 seconds by using the "CommandTimeout" field on the "Command" object as shown below:
using (connection) { SqlCommand sqlcommand = connection.CreateCommand(); sqlcommand.CommandTimeout = 60; //default is 30 seconds sqlcommand.CommandText = sqlText;
...
Don't be misled by the database connection string option, "Connection Timeout", e.g., "Data Source=myMachine; Integrated Security=SSPI; database=Northwind;Connection Timeout=60". That timeout is for getting the connection, not for how long it queries the database. 3. Register a delegate Example of adding an InforMessage handler to a connection object.
public static void MessageEventHandler( object sender, SqlInfoMessageEventArgs e ) { foreach( SqlError error in e.Errors ) { Console.WriteLine("problem with sql: "+error); throw new Exception("problem with sql: "+error); } } public static int executeSQLUpdate(string database, string command) { SqlConnection connection = null; SqlCommand sqlcommand = null; int rows = -1; try { connection = getConnection(database); connection.InfoMessage += new SqlInfoMessageEventHandler( MessageEventHandler ); sqlcommand = connection.CreateCommand(); sqlcommand.CommandText = command; connection.Open(); rows = sqlcommand.ExecuteNonQuery(); } catch(Exception e) { Console.Write("executeSQLUpdate: problem with command:"+command+"e="+e); Console.Out.Flush(); throw new Exception("executeSQLUpdate: problem with command:"+command,e); } finally { if(connection != null) { connection.Close(); } } return rows; }
4. ExecuteScalar Example of a utility function that uses ExecuteScalar, and a utility function to free resources (which is now obsolete - you should use the "using" construct).
public static int getSQLAsInt(string database, string command) {
int i = -1; SqlConnection connection = null; SqlCommand sqlcommand = null; try { connection = UtilSql.getConnection(database); sqlcommand = connection.CreateCommand(); sqlcommand.CommandText = command; connection.Open(); i = (int)sqlcommand.ExecuteScalar(); } catch (Exception e) { throw new Exception(Util.formatExceptionError("getSQLAsInt",command,e )); } finally { UtilSql.free(null,connection); } return i; } public static void free(SqlDataReader reader, SqlConnection connection) { try { if(reader != null) { reader.Close(); } } catch (Exception) {} try { if(connection != null) { connection.Close(); } } catch () {} // we don't have to declare Exception }
5. Example of Parameterized SQL To avoid SQL injection attacks you should always use parameters
using using using using System; System.IO; System.Collections.Generic; System.Text;
using System.Data.SqlClient; using System.Data; namespace SQLTest { class SqlParameterization { /// <summary> /// example of using parameterized sql to avoid SQL injection attacks /// </summary> static void Main() { Console.Out.WriteLine("Authors whose state is CA:"); SqlConnection sqlConnection = null; string dbconn = "Application Name=SqlTest; Data Source=localhost; Trusted_Connection=yes; database=pubs"; try {
sqlConnection = new SqlConnection(dbconn); sqlConnection.Open(); SqlCommand cmd = new SqlCommand("SELECT au_lname FROM Authors WHERE state = @state", sqlConnection); cmd.CommandType = CommandType.Text; SqlParameter param = new SqlParameter("@state", SqlDbType.Char, 2); param.Direction = ParameterDirection.Input; param.Value = "CA"; cmd.Parameters.Add(param); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(String.Format("{0}", reader[0])); } } finally { if (sqlConnection != null) { sqlConnection.Close(); } } Console.In.ReadLine(); } } }
These lines
SqlParameter param = new SqlParameter("@state", SqlDbType.Char, 2); param.Direction = ParameterDirection.Input; param.Value = "CA";
can be shortened to
"CA"); SqlParameter param = new SqlParameter("@state",
Since the default direction is "Input". Performance implications of the shortcut method are not known. 6. Using SqlDataAdapter with Parameters
7. conn = ... //connection string 8. 9. strSql = ... //sql string with @ variables like SELECT * FROM Authors WHERE name = @name 10. DataSet dataSet = new DataSet(); 11. SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, conn); 12. dataAdapter.SelectCommand.Parameters.Add(new SqlParameter("name", "OHenry")); 13. dataAdapter.Fill(dataSet, "dataTable1"); 14.
280. 281.
Array sorting Example of using "using" to avoid the finally block mess
a "using" block will execute its contents and then immediately call "Dispose()" on the using object. For connections, this will close the connection.
using System; using System.Data.SqlClient; class Test { private static readonly string connectionString = "Data Source=myMachine; Integrated Security=SSPI; database=Northwind"; private static readonly string commandString = "SELECT count(*) FROM Customers"; private static void Main() { using (SqlConnection sqlConnection = new SqlConnection(connectionString)) { using (SqlCommand sqlCommand = new SqlCommand(commandString, sqlConnection)) { sqlConnection.Open(); int count = (int)sqlCommand.ExecuteScalar(); Console.Out.WriteLine("count of customers is " + count); } } Console.In.ReadLine(); } }
To sort an array use the static method on Array class. (I don't know why array.sort() does not exist as a method)
String[] keyArray = nameValueCollection.AllKeys; Array.Sort(keyArray);
282.
Using XPath
The tricky thing about getting the attribute value is using the function 'string()' inside your XPath expression. Otherwise it returns a nodeSetIterator that you have to process.
using System.Xml; using System.Xml.XPath; ... XPathDocument xPathDocument = new XPathDocument(fileName); XPathNavigator xPathNavigator = xPathDocument.CreateNavigator(); string text = (string) xPathNavigator.Evaluate("string(//Survey[@name='"+survey+"']/@URL )");
283.
using block
C# provides a special way of disposing of objects after their use - it's the "using" block. The object of the "using" statement must implement the IDisposable interface which contains one member, Dispose(). As shown below, after the "using" block is executed, Dispose() is immediately called.
using System; namespace Doodle { class DisposableExample : IDisposable { public void Dispose() { Console.Out.WriteLine("I'm being disposed!"); } public static void Main() { DisposableExample de = new DisposableExample(); using (de) { Console.Out.WriteLine("Inside using."); } //the compiler puts: if(de != null) { de.Dispose(); } Console.Out.WriteLine("after using."); Console.In.ReadLine(); } } }
Produces:
Inside using. I'm being disposed! after using.
284.
285. /// <summary> 286. /// gets a property value from the Web.config file 287. /// The problem with just using System.Configuration.ConfigurationSettings.AppSettings 288. /// is that is doesn't work in standalone mode for unit testing e.g., nunit.cs 289. /// </summary> 290. /// <param name="property">property key name</param> 291. /// <returns></returns> 292. public static string getProperty(string property) { 293. string propValue = ""; 294. try { 295. if(System.Configuration.ConfigurationSettings.AppSetti ngs.Count == 0) { 296. // we are in standalone mode 297. XmlNodeList xmlNodeList = null; 298. if(appSettings == null) { 299. XmlDocument xmlDocument = new XmlDocument(); 300. //TODO: use the system environment or config methods instead 301. // of hardcoded path
302. xmlDocument.Load("c:/Inetpub/wwwroot/MyApplication 11/Web.config"); 303. xmlNodeList = 304. xmlDocument.SelectNodes("/configuration/appSetting s/add"); 305. if(verbose) { 306. Console.Write("xmlNodeList.Count = " + xmlNodeList.Count); 307. Console.Out.Flush(); 308. } 309. appSettings = new NameValueCollection(); 310. 311. foreach(XmlNode xmlNode in xmlNodeList) { 312. appSettings.Add( 313. xmlNode.Attributes.GetNamedItem("key").Value, 314. xmlNode.Attributes.GetNamedItem("value").Value ); 315. } 316. } 317. propValue = appSettings[property]; 318. } else { //we are in web mode 319. propValue = (string)System.Configuration.ConfigurationSettings.AppSettings[pr operty]; 320. } 321. } catch (Exception e) { 322. throw new Exception(Util.formatExceptionError("getProperty","getProperty:"+ property,e)); 323. } 324. return propValue; 325. } 326. 327.
328.
Use Reflection to print all the fields and their values in an object.
Often its convenient to print the state of an object. Instead of overriding the ToString() method and explicitly printing each field, you can let C# do the work for you with a little bit of Reflection. You could even add code to recursively print the state of the composition objects as well. This is left as an exercise for the student.
public override string ToString() { StringBuilder sb = new StringBuilder(); System.Type type = this.GetType(); sb.Append("\r\nInformation for "+type.Name); sb.Append("\r\nFields:"); System.Reflection.FieldInfo[] fi = type.GetFields(); foreach(FieldInfo f in fi) { sb.Append("\r\n "+f.ToString()+ " = \""+ f.GetValue(this) +"\""); } System.Reflection.PropertyInfo[] pi = type.GetProperties(); sb.Append("\r\nProperties:"); foreach(PropertyInfo p in pi) {
329.
330.
To import a new node into a DOM, we use the handy 'ImportNode()' method to avoid the 'not in document context' error.
using System.Xml; using System.Xml.XPath; ... //create initial DOM XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<TextDefinitions name='DataSource'></TextDefinitions>"); ... //add new node from xml text XmlDocument newXmlDocument = new XmlDocument(); newXmlDocument.LoadXml("<text lang='en-UK' name='exit'>Goodbye</text>"); XmlNode newNode = xmlDocument.ImportNode(newXmlDocument.DocumentElement,true); xmlDocument.DocumentElement.AppendChild(newNode);
331.
Example C# fragment:
using System.Xml; using System.Xml.XPath; ... //create initial DOM XmlDocument xmlDocument = new XmlDocument(); /// <TextDefinitions> /// <TextDefinition name="DefaultDemographicText"> /// <Text lang="en-UK">Thanks for taking our survey.</Text> /// <Text lang="fr-FR">Merci pour prendre notre apercu.</Text> /// </TextDefinition>
/// </TextDefinition> /// </TextDefinitions> xmlDocument.LoadXml("<TextDefinitions> <TextDefinition name='DefaultDemographicText'> <Text lang='en-UK'>Thanks for taking our survey.</Text> <Text lang='fr-FR'>Merci pour prendre notre apercu.</Text> </TextDefinition> <TextDefinition name='ExitText'> <Text lang='enUK'>Goodbye</Text> <Text lang='fr-FR'>Au revoir </Text> </TextDefinition></TextDefinitions>"); XPathNavigator xPathNavigator = xmlDocument.CreateNavigator(); ... private string GetTextFromDOM(string textName,string lang) { string query = "string(/TextDefinitions/TextDefinition[@name='"+textName+"']/Tex t[@lang = '"+lang+"'])"; string text = (string) xPathNavigator.Evaluate(query); if(verbose) { Util.write("GetTextFromDOM(\""+textName+"\", \""+lang+"\"): \"" +text+"\""); } return text; } }
332. How to return a single node using XPath expressions with the XmlDocument
333. public static Survey GetSurvey(string groupName, string surveyName) { 334. XmlDocument xmlSurveys = new XmlDocument(); 335. xmlSurveys.Load(filename); 336. XmlNode xmlNode = (XmlNode) xmlSurveys.SelectNodes("//Survey[@name='"+surveyName+"']").Item(0 ); 337. ... 338. } 339.
340.
The IComparable interface needs to be supported. Fortunately, its only one method, CompareTo(Object obj).
public class MyObject : ParentObject, IComparable { ... public int CompareTo(Object obj ) { MyObject myObject = (MyObject) obj; //priority is a double, which complicates matters, otherwise // return this.priority-myObject.priority works well if(this.priority > myObject.priority) { return 1; } else if(this.priority < myObject.priority) {
Then you can sort an ArrayList with "myObjectArrayList.Sort();" and C sharp will use your "CompareTo" method 341. Example of using Interfaces
As the following code shows, interfaces can be extended and, unlike classes, multiple interfaces can be extended
using System; //example of interfaces public class Animals { //simple interface interface IAnimal { void Breathes(); } //interfaces can inherent from other interfaces interface IMammal : IAnimal { int HairLength(); } //interfaces can implement other interfaces which implemented interfaces interface IMarsupial : IMammal { int PouchSize(); } //interfaces can implement many other interfaces interface IGonerMammal : IMammal, IExtinct { } interface IExtinct { int HowLongExtinct(); } //classes can implement multiple interfaces public class TasmanianTiger : IGonerMammal, IMarsupial { public int PouchSize() { return 2; } public int HowLongExtinct() { return 28; } public int HairLength() { return 4; } public void Breathes() { } } public static void Main(string[] args) { Console.Write("The Tasmanian Tiger has been extinct for {0} years", new TasmanianTiger().HowLongExtinct()); } }
342.
Randomize C# ArrayList
343.
344. Assembly assembly = Assembly.GetAssembly(this.GetType()); 345. Type[] types = assembly.GetTypes(); 346. foreach(Type type in types) { 347. write("type="+type); 348. }
349.
350. class MyClass() { 351. ... 352. 353. public class comparer: IComparer { 354. public comparer() {} 355. public int Compare(object obj1, object obj2) { 356. return obj1.GetType().ToString().CompareTo(obj2.GetType().ToString()); 357. } 358. } 359. ... 360. ArrayList arrayList = ... 361. arrayList.Sort(new comparer()); 362. ...
363.
364. 365.
or
string className = "MyType"; MyType myType = (MyType) Activator.CreateInstance(Type.GetType(className), new object[]{});
366.
Example of using an attribute to determine if the associated SQL code for this object should be autogenerated. The Attribute code:
using System; using System.Text; namespace MyApplication.Attributes { [AttributeUsage(AttributeTargets.Class, AllowMultiple=false)] public sealed class GenerateSQL : Attribute { public bool YesOrNo; public GenerateSQL(bool YesOrNo) { this.YesOrNo = YesOrNo; } } }
367.
368. public static void WriteStringToFile(string fileName, string contents) { 369. StreamWriter sWriter = null; 370. try { 371. FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write); 372. sWriter = new StreamWriter(fileStream); 373. sWriter.Write(contents); 374. } finally { 375. if(sWriter != null) { 376. sWriter.Close(); 377. } 378. } 379. } 380. public static void AppendStringToFile(string fileName, string contents) { 381. StreamWriter sWriter = null; 382. try { 383. FileStream fileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write); 384. sWriter = new StreamWriter(fileStream); 385. sWriter.Write(contents);
394.
Defining a web service is very easy. Add a reference to "System.Web.Services" in Visual Studio, add the "using System.Web.Services;" line in your code, subclass from "System.Web.Services.WebService" and finally put the "[WebMethod]" attribute on your method.
... using System.Web.Services; ... public class QuotaProxy : System.Web.Services.WebService { ... [WebMethod] public ArrayList GetSurveyStatus(string group, string lang, NameValueCollection DemographicResponses) { ... }
395.
Web Services
To create a WSDL file for a service, just append "?wsdl" to the service name inside IE
http://localhost/MyProject/Service1.asmx?wsdl
396.
Use the Wsdl.exe to read the WSDL document and create a wrapper class
c:> Wsdl.exe "http://localhost/MyProject/Service1.asmx?wsdl"
397.
398. 399. //this constructor takes a single xmlElement argument, converts it to a string, 400. //and calls the constructor that takes a string 401. public SurveyStatus(XmlElement xmlElement) : this(To.ToText(xmlElement)) {} 402. public SurveyStatus(string xmltext) { 403. ... 404. } 405.
406.
Global.asax Hooks
407.
Looking at an Assembly
Code to trip through an assembly and print all public instance methods
public void Coverage() { writeMethodStart("Coverage"); Assembly assembly = Assembly.LoadFrom("MyApplication.dll"); foreach(Module module in assembly.GetModules()) { write("loading module "+module); Type[] types = module.FindTypes(null,null); foreach(Type type in types) { write(" ** "+type); MemberInfo[] memberInfoArray = type.GetMethods(BindingFlags.Public|BindingFlags.Instance| BindingFlags.DeclaredOnly); foreach(MemberInfo memberInfo in memberInfoArray) { write(" "+memberInfo.Name+"()"); } } }
408.
From xprogramming.com: Mark your breakpoint in DevStudio and start the NUnit GUI. Inside DevStudio select "Debug/Process/nuit-gui.exe" then "Attach". A new window pops up, select "Common Language Runtime". Run the test inside the GUI and DevStudio will stop at the breakpoint (ok, well, it should stop there). 409.
410. /// <summary> 411. /// test of remoting 412. /// </summary> 413. [Test] 414. [Ignore("Service often is not started on remote machine")] 415. public void GetProjectList() { 416. writeMethodStart("GetProjectList"); 417. QPManager manager = new QPManager(); 418. string xml = manager.GetProjectList("Test1", "en-UK", "gender:male").ToXml(); 419. write("manager.GetProjectList:"+xml); 420. writeMethodEnd(); 421. }
422.
If this method throws an exception, it will pass the test. If it doesn't throw an exception, it will fail the test.
[Test, ExpectedException(typeof(Exception))] public void Get() { writeMethodStart(MethodInfo.GetCurrentMethod().ToString()); DatabaseObject.Get("IDontExist"); writeMethodEnd(); }
In later versions of NUnit you can use this syntax which is better
Assert.Throws<Exception>(() => new MyObject(badargument));
423.
Static Constructors
This constructor is only called once before the first object of this type is called. (Is it guarenteed to be called if no objects of its kind are never created?) It can only reference static objects of course and it has no parameters.
public class SDObjectRespondent : SDObject { public static DatabaseProxy databaseProxy = null; public SDObjectRespondent() {} public SDObjectRespondent(string xmlstring) : base(xmlstring) {} static SDObjectRespondent() { databaseProxy = new DatabaseProxy(Util.GetRequiredProperty("RespondentDatabase")); } }
424.
Since not all characters in strings map to a small friendly byte (remember our European friends?) the count of characters in strings does not equal the number of bytes. 425. Printing the name of the currently executing method
426.
It's a little trickier than just doing a foreach() loop because you will get a InvalidOperationException. Instead use a simple for loop with a decrementing counter and remove them off the end.
public void Remove(ArrayList surveyNamesToRemove) { if(surveyNamesToRemove == null || surveyNamesToRemove.Count == 0) { return; } for(int i=(surveyStatuses.Count-1); i>=0; i--) { if(surveyNamesToRemove.Contains(((SurveyStatus)surveyStatuses[i]) .GetName())) { surveyStatuses.RemoveAt(i); } } }
427.
428. int respondentSource = 1; 429. ... 430. switch(respondentSource) { 431. case 1: 432. respondent = new DynamicRespondent(group,lang); 433. break; 434. case 2: 435. respondent = Respondent.Get(iteration+1); 436. break; 437. case 3: 438. string xmlString = "<Respondent userID='2' />"; 439. respondent = new Respondent(xmlString); 440. break; 441. default: 442. throw new Exception("Invalid switch option \""+respondentSource+"\""); 443. } 444. ...
switch statement
445.
Environment.StackTrace
/// The Environment.StackTrace is also printed, since the usual stacktrace is /// truncated at times. /// </summary> /// <param name="e">thrown exception</param> /// <returns>string containing human readable exception</returns> public static string FormatException(Exception e){ StringBuilder sb = new StringBuilder(); sb.Append("\r\n *************** Exception ***************"); sb.Append("\r\ne.Message:\""+e.Message+"\""); sb.Append("\r\ne.StackTrace:\""+e.StackTrace+"\""); sb.Append("\r\ne.Source:\""+e.Source+"\""); sb.Append("\r\ne.TargetSite:\""+e.TargetSite+"\""); sb.Append("\r\nEnvironment.StackTrace:\""+Environment.StackTrace+ "\""); //recurse into inner exceptions if(e.InnerException != null) { sb.Append("\r\n *************** Inner ***************"); sb.Append(FormatException(e.InnerException)); } return sb.ToString(); }
446.
See also O'Reilly's Indroduction to Schemas, Microsoft's Roadmap for XML Schemas in the .NET Framework and IBM's Basics of using XML Schema.
/// <summary> /// validate an xml file to a schema /// </summary> /// <param name="xmlString">string representation of xml file</param> /// <param name="schemaString">string representation of schema</param> /// <returns>null if its happy, otherwise a string containing error messages</returns> public static string ValidateXML(string xmlString, string schemaString) { XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(xmlString)); XmlValidatingReader xmlValidatingReader = new XmlValidatingReader(xmlTextReader); xmlValidatingReader.ValidationType = ValidationType.Schema; XmlSchema xmlSchema = new XmlSchema(); xmlSchema = XmlSchema.Read(new StringReader(schemaString),null); xmlValidatingReader.Schemas.Add(xmlSchema); Validate validate = new Validate();
ValidationEventHandler validationEventHandler = new ValidationEventHandler(validate.Validator); xmlValidatingReader.ValidationEventHandler += validationEventHandler; while (xmlValidatingReader.Read()); return validate.errors; } /// <summary> /// tiny class so we can have a ValidationEventHandler and collect the errors /// </summary> private class Validate { public string errors = null; public void Validator(object sender, ValidationEventArgs args) { errors += args.Message + "\r\n"; } }
447.
448.
How to invoke a static method on a dynamic object. This invokes the static method "Get(string name)" on a "myType" class object and returns an instance of a MyObjectType.
using System.Reflection; ... string objectType = "myType"; //create an instance object MyObjectType objectTypeInstance = (MyObjectType)Activator.CreateInstance(Type.GetType(objectType), null); //invoke static method and return an object of MyObjectType MyObjectType myObjectType = (MyObjectType)objectTypeInstance.GetType().InvokeMember ("Get",BindingFlags.Default | BindingFlags.InvokeMethod,null,null,new object [] {name});
449.
This example shows invoking an instance method on the "this" object, although any other object would work as well as long as you get the methodInfo object from its class.
MethodInfo methodInfo = this.GetType().GetMethod("MyMethod"); if(methodInfo != null) { //invoke if method is really there methodInfo.Invoke(this,param); } ...
450.
Case-Insensitive Hashtable
451. With C#2.0 you should really use a type-safe Dictionary collection instead of hashtable most of the time. Here is an example of using a Dictionary with a Guid key and a Survey object as a value.
using System.Collections.Generic; ... private static Dictionary<Guid,Survey> surveyByIdDictionary = null; private static readonly object surveyByIdDictionaryLock = new object(); /// <summary> /// return Survey object based on id. /// If the id requested does not exist, a null is returned. /// </summary> /// <param name="id">guid of the survey of interest.</param> /// <returns>survey or null</returns> public static Survey GetById(Guid id) { if (surveyByIdDictionary == null) { lock (surveyByIdDictionaryLock) { if (surveyByIdDictionary == null) { surveyByIdDictionary = new Dictionary<Guid, Survey>(); foreach (string surveyName in Survey.Default.GetNames()) { Survey survey = Survey.Get(surveyName); Survey.surveyByIdDictionary.Add(survey.id, survey); } } } } return surveyByIdDictionary.ContainsKey(id) ? surveyByIdDictionary[id] : null; }
452.
455.
456. 458.
You can override the "[]" operator to return whatever you wish
/// <summary> /// indexer method to get SurveyStatus object by name /// </summary> public SurveyStatus this[ string surveyName] { get { foreach(SurveyStatus ss in surveyStatuses) { if(CaseInsensitiveComparer.Default.Compare(surveyName, ss.GetName()) == 0) { return ss; } } return null; } }
459.
IEnumerable Interface
The IEnumerable interface (.Net 2.0) implements only one method, "GetEnumerator()". This is an easy way to iterate over collections using foreach. The yield statement returns control to the calling routine and then picks up exactly
where it left off. This can be advantageous if creating the elements is expensive since you don't have to create them until called.
using System; using System.Collections; class DaysOfWeek { public class Days : IEnumerable { readonly string[] days = { "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Sa turday"}; public IEnumerator GetEnumerator() { for(int i=0;i<days.Length;i++) { yield return days[i]; } } } static void Main() { foreach (string day in new Days()) { Console.Write(day + " "); } Console.In.Read(); } }
460.
If you include the 'Application Name' in the connection string, the SQL profiler can show that to you. This makes db tuning easier.
<add key="DB1ConnectionString" value="Application Name=myAppName; Data Source=venus1; Trusted_Connection=yes; database=employees" />
461.
462. 463. 464. 465. 466. 467.
468.
469. [Test] 470. new public void GenerateVenues() { 471. writeMethodStart(MethodInfo.GetCurrentMethod().ToString()); 472. 473. XmlDocument xdoc = new XmlDocument(); 474. XmlElement root = xdoc.CreateElement("Schedule"); 475. xdoc.AppendChild(root); 476. XmlElement day = xdoc.CreateElement("Day"); 477. XmlAttribute date = xdoc.CreateAttribute("date"); 478. date.Value = "2004/01/01"; 479.
480. day.SetAttributeNode(date); 481. XmlAttribute num = xdoc.CreateAttribute("number"); 482. num.Value = "5"; 483. day.SetAttributeNode(num); 484. root.AppendChild(day); 485. 486. write(To.ToText(xdoc)); 487. writeMethodEnd(); 488. 489. } 490.
This produces:
<Schedule> <Day date="2004/01/01" number="5" /> </Schedule>
491.
Delegates
Delegates are a refinement of method pointers in C, but with safty built in. The delegate object is bound to an method that takes the exact number and type of variables are arguments and returns the correct type.
using System; public class DelegateTest { public static void PrintHello(string name) { Console.Write("Hello {0}!",name); } //define the MyPrinter type public delegate void MyPrinter(string s); public static void Main(string[] args) { //create an instance of MyPrinter delegate type MyPrinter myPrinter = new MyPrinter(PrintHello); myPrinter("Bill"); //invoke the delegate }
492.
493. 494. 495. 496. 497. 498. 499. 500. 501. 502.
503. } 504. public static string PrintHello(string name) { 505. Tick(5); 506. Console.Write("Hello {0}!",name); 507. Tick(5); 508. return name; 509. } 510. //define the MyPrinter type 511. public delegate string MyPrinter(string s); 512. 513. public static void Main(string[] args) { 514. //create an instance of MyPrinter delegate type 515. MyPrinter myPrinter = new MyPrinter(PrintHello); 516. IAsyncResult result = myPrinter.BeginInvoke("Bill",null,null); 517. myPrinter("Uma"); 518. string tmp = myPrinter.EndInvoke(result); 519. Console.Write("End of Program. Returned value was "+tmp); 520. } 521. 522. } 523.
524.
525. 526. using System; 527. using System.Runtime.Remoting.Messaging; 528. 529. //example of using Asynchronous Delegate calls with callback 530. public class DelegateTest 531. { 532. public static void MyCallback(IAsyncResult iaresult) { 533. AsyncResult result = (AsyncResult)iaresult; 534. MyPrinter myPrinter = (MyPrinter)result.AsyncDelegate; 535. Console.WriteLine("End of Program. Returned value was "+myPrinter.EndInvoke(iaresult)); 536. } 537. 538. private static void Tick(int count) { 539. for(int i=0;i<count;i++) { 540. System.Threading.Thread.Sleep(1000); 541. Console.Out.WriteLine("."); 542. Console.Out.Flush(); 543. } 544. } 545. public static string PrintHello(string name) { 546. Tick(5); 547. Console.Write("Hello {0}!",name); 548. Tick(5); 549. return name; 550. } 551. //define the MyPrinter type 552. public delegate string MyPrinter(string s); 553. 554. public static void Main(string[] args) { 555. //create an instance of MyPrinter delegate type 556. MyPrinter myPrinter = new MyPrinter(PrintHello);
557. IAsyncResult result = myPrinter.BeginInvoke("Bill",new AsyncCallback(MyCallback),null); 558. myPrinter("Uma"); 559. //string tmp = myPrinter.EndInvoke(result); 560. //Console.Write("End of Program. Returned value was "+tmp); 561. } 562. 563. } 564.
565.
566. /// <summary> 567. /// returns the keys of a hashtable in sorted order 568. /// </summary> 569. /// <param name="hashtable">unsorted type</param> 570. 571. /// <returns>sorted keys</returns> 572. public static ArrayList GetSortedKeys(Hashtable hashtable) { 573. ArrayList arrayList = new ArrayList(hashtable.Keys); 574. arrayList.Sort(); //why couldn't Sort() return 'this' pointer? 575. return arrayList; 576. } 577.
578.
"checked" keyword
Oddly enough, by default, C# does not throw an exception for numerical overflows or underflows. To have C# check, you must use the "check" keyword, or configure your project to check all arithmetic.
using System; //Example of using the "checked" keyword to catch over/under flows public class CheckedExample { public static void Main(string[] args) { int big = int.MaxValue - 1; int tooBig = big + 2; //overflow, but no error generated Console.WriteLine("big = {0}",big); Console.WriteLine("tooBig = {0}",tooBig); try { checked { tooBig = big + 2; //exception generated } } catch (OverflowException e) { Console.WriteLine(e.ToString()); } } }
tooBig = -2147483648 System.OverflowException: Arithmetic operation resulted in an overflow. at CheckedExample.Main(String[] args) in C:\home\mfincher\csharp\CheckedExample.cs:line 13
579.
580. using System; 581. //hokey example of using explicit conversion 582. public class Conversion 583. { 584. public class Circle { 585. public double x,y,r; 586. public Circle(double x, double y, double r) { 587. this.x = x; this.y = y; this.r = r; 588. } 589. } 590. 591. public class Square { 592. public double x,y,width; 593. public Square(double x, double y, double width) { 594. this.x = x; this.y = y; this.width = width; 595. } 596. public override string ToString() { 597. return String.Format("Square x={0} y={1} width={2}",x,y,width); 598. } 599. //show the object how to cast a circle to be a square 600. public static explicit operator Square(Circle circle) { 601. return new Square(circle.x,circle.y,circle.r); 602. } 603. } 604. 605. public static void Main(string[] args) { 606. Circle c = new Circle(1.0,1.0,2.0); 607. Square s = (Square)c; 608. Console.Write("Converted circle to square! "+s.ToString()); 609. } 610. } 611.
612.
Using the "out" or the "ref" parameter modifier will allow values to be returned.
using System; //Example showing use of ref and out method parameter modifiers public class RefOut { public void test(out string text) { text = "inside"; } public static void Main(string[] args) { RefOut refOut = new RefOut();
The results:
text=inside
What's the difference between "ref" and "out"? "ref" requires that an object is assigned before passing it to the method. "out" requires the method being called to assign a value the the variable. Example of using "ref"
using System; class RefMagic { private void Renamer(ref string name) { name = "Joe"; } static void Main() { string name = "Mike"; Console.Out.WriteLine("name = " + name); RefMagic refMagic = new RefMagic(); refMagic.Renamer(ref name); Console.Out.WriteLine("name = " + name); Console.In.Read(); } }
Produces:
name = Mike name = Joe
613.
Use the "params" modifier, which must be modifying the last argument.
using System; class MyDoodle { //example of passing a variable number of arguments to a method private static int Addem(params int[] myarray) { int sum = 0; foreach (int i in myarray) { sum = sum + i; } return sum; }
static void Main() { Console.Out.WriteLine("sum = " + Addem()); Console.Out.WriteLine("sum = " + Addem(1, 2)); Console.Out.WriteLine("sum = " + Addem(1, 2, 3, 4, 5, 6)); Console.In.Read(); }
614.
The results:
Looking Looking Looking Looking at at at at file file file file "C:\home\mfincher\csharp\Animals.cs" "C:\home\mfincher\csharp\AsyncDelegateTest.cs" "C:\home\mfincher\csharp\CheckedExample.cs" "C:\home\mfincher\csharp\Conversion.cs"
A caveat: DirectoryInfo.GetFiles will sometimes return more than you want. It will also return files whose extension has extra characters. Looking for "*.xml" will also yield "*.xmlabc" which can be, at the least, annoying.
foreach (var fileInfo in dirInfo.GetFiles("*.xml")) { if(fileInfo.Extension != ".xml") continue; //gets rid of "SDUS.xml~" using (var reader = new XmlTextReader(fileInfo.FullName)) ... }
615.
This launches an instance of the browser, waits 15 seconds and then closes it.
using System; using System.IO; using System.Diagnostics;
using System.Threading; public class Temp { /// <summary> /// Example of creating an external process and killing it /// </summary> public static void Main() { Process process = Process.Start("IExplore.exe","www.cnn.com"); Thread.Sleep(15000); try { process.Kill(); } catch {}
} }
616.
Using a Timer with a TimerCallback you can tell .Net to repeatedly invoke a method on a schedule. The code is a little verbose for instructional purposes.
using System; using System.Threading; public class RegistrarProxy { private static Timer _timer; private static readonly TimerCallback _timerCallback = timerDelegate; public void Init() { _timer = new Timer(_timerCallback, null, 0, 2000); //repeat every 2000 milliseconds } private static void timerDelegate(object state) { Console.WriteLine("timerDeletegate: "+DateTime.Now); } public static void Main() { RegistrarProxy rp = new RegistrarProxy(); rp.Init(); Console.In.Read(); //let's wait until the "return" key pressed } }
617.
The binary and SOAP formatters are more useful in most situations.
using System; using System.Xml;
using System.Xml.Serialization; using System.IO; public class SerializeExample { [Serializable] public class Employee { public string name; public int yearOfBirth; public Employee(string name, int yearOfBirth) { this.name = name; this.yearOfBirth = yearOfBirth; } public Employee() {} //needed for serialization } public static void Main(string[] args) { Console.Write("starting serialization..."); FileStream fileStream = File.Create("SerializeExample.xml"); XmlSerializer xmlSerializer = new XmlSerializer(typeof(Employee),"Employee"); xmlSerializer.Serialize(fileStream,new Employee("Achilles",1972)); fileStream.Close(); Console.Write("done."); } }
618.
By default dev studio creates a small file for you called "AssemblyInfo.cs". Inside are various assembly-level attributes. If you fill these in, then when the .dll is queried via a right mouse click and "Properties" selection, the information will appear in the dialog box.
[assembly: AssemblyCompany("Acme Enterprises")]
619.
620. 621. 622. 623. 624.
625. 626.
627.
The tertiary operator '?' has a friend, the '??' operator. If the value before the '??' is non-null, the value is returned. If the value is null, the value after the '??' is returned. The two statements below work identically.
s = (name != null) ? name : ""; s = name ?? ""; //returns "" if name is null, otherwise returns name
628.
2. Enter your name 3. <asp:TextBox Runat=server id=TextBox1 /> 4. <asp:RequiredFieldValidator ControlToValidate=TextBox1 5. Runat="server"> 6. You must supply a name. 7. </asp:RequiredFieldValidator>
18.
System.Web.UI.WebControls.DropDownList StatusDropDownList; 19. //...(add members) 20. StatusDropDownList.Items[StatusDropDownList.SelectedInd ex].Selected = 21. false; 22. StatusDropDownList.Items.FindByValue(surveyDescriptor.S tatus).Selected = 23. true;
24. To catch all the unhandled exceptions in a Page This will allow you to make sure all the errors encountered at the top level get logged.
private void Page_Error(object sender, System.EventArgs e) { Exception ep = Server.GetLastError(); LogFile.LogFatal(Util.FormatExceptionError("Page_Error","to p level error", ep,4)); //Server.ClearError(); //we don't clear, but let the system produce message }
29. How an application can be notified of changes to a file You can set a FileWatcher to invoke a callback whenever a file is changed by an external force.
using System; using System.IO; namespace DefaultNamespace { /// <summary> /// Description of Class1. /// </summary> public class FileWatcher { public FileWatcher()
{ } public static void Main() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(); fileSystemWatcher.Path = "C:\\spy"; fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite; fileSystemWatcher.Filter = "*.txt"; fileSystemWatcher.Changed += new FileSystemEventHandler(OnChanged); fileSystemWatcher.EnableRaisingEvents = true; Console.Write("Listening for changes in 'C:\\spy' directory...press any key to exit"); Console.Read(); } private static void OnChanged(object source, FileSystemEventArgs e) { Console.Write("\r\nFile: {0} {1} {2}", e.FullPath, e.ChangeType, DateTime.Now); } } }
30. How to write the name of a calling function. Use the handy StackTrace object as shown below. Note: the write() method is defined elsewhere.
... using System.Diagnostics; ... /// <summary> /// writes the name of the method that called it /// </summary> public void writeMethodStart() { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); MethodBase methodBase = stackFrame.GetMethod(); write("Method who called me was \""+methodBase.Name+"\""); }
/// <summary> /// returns the contents of the webpage whose url is passed in
34.
/// No error handling is done. If something goes wrong an exception is thrown even 35. /// something as simple as not being able to close the connection. 36. /// </summary> 37. /// <param name="link">url to get</param> 38. 39. /// <returns>string of web contents</returns> 40. private static string GetWebPage(string link) { 41. HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(link); 42. myRequest.Method = "GET"; 43. WebResponse webResponse = myRequest.GetResponse(); 44. StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8); 45. string contents = streamReader.ReadToEnd(); 46. streamReader.Close(); 47. webResponse.Close(); 48. return contents; 49. } 50.
51. To force .Net to use a proxy connection for web calls Add this to your web.config (inside the configuration element)
<system.net> <defaultProxy> <proxy proxyaddress = "10.33.19.14:80" bypassonlocal = "true" /> </defaultProxy> </system.net>
52. How to bypass System.Web.UI.Page and write directly to requestor This is very useful in returning raw xml for AJAX invocations.
using System; using System.Web; namespace RestDB { /// <summary> /// Example of using HttpHandler /// </summary> public class Rest : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.Write("<h1>Houston we have contact!</h1>"); } public bool IsReusable { get { return true; }
} }
53. How to write a gif to a browser request for an img tag This is useful when you need to know if a particular page has been viewed. Logic for recording the event is done elsewhere and then calls this routine.
/// <summary> /// writes a gif image to the browser and closes the response object /// </summary> /// <param name="response">where to write the gif</param> /// <param name="absolutePath">where to read the gif</param> public static void WriteGif(System.Web.HttpResponse response, string absolutePath) { //TODO: cache images in hashmap with filename the key FileStream fileStream; long length = 0; fileStream = new FileStream(absolutePath, FileMode.Open, FileAccess.Read); length = fileStream.Length; byte[] bBuffer = new byte[(int)length]; fileStream.Read(bBuffer, 0, (int)length); fileStream.Close(); response.ClearContent(); response.ContentType = "image/gif"; response.BinaryWrite(bBuffer); response.End(); }
54. Quick 'web service' call without the overhead If you only have a string to transmit between your server and client, you can cheat and use the "Response.StatusDescription" to pass a string message. In the Page_Load method of the server set the StatusDescription field of the Response object.
private void Page_Load(object sender, System.EventArgs e) { .... Response.StatusDescription = "my tiny bit of information to transmit"; ... }
In the client, invoke a url on the server and look at the "StatusDescription" field for your tiny bit of info.
string url = "http://...(your url goes here)......."; HttpWebResponse resp = (HttpWebResponse)WebRequest.Create(url).GetResponse(); string secretMessage = resp.StatusDescription;
55. How to add a javascript callback to an asp:checkbox. Unfortunately you can't simply add it in the HTML code. You have to go to the code behind page.
private void Page_Load(object sender, System.EventArgs e) { if(!this.IsPostBack) { this.myCheckBox.Attributes.Add("onclick","javascript:my Function()"); } }
if(Request.Cookies["ExtraUrlParamsTextBox"] != null) { ExtraUrlParamsTextBox.Text = Request.Cookies["ExtraUrlParamsTextBox"].Value; 62. } 63. 64. } 65. if(this.IsPostBack) { 66. Response.Cookies["ExtraUrlParamsTextBox"].Value = ExtraUrlParamsTextBox.Text; 67. } 68. }
81. Using standalone C# in an aspx page When a respondent is forwarded to this page, they are redirected to another page based on the value of "x" All their GET parameters are passed on as well. If x=ABCDE, then they are forwarded to ABCDE.html
<%@ Page Language="C#" %> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { string source = Page.Request.QueryString["x"]; if (string.IsNullOrEmpty(source)) { source = "XYZ"; //this is the default source if nothing is passed in as "x" param } Page.Response.Redirect(source + ".html?" + Page.Request.QueryString); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Redirect Page</title> </head> <body> </body> </html>
2. Misc Notes: 1. To view an assembly in gui using a tree structure use the handy Intermediate Language Disassembler (ildasm): c:\...\bin>ildasm myassemblyname.dll 2. Which data type should we use for money? The "decimal" struct gives 28 significant digits and may be used for most currency applications. Use the "m" suffix for constants.
const decimal interestRate = 0.02m; decimal interestEarned = customer.Amount*interestRate/365.25m;
3. Dotnetfx.exe If your target machine may not have .Net installed, you can install Dotnetfx.exe during your program's installation and Dotnetfx will install the .Net framework.
4. machine.config 'machine.config' control's the settings for ASP.Net. It is found in a directory like "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG". 5. To allow remote testing of web services For security reasons, only clients on the local host can access the web page version of a web service. To allow any client to access the service, put the following in the web.config inside the "system.web" element. This gets rid of the "The test form is only available for requests from the local machine." message.
<!-- to allow remote access to web services --> <webServices> <protocols> <add name="HttpSoap1.2"/> <add name="HttpSoap"/> <add name="HttpGet"/> <add name="HttpPost"/> </protocols> </webServices>
6. The Main method can take 3 forms: "static void Main()","static int Main()",or "static int Main(string[] args)" 7. Typical output: "System.Console.WriteLine("Howdy World!");" 8. In VS.NET, to get the docs on an object, highlight it and press 'F1' 9. To launch the Object Browser: View/Other Windows/Object Browser or Ctl-Alt-J 10. To add namespaces to the object browser, in the Solution Explorer, right click on the "References" tag and select "Add..." 11. Using an "@" in front of a string turns off escape substitutions, e.g.,, @"C:\" == "C:\\" 12. Three ways to initialize an array int [] a = new int[10]; a[0] = 1; a[1] = 2; int [] b = new int[] { 1, 2 }; int [] c = { 1, 2 }; 13. Our old friends, 'Preprocessor' commands, are available
14. 15. 16. 17. 18. 19. 20. #if (DEBUG) .... #endif
#warning remove next debug line from the code before release Console.Error.WriteLine("userID:"+userID+" : "+To.ToText(someObject));
21. The 'checked' and 'unchecked' operators are used to turn on and off arithmetic exceptions, e.g.,, int x = unchecked(a * b);
22. Enumerations
23. 24. enum Sizes {Tall, Grande, Venti}; //by default assigned to 0,1,2 25. enum Sizes {Tall=1, Grande=2, Venti=4}; // can be overridden 26. enum Sizes : byte {Tall, Grande, Venti}; //specify the size of the enum
Enums in C# are well developed and have many interesting methods. Enums derive from System.Enum which contain methods like Format() and GetName(). My favorite is ToString(). GetValues() will return all the possible values of an enum. 27. Struct Structures are similar to classes but do not have inheritance and, although created with the 'new' operator, they live on the stack. 28. "using" keyword Ambiguity with class names may be resolved by the "using" keyword.
using Set = MyUtil.Set;
This tells the compiler that all instances of 'Set' in the rest of the file are references to 'MyUtil.Set'. This would be helpful if 'Set' becomes a real collection class in a future release of .Net and you have coded your own. 29. "readonly" and "const" keywords
30. public const string myValue = "abc"; //myValue cannot be changed. Set at compile time. 31. public readonly string myFutureValue; //this can be set only once at declaration or in the constructor
const is set at compile time, and readonly at runtime. 32. "is" keyword tests to determine if an object is of a particular type
if(myShape is Circle) { ... }
33. "as" keyword similar to a type cast, but if the object is not what is expected, "as" returns a null while a type cast throws an exception.
34. "base" is similiar, but not identical to, Java's "super" to access a parent's members. 35. To read a double from a string: Console.Out.WriteLine("d = {0}",Double.Parse("1.02")); 36. Use "sealed" as a method modify so no subclass can extend the class ( like java's "final") 37. The Object class has four methods: ToString(), Equals(), GetHashCode(), and GetType(). The first two should be overridden. Example,
38. 39. public override string ToString() { return "I'm a Jet"; }
40. Member Accessibility 1. public - available to all code 2. protected - accessible only from derived classes 3. private - accessible only from within the immediate class 4. internal - accessible only from within the same assembly 5. protected internal - accessible only from within the same assembly or from classes extending classes from this assembly 41. Instead of using Java's "instanceof", C# uses the "is" operator. The "as" operator in C# is somewhat similar, but does more work. 3. Installing a Service via Nant Hate typing in username and passwords? Let Nant do the work for you
<target name="uninstall"> <echo message="uninstalling..." /> <exec program="installUtil.exe" basedir="C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727" workingdir="C:\workfiles\throttler\src\Harvester\bin\debug" commandline="/u Harvester.exe" failonerror="false" /> </target> <target name="install" depends="uninstall" > <echo message="installing..." /> <exec program="installUtil.exe" basedir="C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727" workingdir="C:\workfiles\throttler\src\Harvester\bin\debug" commandline="/user=mydomain\myuser /password=mypassword Harvester.exe" /> </target>
/// Sets the username and password for the service /// </summary> /// <param name="savedState"></param> protected override void OnBeforeInstall(IDictionary savedState) { base.OnBeforeInstall(savedState); this.serviceProcessInstaller1.Username = this.Context.Parameters["user"].ToString(); this.serviceProcessInstaller1.Password = this.Context.Parameters["password"].ToString(); this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.User;
4. Using Nullable Types In C# 2.0 we can use nullable types which are like regular objects but have a "HasValue()"
using System; class Nullable { static void Main() { int? i = null; Console.Out.WriteLine("i = " + i); Console.Out.WriteLine("i.HasValue=" + i.HasValue); i = 6; Console.Out.WriteLine("i = " + i); Console.Out.WriteLine("i.HasValue=" + i.HasValue); Console.In.Read(); } }
5. How to surpress warning with MSBuild With csc.exe it's easy to surpress warning with the "nowarn" option. With MSBuild it's a little trickier. Use the "property" switch and encluse your warning numbers with """, which is a little awkward.
<target name="compile"> <exec program="MSBuild.exe" basedir="${framework::get-frameworkdirectory(framework::get-target-framework())}" workingdir="$ {project::get-base-directory()}" commandline="MyProject.sln /verbosity:diag /p:Configuration=${string::to-upper(project.config)} /t:Clean;Rebuild /property:nowarn="1591,0618"" output="MyProjectMSBuild.txt" /> </target>
6. How to write a message to the Event Log This tiny helper function creates the entry and closes it. The "source" argument is the name of your application
... WriteMessage("MyProgram",e.ToString(),System.Diagnostics.EventLogEntryT ype.Error); ... private static void WriteMessage(string source, string message, System.Diagnostics.EventLogEntryType type) { System.Diagnostics.EventLog oEV = new System.Diagnostics.EventLog(); oEV.Source = source; oEV.WriteEntry(message, type); oEV.Close(); }
7. Using generics in a list. Our old friendly collection, ArrayList, is alas not in Generics. Instead we use the List collection.
using System.Collections.Generic; ... public List<XmlObject> GetChildren(string typeName) { List<XmlObject> list = new List<XmlObject>(); foreach (XmlObject xmlObject in Children) { if (xmlObject.GetType().ToString() == (NameSpace + typeName)) { list.Add(xmlObject); } } return list; }
8. Create your own generic class By adding "lt;T>" after the class you can create a Templated, or generic, version of your object, in this case a wrapper for cached items. We don't have to create a CachedItemString and a CachedItemInt.
using System; namespace PlayingAround { class Cacher<T> { public T CachedItem; public DateTime ExpirationDate; } class Runner { private static void Main() { Cacher<string> myString = new Cacher<string>(); myString.CachedItem = "old string"; Console.Out.WriteLine("myString.CachedItem = {0}", myString.CachedItem); Cacher<int> myInt = new Cacher<int>(); myInt.CachedItem = 6; Console.Out.WriteLine("myInt = {0}", myInt.CachedItem);
or
new System.IO.FileInfo(Assembly.GetCallingAssembly().Location).Directory.To String()
11. Examples of using Regular Expressions 1. Testing if each line in a data file conforms to a regular expression
2. private bool TestPanelistFile(TextWriter textWriter, string fileName) { 3. textWriter.WriteLine("Testing "+fileName); 4. StreamReader sr = new StreamReader(fileName); 5. //example line: 6. //"LUK09","g9002827491","DJH4W","Stopped By Signal","01/06/2006" 7. System.Text.RegularExpressions.Regex exp = 8. new System.Text.RegularExpressions.Regex( 9. "\"[a-zA-Z0-9]+\",\"[a-zA-Z0-9]+\",\"[a-zA-Z09]+\",\"(Completed Successfully|Stopped By Signal)\",\"\\d\\d/\\d\\d/\\d\\d\\d\\d\"" 10. ); 11. int i=0; 12. string line = ""; 13. while((line = sr.ReadLine()) != null) { 14. i++; 15. if( ! exp.IsMatch(line)) { 16. textWriter.WriteLine("\r\nError in input file on line "+i); 17. textWriter.WriteLine(" bad line: "+line); 18. } else { 19. if(i % 500 == 0) { textWriter.Write("."); } 20. } 21. } 22. return false; 23. } 24.
31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 46. 47.
/// </summary> /// <param name="cmd">sql string with '@' prefacing parameters</param> /// <returns>array like, {"name","lang"}</returns> private static string[] GetVariables(string cmd) { Regex rexp =new Regex("@[a-zA-Z0-9]+"); MatchCollection matches = rexp.Matches(cmd); string[] strings = new string[matches.Count]; for(int i=0;i<matches.Count;i++) { strings[i] = matches[i].ToString().Remove(0,1); } return strings; }
/// <summary> /// converts between the old style sql commands and parameterized. 48. /// changes '$(xyz)' to @xyz. e.g., "'$(name)'" returns "@name" 49. /// 50. /// </summary> 51. 52. /// <param name="cmd">string to translate</param> 53. /// <returns>string with updated params</returns> 54. public static string ReplaceWithParameterizedArgs(string cmd) { 55. Regex rexp = new Regex("'\\$\\(([a-zA-Z0-9]+)\\)'"); 56. # this replaces the entire match with the inner match only 57. string result = rexp.Replace(cmd, "@$1"); 58. return result; 59. } 60. 61. ... 62. 63. [Test] 64. public void ReplaceWithParameterizedArgs() { 65. writeMethodStart(MethodBase.GetCurrentMethod().ToString()); 66. Assert.AreEqual("@name @test", 67. Util.ReplaceWithParameterizedArgs("'$(name)' '$ (test)'")); 68. Assert.AreEqual("SELECT * FROM mytable where name = @name", 69. Util.ReplaceWithParameterizedArgs("SELECT * FROM mytable where name = '$(name)'")); 70. Assert.AreEqual("", Util.ReplaceWithParameterizedArgs("")); 71. }
72. Select a string This lifts the database name from a connection string.
string result="No Database found."; Regex pattern = new Regex(@"Database=(?<databaseName>\w+)", RegexOptions.IgnoreCase);
Match match = pattern.Match("Server=.; Integrated Security=SSPI; Database=T800; Application Name=Cyberdyne"); if (match.Success) { result = match.Groups["databaseName"].Value; }
73. Visual Studio Regular Expression Editing tips VS provides regular expressions in replacing string which can be a lifesaver. Here's a few examples of operations to be performed on many files: 1. Removing an xml attribute What the RE means: Find the string "<Survey " followed by a bunch of characters, followed by the string "cluster=" followed by a bunch of nonspace characters. Replace with just the "<Survey " and the characters before "cluster".
regex: to delete the attribute "cluster" from the "Survey" element: Find What: \<Survey {.*} cluster=[^ ]* Replace With: \<Survey \1
2. Rename an attribute In this case I want to rename the "Survey" element's 'id' attribute to 'registrarId', but not the other elements' 'id' attribute. The element name and the attribute to change must be on the same line for this to work. A tiny sliver of regular expression in the "Find and Replace" dialog did the trick: The "Find What" says find "<Survey " followed by any characters followed by " id=". The "\1" takes the value of all the characters skipped with the {.*}.
Find What: \<Survey {.*} id= Replace with: \<Survey \1 registrarId=
12. How to get the version number of your assembly? This will print the version set in Properties/AssemblyInfo.cs.
Console.WriteLine("version:"+Assembly.GetExecutingAssembly().GetName(). Version.ToString());
13. Finalize C# provides a way to release resources when an object dies. Like in C++, the destructor has the same name as the class with a "~" prefix.
using System; public class Destructo { ~Destructo() { Console.WriteLine("Help, I'm being destroye.#@@!@##"); } public static void Main(string[] args) { new Destructo(); new Destructo(); } }
This produces the following, but not reliably since the Console.Out may have been closed by then.
Help, I'm being destroye.#@@!@## Help, I'm being destroye.#@@!@##
14. CLSCompliant Using the CLSCompliant(true) attribute marks the assembly as being Common Language Specification compliant, so VB and other .Net languages can use your assembly. When compiling with this attribute, the compiler warns you with the error message CS3008 of non-compliant issues like exposed variable names differing only in case.
... using System.Xml; [assembly: CLSCompliant(true)] namespace MyComponents {
15. Using Regular Expressions in Visual Studio for Replacing text If you have lots of test xml files for creating objects and you need to add a new attribute, it's easy with regular expressions. For example, if you need to add "newattribute='1'" to all "Survey" elements scattered over many files like this one:
<Survey name='MoonManA' groupName='Baseline' priority='1' status='1' cellLimiter='100' surveyLimiter='100' dateStart='2004-01-10T08:00:00' dateEnd='2007-10-30T16:30:00' exclusions='0' cluster='Cluster1' >
Enter "control-h" to bring up the Replace dialogue box and select the "Use:" check box in the lower left corner and make sure it displays "Regular expressions". Then enter these:
"Find what:" \<Survey {[^\>]*}\> "Replace with:" <Survey \1newattribute='0'>
This will match all characters between "<Survey" and the ">". Putting the expression in braces allows you to use the "\1" syntax to place in the matched characters. The final result is
<Survey name='MoonManA' groupName='Baseline' priority='1' status='1' cellLimiter='100' surveyLimiter='100' dateStart='2004-01-10T08:00:00' dateEnd='2007-10-30T16:30:00' exclusions='0' cluster='Cluster1' newattribute='0' >
16. Delegates
Delegates are type-safe function pointers. In the old C# 1.0 days a delegate method had to have it's own declaration as a method like this:
// CalculateTax is a delegate that takes a double and returns a double public delegate double CalculateTax(double x); static public double StateTax(double x) { return x * 0.05; } static public double FederalTax(double x) { if (x > 1000.0) return x * 0.02; else return 0.0; } static void Main(string[] args) { CalculateTax stateDelegate = new CalculateTax(StateTax); CalculateTax federalDelegate = new CalculateTax(FederalTax); double amountOfPurchase = 12.99; Console.WriteLine("{0}", stateDelegate(amountOfPurchase)); Console.WriteLine("{0}", federalDelegate(amountOfPurchase)); Console.In.ReadLine(); }
17. Anonymous methods (C# 2.0) You can do the same as above with a cleaner look by using anonymous methods. We don't have to declare a real method, we can just inline it:
// CalculateTax is a delegate that takes a double and returns a double public delegate double CalculateTax(double x); static void Main(string[] args) { CalculateTax stateDelegate = delegate(double x) { return x * 0.05; }; CalculateTax federalDelegate = delegate(double x) { if (x > 1000.0) return x * 0.02; else return 0.0; }; double amountOfPurchase = 12.99; Console.WriteLine("{0}", stateDelegate(amountOfPurchase)); Console.WriteLine("{0}", federalDelegate(amountOfPurchase)); } Console.In.ReadLine();
19. My favorite C# links: 1. OpenSource C# projects. 2. web security (not directly a C# issue, but important). 3. ORMapper.com a sneak peak at ObjectSpaces, except this one works now. 4. Microsoft's list of dotnet and csharp tools. 5. weblogs.asp.net the heavy weights of .Net. 6. msdn c# site. 7. codeproject's list of code snippets and discussions . 8. dotnetforums. 9. Testing with NUnit. 10. builder.com.com notes on strong naming and microsoft's note on how to fix "Assembly Generation Failed" Error Message When You Try to Build a Managed DLL Without a Strong Name 11. zip library 12. a logging library 13. http://www.developer.com/net/net/article.php/1756211 14. CodeDOM a language independent code writer. 15. http://nunit.org for version 2.0 16. mantrotech 17. Sisyphus Persistence Framework 18. http://groups.msn.com/dotnetpersistence 19. list of UML Modeling Tools 20. www.gotdotnet.com/ 21. Austin .Net Users Group (2nd Monday of the month) and the Austin special interest which meets the following Wednesday at Catapult. 22. Nunit overview for Junit users 23. How to create a "servlet" in csharp 24. Wonderful conversion document from java syntax to C# 25. http://www.csharp-station.com/Tutorials/Lesson01.aspx 26. nunit a JUnit clone, a must for testing. 27. net-language csharp code examples 28. Comparison with Java 29. Oreillynet.com on C# 30. Download 131 Meg SDK for .Net. 31. http://msdn.microsoft.com intro with c# 32. http://www.csharp-station.com/ 33. http://www.learn-c-sharp.com
34. ecma specification for C# and the 5 components of CLI including the C#
language itself
35. c-sharpcorner.com 36. Comparison with Java 37. http://www.csharphelp.com/ 38. XML and C Sharp 39. www.sqlxml.org
20. ASP.NET notes Types of files 1. 2. 3. 4. 5. .aspx.cs - web forms, like jsp pages .ascx.cs - c# code objects .asmx - web services .asax - global objects .ashx - http modules
Three types of controls 6. HTML server controls 7. Web server controls 8. Validation 21. Notes on .NET. The Common Language Infrastructure (CLI) consists of 5 parts 1. Partition I - Architecture 1. Common Lanugage Specification (CLS) rules that guarantee one language can interoperate with others if it follows the specification 2. Common Type System (CTS) Type 1. Value Types 1. Built-in Value Types 1. Integer Types 2. Floating Point Types 3. Typed References 2. User Defined 1. Enums 3. Virtual Execution System (VES) Partition II - Metadata Partition III - Common Intermediate Language (CIL) bytecode Partition IV - Library Partition V - Annexes
2. 3. 4. 5.