1. Cryptographic errors are usually a missing snk file – look in AssemblyInfo.cs to find out where it should be.
March 12, 2008
March 10, 2008
Visual Studio Go Faster Techniques
The trick of the year supplied by Paul is to drag code from your active cs (or vb) page into the Toolbox sidebar. This is far better than using the snippets feature that VS supplies yet, as far as I can see, is not a widely known super feature.
The snippets seemed great when VS was released (just right click on a coding surface and select one) but having your superior custom code available in the Toolbox is the bees knees.
Another performance trick (if somewhat obvious) is to add debug and view windows as tabs at the bottom of the development page. For example:
- Immediates Window
Call Stack
Breakpoints
Pending Checkins
Watch1
FindResults1
To achieve this in VS2005+, right click on each window to make them dockable then drag the window down to the bottom status bar. Use Auto Hide to keep tidy.
Here is a way to speed things up by using shortcut keys.
February 19, 2008
PopulateHTMLTable()
public void PopulateHTMLTable()
{
int numrows = 5;
int numcells = 7;
for (int j = 0; j < numrows – 1; j++)
{
HtmlTableRow r = new HtmlTableRow();
for (int i = 0; i < numcells – 1; i++)
{
HtmlTableCell c = new HtmlTableCell();
c.InnerHtml = “Created from” + Environment.NewLine + “code behind”;
//c.Controls.Add(new LiteralControl(”row ” + j.ToString() + “, cell ” + i.ToString()));
r.Cells.Add(c);
}
this.Table1.Rows.Add(r);
}
}
C# Generic Lists
using System;
using System.Collections.Generic;
using System.Text;
namespace Utilities
{
class GenericList
{
public GenericList()
{
List<Person> people = new List<Person>();
people.Add(new Person(50, “Fred”));
people.Add(new Person(30, “John”));
people.Add(new Person(26, “Andrew”));
people.Add(new Person(24, “Xavier”));
people.Add(new Person(5, “Mark”));
people.Add(new Person(6, “Cameron”));
// Unsorted list
people.ForEach(delegate(Person p)
{
Console.WriteLine(String.Format(“{0} {1}”, p.age, p.name));
});
// Find
List<Person> young = people.FindAll(delegate(Person p)
{
return p.age < 25;
});
young.ForEach(delegate(Person p)
{
Console.WriteLine(String.Format(“{0} {1}”, p.age, p.name));
});
// Sort by name
people.Sort(delegate(Person p1, Person p2)
{
return p1.name.CompareTo(p2.name);
});
people.ForEach(delegate(Person p)
{
Console.WriteLine(String.Format(“{0} {1}”, p.age, p.name));
});
// Sort by age
people.Sort(delegate(Person p1, Person p2)
{
return p1.age.CompareTo(p2.age);
});
Console.WriteLine(“Sorted list, by age”);
people.ForEach(delegate(Person p)
{
Console.WriteLine(String.Format(“{0} {1}”, p.age, p.name));
});
}
}
public class Person
{
public int age;
public string name;
public Person(int age, string name)
{
this.age = age;
this.name = name;
}
}
}
C# Enums
using System;
using System.ComponentModel;
using System.Diagnostics;
public class EnumFunctions
{
public enum MyEnum : int
{
alfa = 1,
beta = 2,
gamma = 3
}
public enum ProjectTypes
{
Unknown = 0,
Closing = 1,
Generic = 2,
Listing = 3,
Buying = 4
}
enum Color
{
Green,
Yellow,
Red
}
public EnumFunctions()
{
//How to retrieve an Enum member given its integer value
//To retrieve an Enum member given its integer value, cast the integer value to your Enum type:
MyEnum MyEnumVal;
int i;
// Retrieve an enum member by its value
i = 2;
MyEnumVal = (MyEnum)i;
Debug.WriteLine(MyEnumVal.ToString());
// If the specified value is not an enum member, MyEnumVal receives the value anyway
i = 4;
MyEnumVal = (MyEnum)i;
Debug.WriteLine(MyEnumVal.ToString()); // The output is “4″
// Test for allowed enum values
if (!MyEnum.IsDefined(typeof(MyEnum), 4))
Debug.WriteLine(“The value of 4 is not defined in the Enum”);
//How to retrieve an Enum member given its name
//To retrieve an Enum member given its name, use the ConvertFrom() method of the
//TypeConverter class and cast the result to your Enum type:
MyEnumVal = (MyEnum) TypeDescriptor.GetConverter(MyEnumVal).ConvertFrom(“gamma”);
Debug.WriteLine(MyEnumVal.ToString()); // The output is “gamma”
// or
MyEnumVal = (MyEnum) Enum.Parse(typeof(MyEnum), “gamma”);
Debug.WriteLine(MyEnumVal.ToString()); // The output is “gamma”
//Using Enums
switch ((ProjectTypes)Convert.ToInt32(projectTypeID))
{
case ProjectTypes.Buying:
break;
case ProjectTypes.Closing:
break;
case ProjectTypes.Generic:
break;
case ProjectTypes.Listing:
break;
case ProjectTypes.Unknown:
break;
default:
break;
}
// or
ProjectTypes projectType = (ProjectTypes)Enum.Parse(typeof(ProjectTypes), projectTypeID)
// or cast from int to enum like
ProjectTypes pType = (ProjectTypes ) intStatus;
switch (pType)
{
case ProjectTypes.Buying:
fileType = “Buying”;
break;
case ProjectTypes.Closing:
fileType = “Closing”;
break;
//…
default:
break;
}
//C# / CSharp Tutorial » Data Type » enum base type
//Convert enum to int
Color t1 = Color.Green;
Color t2 = Color.Yellow;
Color t3 = Color.Red;
Console.WriteLine(“{0},\t{1}”, t1, (int)t1);
Console.WriteLine(“{0},\t{1}”, t2, (int)t2);
Console.WriteLine(“{0},\t{1}\n”, t3, (int)t3);
}
}
C# Arrays
using System;
using System.ComponentModel;
using System.Diagnostics;
/// <summary>
/// Summary description for Class1
/// </summary>
public class Class1
{
/*********************************************************************
* Quick Pastes:
*********************************************************************/
#region private members
#region public properties
#region constructors
#region private methods
#region public methods
#region properties
/*********************************************************************
* Array Methods:
* BinarySearch GetLength IsFixedSize Rank
* Clear GetLowerBound IsReadOnly Reverse
* Copy GetUpperBound IsSynchronized SetValue
* CreateInstance IndexOf LastIndexOf Sort
* GetEnumerator Initialize Length SyncRoot
* // http://en.csharp-online.net/index.php?title=CSharp_Code_Snippets
*********************************************************************/
private void Arrays() {
int i;
int[] a;
int[] b = new int[20]; // elements initialize to null
int[,] c;
int[,] d = new int[10,20];
int[] primes = {2, 3, 5, 7, 11, 13, 17,};
a = new int[10];
System.Array.Copy(primes, 0, a, 0, 2);
for (i = 0; i < a.Length; i++) a[i] = i;
foreach (int j in a) a[j] = j;
int[][] e = new int[10][]; // multidimensional arrays do not have to be rectangular
for (i = 0; i < e.Length; i++) e[i] = new int[i+1];
}
/*********************************************************************
* Array Reverse:
*********************************************************************/
public string Reverse(string x)
{
char[] charArray = new char[x.Length];
int len = x.Length – 1;
for (int i = 0; i <= len; i++)
charArray[i] = x[len-i];
return new string(charArray);
}
public string Reverse( string x )
{
char[] charArray = x.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
// http://en.csharp-online.net/index.php?title=CSharp_Code_Snippets
private void ReverseArray(string[] arr)
{
string[] strings = {“beta”, “alpha”, “gamma”};
Array.Reverse (strings); // Reverse element order
foreach (object o in strings)
{
Console.Write (“{0} “, o);
}
}
/*********************************************************************
* Array Copy:
*********************************************************************/
private void CopyArray(string[] arr)
{
int[] integers = new int[] { 5, 10, 15 };
double[] doubles = new double[3];
Array.Copy(integers, doubles, 2);
foreach (int integer in integers)
{
Console.Write(“{0,3}”, integer);
}
foreach (double duble in doubles)
{
Console.Write(“{0,3}”, duble);
}
}
/*********************************************************************
* Array Sort:
*********************************************************************/
private static void SortArray(string[] arr)
{
string[] strings = { “beta”, “alpha”, “gamma” };
Array.Sort(strings); // Sort elements
foreach (object o in strings)
{
Console.Write(“{0} “, o);
}
}
private void FindCommonValues()
{
object[] objects = { 1, 2, 4, 8 };
DisplayMatches(objects, new object[] { 0, 1, 5, 8 });
string[] strings = { “one”, “two”, “four”, “eight” };
DisplayMatches(strings,
new string[] { “zero”, “one”, “five”, “eight” });
}
private void DisplayMatches(IList iList, object[] objects)
{
foreach (object o in objects)
{
if (iList.Contains(o))
{
Console.WriteLine(“iList contains {0}”, o);
}
}
}
/*********************************************************************
* Array Load:
*********************************************************************/
int[] numbers;
private void SingleDimArrayApp()
{
numbers = new int[6];
for (int i = 0; i < 6; i++)
{
numbers[i] = i * i;
}
}
protected void PrintArray()
{
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(“numbers[{0}]={1}”, i, numbers[i]);
}
}
int range1 = 10;
int range2 = 20;
double[,] sales;
private void MultiDimArrayApp()
{
sales = new double[range1, range2];
for (int i = 0; i < sales.GetLength(0); i++)
{
for (int j = 0; j < sales.GetLength(1); j++)
{
// put a value in the array location
sales[i,j] = (i * 1) + j;
}
}
PrintSales();
}
private void PrintSales()
{
for (int i = 0; i < sales.GetLength(0); i++)
{
for (int j = 0; j < sales.GetLength(1); j++)
{
Console.WriteLine(“[{0}][{1}]={2}”, i, j, sales[i,j]);
}
}
}
//Fill an array with prime numbers
private void CreatePrimeNumbers()
{
const int UPPER_LIMIT = 1000;
int primes = 0;
BitArray candidates = new BitArray(UPPER_LIMIT, true);
for (int i = 2; i < UPPER_LIMIT; i++)
{
if (candidates[i])
{
for (int j = i * 2; j < UPPER_LIMIT; j += i)
{
candidates[j] = false;
}
}
}
// write them out
for (int i = 1; i < UPPER_LIMIT; i++)
{
if (candidates[i])
{
primes++;
Console.Out.WriteLine (i);
}
}
Console.Out.WriteLine(“\n” + primes + ” primes found in the range 2-” + UPPER_LIMIT);
}
/*********************************************************************
* Generic List from Array:
*********************************************************************/
/// <summary>
/// List list = GetGenericListFromArray(arr);
/// </summary>
/// <typeparam name=”T”></typeparam>
/// <param name=”items”></param>
/// <returns></returns>
private List<T> GetGenericListFromArray<T>(object[] items)
{
List<T> list = new List<T>();
for (int i = 0; i < items.Length; i++)
{
list.Add((T)items[i]);
}
return list;
}
/*********************************************************************
* Enums:
*********************************************************************/
enum Planets
{ // base type is int
Mercury, // default value 0
Venus,
Earth,
Mars,
Jupiter,
Saturn,
Uranus,
Neptune,
Pluto
}
enum Moons : short
{ // base type is short
Mercury = 0,
Venus = 0,
Earth = 1,
Mars = 2,
Jupiter = 16,
Saturn = 18,
Uranus = 15,
Neptune = 8,
Pluto = 1
}
private static void EnumExample()
{
Moons moonType = Moons.Neptune;
int integer = (int)Moons.Uranus;
Console.WriteLine(“moonType is {0}.”, moonType);
Console.WriteLine(“test is {0}.”, integer);
Console.WriteLine(“The planet {0} has {1} moons.”, Planets.Jupiter, (short)Moons.Jupiter);
}
/*********************************************************************
* Conversions:
*********************************************************************/
// instance variables (properties) default to 0, false, or null
//Convert to Fahrenheit
private double CelsiusToFahrenheit(string temperatureCelsius)
{
double celsius = Double.Parse (temperatureCelsius);
return (celsius * 9 / 5) + 32;
}
//Convert to Celsius
private double FahrenheitToCelsius(string temperatureFahrenheit)
{
double fahrenheit = Double.Parse (temperatureFahrenheit);
return (fahrenheit – 32) * 5 / 9;
}
/*********************************************************************
* Elasped Time:
*********************************************************************/
private void ElapsedTime()
{
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 1; i < 1000000; i++) { } // Execute the task to be timed
watch.Stop();
Console.WriteLine(“Elapsed: {0}”, watch.Elapsed);
Console.WriteLine(“In milliseconds: {0}”, watch.ElapsedMilliseconds);
Console.WriteLine(“In seconds: {0}”, (long) watch.ElapsedMilliseconds / 1000);
Console.WriteLine(“In timer ticks: {0}”, watch.ElapsedTicks);
}
/*********************************************************************
* Date and Time:
*********************************************************************/
private void DatesAndTimes()
{
DateTime dateTime = DateTime.Now;
Console.WriteLine (“d = {0:d}”, dateTime ); // mm/dd/yyyy
Console.WriteLine (“D = {0:D}”, dateTime ); // month dd, yyyy
Console.WriteLine (“f = {0:f}”, dateTime ); // day, month dd, yyyy hh:mm
Console.WriteLine (“F = {0:F}”, dateTime ); // day, month dd, yyyy HH:mm:ss AM/PM
Console.WriteLine (“g = {0:g}”, dateTime ); // mm/dd/yyyy HH:mm
Console.WriteLine (“G = {0:G}”, dateTime ); // mm/dd/yyyy hh:mm:ss
Console.WriteLine (“M = {0:M}”, dateTime ); // month dd
Console.WriteLine (“R = {0:R}”, dateTime ); // ddd Month yyyy hh:mm:ss GMT
Console.WriteLine (“s = {0:s}”, dateTime ); // yyyy-mm-dd hh:mm:ss (Sortable)
Console.WriteLine (“t = {0:t}”, dateTime ); // hh:mm AM/PM
Console.WriteLine (“T = {0:T}”, dateTime ); // hh:mm:ss AM/PM
Console.WriteLine (“u = {0:u}”, dateTime ); // yyyy-mm-dd hh:mm:ss (Sortable)
Console.WriteLine (“U = {0:U}”, dateTime ); // day, month dd, yyyy hh:mm:ss AM/PM
Console.WriteLine (“Y = {0:Y}”, dateTime ); // month, yyyy (March, 2006)
Console.WriteLine (“Month = “ + dateTime.Month); // month number (3)
Console.WriteLine (“Day Of Week = “ + dateTime.DayOfWeek); // day of week name (Friday)
Console.WriteLine (“Time Of Day = “ + dateTime.TimeOfDay); // 24 hour time (16:12:11)
Console.WriteLine(“DateTime.Ticks = “ + dateTime.Ticks); // (632769991310000000)
// Ticks are the number of 100 nanosecond intervals since 01/01/0001 12:00am
// Ticks are useful in elapsed time measurement.
}
/*********************************************************************
* Validation:
*********************************************************************/
private bool IsValidGuid(string guidCandidate)
{
if (!string.IsNullOrEmpty(guidCandidate))
{
Regex rx = new Regex(@”^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$”);
return rx.IsMatch(guidCandidate);
}
return false;
}
// Check if string is all numbers
private bool AllNumeric(string inputString)
{
const string ALL_NUMERIC = “[a-z|A-Z]“;
const string ALL_CAPS = “[a-z]“;
Regex AllNumericRegex = new Regex(ALL_NUMERIC);
if (AllNumericRegex.IsMatch(inputString))
{
return false;
}
return true;
}
// Check if string is all a specific type of number
// Test for an integer:
// isNumeric(“42000″, System.Globalization.NumberStyles.Integer)
// Test for an integer separated with commas:
// isNumeric(“42,000″, System.Globalization.NumberStyles.Integer | System.Globalization.NumberStyles.AllowThousands)
public bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle)
{
Double result;
return Double.TryParse(val, NumberStyle, System.Globalization.CultureInfo.CurrentCulture, out result);
}
if ( ! isNumeric(this.txtBestGuess.Text, System.Globalization.NumberStyles.Integer))
{
string str = “Your entry needs to be a number: “;
MessageBox.Show(str);
return;
}
try
{
bestGuess = Convert.ToInt32(this.txtBestGuess.Text);
}
catch (Exception ex)
{
string str = “Your entry could not be converted to a number: “;
MessageBox.Show(str + ex.Message);
}
/*********************************************************************
* App.Config:
*********************************************************************/
<appSettings>
<!–<add key=“DataStore” value=“Xml”/>–>
<add key=“DataStore” value=“SQLServer2005″/>
</appSettings>
//Need to add a Reference the Configuration
using System.Configuration;
// Get setting
private static string DataStore = ConfigurationManager.AppSettings["DataStore"];
private static string ConnectionString = ConfigurationManager.ConnectionStrings["SQLConnString"].ConnectionString;
public void AddSetting(string SettingName, string SettingValue)
{
// Open app.config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add setting.
config.AppSettings.Settings.Add(SettingName, SettingValue);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(“appSettings”);
}
public void ChangeSetting(string SettingName, string SettingValue)
{
// Open app.config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Chnage the Application Setting.
config.AppSettings.Settings["DataStore"].Value = “XML”;
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection(“appSettings”);
}
/*********************************************************************
* Parameter List:
*********************************************************************/
/// Use the params keyword to implement a method
/// e.g. ListArguments (“Arguments: “, DateTime.Now, 3.14f);
private void ListArguments(params object[] arguments)
{
foreach (object argument in arguments)
{
Console.WriteLine(argument);
}
}
public static void Main()
{
double a = 1;
int b = 2;
int c = 3;
int d = totalIgnoreFirst(a, b, c);
}
public static int totalIgnoreFirst(double a, params int[] intArr)
{
int sum = 0;
for (int i=0; i < intArr.Length; i++)
sum += intArr[i];
return sum;
}
/*********************************************************************
* Out Parameters :
*********************************************************************/
public static void Main()
{
bool b;
int c = change(5, out b);
}
public static int change (int a, out bool b)
{
b=false;
if (a>0)
b=true;
return (2*a);
}
/*********************************************************************
* Passing by reference:
*********************************************************************/
public static void Main()
{
int a = 0;
change(ref a); // following this method invocation, a==5
}
public static void change (ref int b)
{
b = 5;
}
/*********************************************************************
* Methods:
*********************************************************************/
private void Functions() {
int i = Factorial(5);
int a = 0;
int b = 0;
int c;
int d = Parms(a, ref b, out c);
i = Max(5, 3);
double x = Max(5.0, 3.0);
VarArgs(1,2,3);
}
private int Factorial(int n) { // methods must always specify a return value (can be void)
if (n == 1) {
return (1);
} else {
return (n * Factorial(n-1));
}
}
static int SFactorial(int n) { // static methods belong to class – can be called with no instance
if (n == 1) {
return (1); // static methods are implicitly final – no override allowed
} else {
return (n * SFactorial(n-1));
}
}
private int Parms(int x, ref int y, out int z) {
x = 1; // x = by value
y = 2; // y = by reference
z = 3; // z = output only
return 4;
}
private void VarArgs(params int[] x) { // params keyword allows var arg type calls VarArgs(1,2,3);
}
/*********************************************************************
* Method Overloading:
*********************************************************************/
private int Max(int a, int b) { // method overloading is resolved at compile time
if (a >= b) { // method of derived class always overrides – no matter how accessed
return a; // all function parameters are passed by value
} else {
return b;
}
}
private double Max(double a, double b) {
if (a >= b) {
return a;
} else {
return b;
}
}
/*********************************************************************
* Object Methods:
* Equals GetType MemberwiseClone ToString
* GetHashCode Finalize ReferenceEquals
*********************************************************************/
private void Objects() {
Object x = new Rational(1,2);
Object y = new Rational(1,2);
bool b = x.Equals(y);
}
/*********************************************************************
* String Methods:
* Chars Empty LastIndexOf ToCharArray
* Clone EndsWith Length ToLower
* Compare Equals PadLeft ToUpper
* CompareOrdinal Format ParRight Trim
* CompareTo Insert Remove TrimEnd
* Concat Intern Split TrimStart
* Copy IsInterned StartsWith
* CopyTo Join Substring
*********************************************************************/
private void Strings() {
string a = “Hello World”;
string b = @”\Hello World”; // literal string – no escape
int i = string.Compare(a, b);
i = string.Compare(a, b, true); // case insensitive
string s = string.Concat(a, b); // join strings
s = string.Copy(a);
i = a.Length;
char c = a[2];
bool f = a.EndsWith(“World”);
i = a.IndexOf(“World”);
i = a.LastIndexOf(“o”);
s = a.Insert(5, “fred”);
s = a.Substring(5);
s = a.Substring(0, 5);
char[] delimiters = {‘ ‘, ‘,’, ‘;’};
string[] xs = a.Split(delimiters);
s = String.Format(“{0,5:0.0}”, 1); // {ParamIndex[,MinWidth][:FormatString]}
System.Console.WriteLine(s);
Console.WriteLine(“Got {0} elements in UserInfoCollection”, userList.GetType().ToString());
}
/*********************************************************************
* StringBuilder Methods:
* Append Chars Length Remove
* AppendFormat EnsureCapacity MaxCapacity Replace
* Capacity Insert
*********************************************************************/
private void StringBuilders() {
System.Text.StringBuilder s = new System.Text.StringBuilder(“”);
s.Append(“abc”);
s.AppendFormat(“{0}{1}{2}”, “d”, “e”, “f”);
}
/*********************************************************************
* Regex Methods:
*********************************************************************/
private void RegEx() {
string s = “One,Two,Three Liberty Associates, Inc.”;
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(” |, |,”);
re.Split(s);
foreach (string a in re.Split(s)) {
System.Console.WriteLine(a);
}
}
/*********************************************************************
* Indexers:
*********************************************************************/
private void Indexers() {
Indexer indx = new Indexer();
indx.Add(“a”);
indx.Add(“b”);
for (int j = 0; j < indx.GetNumEntries(); j++) {
System.Console.WriteLine(indx[j]);
}
}
class Indexer {
private string[] s = new string[256];
private int i = 0;
public void Add(string a) {
s[i++] = a;
}
public string this[int index] {
get {
if ((index < 0) || (index >= s.Length)) {
// handle bad index
}
return s[index];
}
set {
if (index >= i) {
// add only through add method
} else {
s[index] = value;
}
}
}
public int GetNumEntries() {
return i;
}
}
/*********************************************************************
* Collection Classes:
*********************************************************************/
private void Collect() {
// ArrayList – dynamically sized array
System.Collections.ArrayList a = new System.Collections.ArrayList();
a.Add(“Fred”);
a.Add(“Hank”);
a.Sort();
foreach (string x in a) System.Console.WriteLine(x);
// BitArray – dynamically sized boolean array
System.Collections.BitArray b = new System.Collections.BitArray(0);
b.Length = 2;
b[1] = true;
b.Xor(b);
// HashTable – dictionary
System.Collections.Hashtable d = new System.Collections.Hashtable();
d["ab"] = 1;
d["cd"] = 2;
int i = (int)d["ab"];
// SortedList – sorted dictionary
System.Collections.Hashtable e = new System.Collections.Hashtable();
e["ab"] = 1;
e["cd"] = 2;
i = (int)e["ab"];
// Queue – fifo
System.Collections.Queue q = new System.Collections.Queue();
q.Enqueue(1);
q.Enqueue(2);
i = (int)q.Dequeue();
i = (int)q.Dequeue();
// Stack – lifo
System.Collections.Stack s = new System.Collections.Stack();
s.Push(1);
s.Push(2);
i = (int)s.Pop();
i = (int)s.Pop();
// StringCollection
System.Collections.Specialized.StringCollection c = new System.Collections.Specialized.StringCollection();
c.Add(“abc”);
c.Add(“def”);
}
/*********************************************************************
* XML – Serialize:
*********************************************************************/
/// <summary>
/// Serialization – Writes the XML to disk.
/// </summary>
public void SaveXmlToDisk(UserList userList)
{
if (userList == null || userList.Count < 1 )
{
throw new ArgumentException(“The collection must contain data”);
}
try
{
if (File.Exists(xmlFile))
{
File.Delete(xmlFile);
}
}
catch (IOException)
{
throw;
}
XmlSerializer xser = new XmlSerializer(userList.GetType());
using (TextWriter writer = new StreamWriter(xmlFile))
{
// serialize without the default namespace
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(“”, “”);
xser.Serialize(writer, userList, ns);
}
}
/*********************************************************************
* XML – Deserialize:
*********************************************************************/
/// <summary>
/// Deserialization – Reads the XML from disk.
/// </summary>
/// <returns>An Entity Collection object</returns>
public UserInfoCollection ReadXmlFromDisk()
{
UserInfoCollection newList = new UserInfoCollection();
newList = null;
if ( ! File.Exists(xmlFile))
{
MakeEmptyXmlDocument(xmlFile);
}
if (File.Exists(xmlFile))
{
using (XmlTextReader xr = new XmlTextReader(xmlFile))
{
XmlSerializer xs = new XmlSerializer(typeof(UserInfoCollection));
newList = (UserInfoCollection)xs.Deserialize(xr);
Console.WriteLine(“Got {0} elements in UserInfoCollection”, newList.GetType().ToString());
}
}
return newList;
}
/*********************************************************************
* XML – Create an XML file:
*********************************************************************/
/// <summary>
/// Makes the empty XML document.
/// </summary>
/// <param name=”xmlFile”>The XML file.</param>
private void MakeEmptyXmlDocument(string xmlFile)
{
XmlDocument xmldoc = new XmlDocument();
//Add the XML declaration section
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, “”, “”);
xmldoc.AppendChild(xmlnode);
//Add the root element
XmlNode xmlelem = xmldoc.CreateElement(“”, “UserList”, “”);
xmldoc.AppendChild(xmlelem);
//Add remaining elements
string[] elements =
{
“Login”, “Password”, “FirstName”, “LastName”, “Address”, “City”, “State”, “Zip”, “Telephone”
};
foreach (string element in elements)
{
xmlelem = xmldoc.CreateElement(“”, element, “”);
xmldoc.ChildNodes.Item(1).AppendChild(xmlelem);
}
try
{
xmldoc.Save(xmlFile);
}
catch (IOException)
{
throw;
}
}
/*********************************************************************
* Retrieve the path of a file:
*********************************************************************/
OpenFileDialog openFileDialog1 = new OpenFileDialog();
string fn = “”;
string path = “”;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fn = System.IO.Path.GetFileName(openFileDialog1.FileName);
path = System.IO.Path.GetDirectoryName(openFileDialog1.FileName);
}
MessageBox.Show(fn, “Filename”);
MessageBox.Show(path, “Directory”);
/*********************************************************************
*Reading a file on disk:
*********************************************************************/
void FileIO()
{
System.IO.Stream ios = new System.IO.FileStream(“foo.txt”, System.IO.FileMode.Create);
ios.WriteByte(67);
ios.WriteByte(35);
ios.WriteByte(0xd);
ios.WriteByte(0xa);
ios.Close();
ios = new System.IO.FileStream(“foo.txt”, System.IO.FileMode.Open);
int i = ios.ReadByte();
i = ios.ReadByte();
ios.Close();
ios = new System.IO.FileStream(“bar.txt”, System.IO.FileMode.Create);
System.IO.StreamWriter sw = new System.IO.StreamWriter(ios, System.Text.Encoding.ASCII);
sw.WriteLine(“C#”);
sw.Close();
ios = new System.IO.FileStream(“bar.txt”, System.IO.FileMode.Open);
System.IO.StreamReader sr = new System.IO.StreamReader(ios, System.Text.Encoding.ASCII);
string a = sr.ReadLine();
sr.Close();
}
/*********************************************************************
* Save string text to a file:
*********************************************************************/
string temp = importResult.GetResult().OuterXml;
string pPath = “C:\\test.txt”;
System.IO.StreamWriter lfWriter = new System.IO.StreamWriter(pPath);
lfWriter.Write(“”);
System.IO.StringReader reader = new System.IO.StringReader(temp);
string strTemp = string.Empty;
strTemp = reader.ReadToEnd();
lfWriter.WriteLine(strTemp);
lfWriter.WriteLine();
lfWriter.Close();
/// <summary>
/// Write text to a file.
/// </summary>
/// <param name=”file”>The file to write to.</param>
/// <param name=”text”>The text to write into the file.</param>
/// <remarks>
/// If the file does not exist, it will be created. If the file does
/// exist, the text will be appended at the end of the current contents
/// of the file.
/// e.g. WriteToFile(@”C:\temp.txt”, “This is a test.”);
/// </remarks>
private void WriteToFile(string file, string text)
{
FileStream fs = null;
StreamWriter sw = null;
try
{
fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write);
sw = new StreamWriter(fs);
// Begin writing at the end of the existing contents of the file
sw.BaseStream.Seek(0, SeekOrigin.End);
// Write the text to the file
sw.WriteLine(text);
sw.Flush();
}
catch (Exception)
{
throw;
}
finally
{
sw.Close();
fs.Close();
}
}
/*********************************************************************
* Save to a specific folder:
*********************************************************************/
private static string UserData = “UserData.xml”;
private static string FilePath = Environment.GetFolderPath( Environment.SpecialFolder.Personal );
/*********************************************************************
* Threading:
*********************************************************************/
void Threads() {
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(StartMe));
t.Start();
}
void StartMe() {
lock(this) {
//System.Threading.Monitor.Wait(this);
//System.Threading.Monitor.Pulse(this);
System.Console.WriteLine(“Thread Me”);
}
}
/************************************************************************
* Attributes:
************************************************************************/
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class MyAttribute : System.Attribute {
private int commentID;
private string comment;
public MyAttribute(int commentID, string comment) {
this.commentID = commentID;
this.comment = comment;
}
public int CommentID {
get { return commentID; }
}
public string Comment {
get { return comment; }
set { comment = value; }
}
}
// using attributes
[MyAttribute(1, "Hello World")]
[MyAttribute(2, "Foo Bar")]
class TestAttributes { }
/*********************************************************************
* Reflection:
*********************************************************************/
void DumpType(System.Type t) {
System.Console.WriteLine(“Type: {0}”, t);
System.Reflection.MemberInfo[] a = t.GetMembers();
foreach (System.Reflection.MemberInfo m in a) {
Console.WriteLine(“ {0} = {1}”, m.MemberType, m);
}
// filtering for a method
a = t.FindMembers(
System.Reflection.MemberTypes.Method,
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Static |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.DeclaredOnly,
Type.FilterName, “Get*”);
foreach (System.Reflection.MemberInfo m in a) {
Console.WriteLine(“ {0} = {1}”, m.MemberType, m);
}
}
void Reflections() {
// type discovery
System.Type ta = System.Type.GetType(“System.Int32″);
System.Type tb = typeof(System.Int32);
DumpType((new System.Object()).GetType());
//DumpType(typeof(string));
// viewing attribute metadata
System.Reflection.MemberInfo inf = typeof(TestAttributes);
object[] a = inf.GetCustomAttributes(typeof(MyAttribute), false);
foreach (object m in a) {
MyAttribute x = (MyAttribute)m;
System.Console.WriteLine(x.CommentID + ” : “ + x.Comment);
}
}
/// <summary>
/// Get Calling Method using Reflection
/// </summary>
private void GetCallingMethod()
{
// Get new instance of the call stack
StackTrace stack = new StackTrace();
// GetFrame index of 0 is current stack frame, index of 1 is previous stack frame and so on
StackFrame frame = stack.GetFrame(1);
// Use reflection to get the actual method from the previous stack frame
MethodBase method = frame.GetMethod();
// Get the name of the method and the class it’s containedin using reflection properties
string methodName = method.Name;
string className = method.ReflectedType.ToString();
}
/*********************************************************************
* Database:
*********************************************************************/
void Databases() {
System.Data.SqlClient.SqlConnection Db;
System.Data.SqlClient.SqlDataAdapter Da;
System.Data.DataSet Ds;
System.Data.DataTable Dt;
System.Data.SqlClient.SqlCommand Cmd;
System.Data.SqlClient.SqlDataReader Rs;
string connectionStr = “Server=.; Database=Northwind; Integrated Security=sspi”;
string commandStr;
// open up a database connection
Db = new System.Data.SqlClient.SqlConnection(connectionStr);
Db.Open();
// create a table
commandStr = “CREATE TABLE TestCSharp(“ +
“ TestCD CHAR(2) NOT NULL PRIMARY KEY,” +
“ Description VARCHAR(80) NOT NULL)”;
Cmd = new System.Data.SqlClient.SqlCommand(commandStr, Db);
Cmd.CommandType = System.Data.CommandType.Text;
Rs = Cmd.ExecuteReader();
Rs.Close();
// create a stored procedure for saves
commandStr = “CREATE PROCEDURE spSaveTestCSharp” +
“ @TestCD CHAR(2) = NULL,” +
“ @Description VARCHAR(80) = NULL” +
“ AS” +
“ SET NOCOUNT ON” +
“ INSERT INTO TestCSharp(TestCD, Description) VALUES(@TestCD, @Description)” +
“ SELECT” +
“ Status = 0,” +
“ Token = ‘1234′”;
Cmd = new System.Data.SqlClient.SqlCommand(commandStr, Db);
Cmd.CommandType = System.Data.CommandType.Text;
Rs = Cmd.ExecuteReader();
Rs.Close();
// create a stored procedure for reads
commandStr = “CREATE PROCEDURE spReadTestCSharp” +
“ AS” +
“ SET NOCOUNT ON” +
“ SELECT” +
“ Status = 0,” +
“ Token = ‘1234′,” +
“ TestCD = tab.TestCD,” +
“ Description = tab.Description” +
“ FROM TestCSharp tab” +
“ ORDER BY tab.TestCD”;
Cmd = new System.Data.SqlClient.SqlCommand(commandStr, Db);
Cmd.CommandType = System.Data.CommandType.Text;
Rs = Cmd.ExecuteReader();
Rs.Close();
// insert via stored procedure call
Cmd = new System.Data.SqlClient.SqlCommand(“spSaveTestCSharp”, Db);
Cmd.CommandType = System.Data.CommandType.StoredProcedure;
Cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter(“@TestCD”, System.Data.SqlDbType.VarChar, 2));
Cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter(“@Description”, System.Data.SqlDbType.VarChar, 80));
Cmd.Parameters["@TestCD"].Value = “TX”;
Cmd.Parameters["@Description"].Value = “Texas”;
Rs = Cmd.ExecuteReader();
Rs.Read();
int Status = (int)Rs["Status"];
string Token = (string)Rs["Token"];
if (Status != 0) {
System.Console.WriteLine(“Error in test insert”);
}
Rs.Close();
// read via stored procedure call
Cmd = new System.Data.SqlClient.SqlCommand(“spReadTestCSharp”, Db);
Cmd.CommandType = System.Data.CommandType.StoredProcedure;
Rs = Cmd.ExecuteReader();
Rs.Read();
Status = (int)Rs["Status"];
Token = (string)Rs["Token"];
if (Status != 0) {
System.Console.WriteLine(“Error in test insert”);
} else {
do
System.Console.WriteLine(Rs["TestCD"] + ” “ + Rs["Description"]);
while (Rs.Read());
}
Rs.Close();
// example using DataAdapter (sans SqlConnection)
commandStr = “SELECT * FROM TestCSharp”;
Da = new System.Data.SqlClient.SqlDataAdapter(commandStr, connectionStr);
Ds = new System.Data.DataSet();
Da.Fill(Ds, “Test”);
Dt = Ds.Tables[0];
foreach (System.Data.DataRow row in Dt.Rows) {
System.Console.WriteLine(row["TestCD"] + ” “ + row["Description"]);
}
// drop the read stored procedure
commandStr = “DROP PROCEDURE spReadTestCSharp”;
Cmd = new System.Data.SqlClient.SqlCommand(commandStr, Db);
Cmd.CommandType = System.Data.CommandType.Text;
Rs = Cmd.ExecuteReader();
Rs.Close();
// drop the save stored procedure
commandStr = “DROP PROCEDURE spSaveTestCSharp”;
Cmd = new System.Data.SqlClient.SqlCommand(commandStr, Db);
Cmd.CommandType = System.Data.CommandType.Text;
Rs = Cmd.ExecuteReader();
Rs.Close();
// drop the table
commandStr = “DROP TABLE TestCSharp”;
Cmd = new System.Data.SqlClient.SqlCommand(commandStr, Db);
Cmd.CommandType = System.Data.CommandType.Text;
Rs = Cmd.ExecuteReader();
Rs.Close();
// close the database connection
Db.Close();
}
/*********************************************************************
* Networking:
*********************************************************************/
void Networking() {
System.Net.WebClient wc = new System.Net.WebClient();
System.Text.UTF8Encoding utf = new System.Text.UTF8Encoding();
try {
// can’t seem to get this thing to work???
string doc = utf.GetString(wc.DownloadData(“http://localhost/”));
System.Console.WriteLine(doc);
} catch (System.Net.WebException e) {
Console.WriteLine(e);
}
}
/*********************************************************************
* Inner Classes:
*********************************************************************/
public class InnerClass { // C# inner classes are equivalent to static inner classes in Java
int a; // No C# equivalent for instance inner classes or anonymous classes
public int b; // can not access instance methods or properties of the outer class
private int c;
public InnerClass() {
InnerInnerClass xa = new InnerInnerClass();
}
public class InnerInnerClass {
int a;
public int b;
private int c;
public InnerInnerClass() {
System.Console.WriteLine(“InnerInnerClass”);
a = 0;
}
}
}
}
/************************************************************************
* Outer Classes:
************************************************************************/
class OuterClass { // outer class can not be declared public
const double PI = 3.14;
static int objcount = 0;
internal OuterClass() {
int i;
double x;
String s;
XShape x1;
XShape x2;
XShape x3;
XShape x4;
XShape x5;
XRectangle xa;
IConvert xb;
x1 = new XRectangle(3.0, 4.0);
x2 = new Square(3.0);
x3 = new Triangle(1.0, 2.0, 3.0);
x4 = new Circle(4.0);
x5 = new EquilateralTriangle(5.0);
xa = (XRectangle)x2; // polymorphism – base class object can point to any derived class
x2 = xa; // assigning object to super class does not require casting
x = x1.Area(); // appropriate method for the subclass instance is called
i = x2.Sides; // superclass variables can only access variables and methods
s = x3.ToString(); // that exist at the superclass level of the variable
xb = (IConvert)x4; // polymorphism – interface var can point to any class that implements
x = xb.InchToMM();
System.Console.WriteLine(x1.ToString() + “:” + x2.ToString() + “:” + x3.ToString() + “:” +
x4.ToString() + “:” + x5.ToString());
}
// inner class objects outside of class can be created only in context of the top level class
OuterClass(String s) {
Syntax xa = new Syntax();
Syntax.InnerClass xb = new Syntax.InnerClass();
Syntax.InnerClass.InnerInnerClass xc = new Syntax.InnerClass.InnerInnerClass();
}
}
/************************************************************************
* SubClasses:
************************************************************************/
abstract class XShape { // abstract class can not be alocated – serves as subclass template
internal String name;
internal int Sides = 0; // subclasses inherit all fields and methods not defined as private
internal XShape(int Sides) {
this.Sides = Sides;
}
internal abstract double Area(); // abstract requires all subclasses to define this method
internal virtual double Perimeter() { // virtual methods are intended to be overridden – must be explicit (final is default)
return 0;
}
public override String ToString() { // override the inherited Object method
return name;
}
}
class XRectangle : XShape { // extends identifies this as a subclass of the specified superclass
internal double length = 1.0; // subclass inherits all members of superclass that are not private
double width = 1.0;
internal XRectangle(double length, double width) : base(4) { // constructors of base class not inherited – but can be called
name = “XRectangle”;
this.length = length;
this.width = width;
}
internal XRectangle() : this(2, 4) { // this or super constructor must be first statement in constructor
}
override internal double Area() { // define abstract method
return length * width;
}
override internal double Perimeter() {
return 2 * length * width;
}
}
sealed class Square : XRectangle { // sealed (final) class prevents any further subclassing
new internal double length; // new keyword indicates intentionally shadowing
internal Square(double length) : base(length, length) {
name = “Square”;
this.length = length;
base.length = length; // accessing shadowed variables allowed through super
((XRectangle)this).length = length; // accessing shadowed variables allowed through casting
double x = base.Area(); // accessing overridden method allowed through super
x = ((XRectangle)this).Area(); // casting does not provide access to the overridden method
}
override internal double Area() { // override base class method – Perimeter function is inherited
return base.Area(); // overriding method cannot be less accessible than overridden method
} // throws clause of overriding method must match overridden method
}
class Triangle : XShape {
internal double[] side = new double[3];
double xbase;
double height;
internal Triangle(double a, double b, double c) : base(3) {
name = “Triangle”;
side[0] = a;
side[1] = b;
side[2] = c;
xbase = a;
height = 1.0;
}
override internal double Area() {
return 0.5 * xbase * height;
}
override internal double Perimeter() {
return (side[0] + side[1] + side[2]);
}
}
class Factors {
public const double PI = 3.14;
public static double PISQUARE = Math.Pow(PI, 2);
public const double INCH_TO_MM = 25.4;
private Factors() { }
}
/************************************************************************
* Interfaces:
************************************************************************/
interface IConvert { // an interface is a collection of abstract methods
double InchToMM(); // methods in interface are always abstract and public (can not specify access modifier)
} // C# does not support constant fields in interfaces
interface IMoreConvert : IConvert { // interfaces can be extended similar to classes
double MMToInch();
}
class Circle : XShape, IMoreConvert { // multiple interfaces may be implemented
double radius; // explicit implementation can be used for methods that exist in more than one interface
// IMoreConvert.MMToInch() – can only be accessed through cast of the object to interface
internal Circle(double radius) : base(0) {
name = “Circle”;
this.radius = radius;
}
override internal double Area() { // abstract methods required from superclass
return Factors.PI * Factors.PI * radius;
}
override internal double Perimeter() { // override superclass method
return 2 * Factors.PI * radius;
}
public double InchToMM() { // abstract method for interface
return (Perimeter() * Factors.INCH_TO_MM);
}
public double MMToInch() {
return radius * (1 / Factors.INCH_TO_MM);
}
}
internal class EquilateralTriangle : Triangle, IConvert {
internal EquilateralTriangle(double a) : base(a, a, a) {
name = “EquilateralTriangle”;
}
override internal double Area() {
return 0.5;
}
public double InchToMM() { // abstract method for interface
return 3 * side[0] * Factors.INCH_TO_MM;
}
}
/************************************************************************
* Structs:
************************************************************************/
public struct Location { // structs do not support inheritance (can implement interfaces)
private int xval; // initialization not supported
private int yval;
public Location(int x, int y) { // structs are value objects
xval = x; // destructors not supported
yval = y;
}
public int x {
get {
return xval;
}
set {
xval = value;
}
}
public int y {
get {
return yval;
}
set {
yval = value;
}
}
public override string ToString() {
return String.Format(“{0}, {1}”, xval, yval);
}
}
/************************************************************************
* Link Lists:
************************************************************************/
class LinkList {
LinkList prev;
LinkList next;
LinkList() {
prev = null;
next = null;
}
LinkList(LinkList x) {
x.prev = x;
x.next = null;
x.prev.next = this;
}
}
}
/************************************************************************
* Documentation Comments:
************************************************************************/
/// <summary>
/// Summary of a Member
/// </summary>
/// <remarks>Description of a type</remarks>
/// <param name=”pname”>Description for method parameter</param>
/// <returns>Description of return value</returns>
/// <exception cref=”IndexOutOfRangeException”>Description of Exceptions that may be thrown</exception>
/// <permission cref=”public”>Description of permission requirements</permission>
/// <example>Example Description</example>
/// <code>Syntax x = new Syntax();</code>
/// <seealso cref=”System.IO”>Document Cross Reference</seealso>
/// <see cref=”System.IO”>Inline Document Cross Reference</see>
/// <value>Description of Property Value</value>
/// <paramref name=”prname”>Parameter name within descriptive text</paramref>
/// <include file=”documentation.xml” path=”/”>External documentation file</include>
/// <mytag>User Defined Tags</mytag>
/***************************************************************************
* Preprocessor Defines:
***************************************************************************/
#define DEBUG // defines/undefines must be first directives in file
#undef DEBUG
/***************************************************************************
* Using NameSpace References:
***************************************************************************/
using System; // allow simple access to classes within namespace without full name
using socks = System.Net.Sockets; // aliasing namespace
using txt = System.String; // aliasing type
/***************************************************************************
* NameSpace Definition:
***************************************************************************/
namespace Fred { namespace Hank { } } // namespaces may be nested
namespace Fred.Hank { } // shortcut for nested namespaces
namespace Test {
/************************************************************************
* Classes:
************************************************************************/
class Syntax {
/*********************************************************************
* Access Modifiers:
*********************************************************************/
int mydefault; // private by default
public int mypublic; // visible to any class
private int myprivate; // visible only to this class
protected int myprotected; // visible only to this class and subclasses
internal int myinternal; // visible to any class in this assembly
protected internal int myprotint; // protected or internal visibility
// class, struct, properties and indexers can be set with: abstract, virtual, override, sealed
}