C# Code Snippets: Common Tasks and Best Practices
Reflection and Type Information
D.
Type t = Type.GetType("CompanyClass");
MethodInfo m = t.GetMethod("MyMethod");
int i = (int)m.Invoke(this, new object[] { 1 });
D. Call the IsFamily
property of the MethodInfo
class.
Culture-Specific Formatting
B.
NumberFormatInfo culture = new CultureInfo("zh-HK").NumberFormat;
culture.CurrencyNegativePattern = 1;
return numberToPrint.ToString("c", culture);
A.
DateTimeFormatInfo dtfi = new CultureInfo("es-MX", false).DateTimeFormat;
DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
string dateString = dt.ToString(dtfi.LongDatePattern);
A.
foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) {
// Output the culture information
}
C.
RegionInfo regionInfo = new RegionInfo("CA");
// Output the region information
D.
CompareInfo comparer = new CultureInfo("it-IT").CompareInfo;
if (comparer.IndexOf(searchList, searchValue) > -1) {
return true;
} else {
return false;
}
Data Transfer and Streams
A.
bytesTransferred = stream1.Read(byteArray, 0, 80);
C.
BufferedStream bufStream = new BufferedStream(netStream, 8192);
bufStream.Write(dataToSend, 0, dataToSend.Length);
C.
MemoryStream outStream = new MemoryStream();
GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress);
zipStream.Write(document, 0, document.Length);
zipStream.Close();
return outStream.ToArray();
C.
MemoryStream strm = new MemoryStream();
DeflateStream deflate = new DeflateStream(strm, CompressionMode.Compress);
deflate.Write(document, 0, document.Length);
deflate.Close();
return strm.ToArray();
B.
string result = null;
StreamReader reader = new StreamReader("Message.txt");
result = reader.ReadToEnd();
C.
StringReader reader = new StringReader(message);
while (reader.Peek() != -1) {
Process(reader.ReadLine());
}
reader.Close();
Delegates and Events
C.
public delegate void PowerDeviceOn(DateTime aoutPowerOff);
A.
public static event FaxDocs Fax;
D.
public delegate bool PowerDeviceOn(DateTime);
Configuration and Serialization
C.
public class DeptHandler : IConfigurationSectionHandler {
public object Create(object parent, object configContext, System.Xml.XmlNode section) {
Department dept = new Department();
dept.Name = section.SelectSingleNode("name").InnerText;
dept.Manager = section.SelectSingleNode("manager").InnerText;
return dept;
}
}
A. Insert the following code between line 1 and 2 of the code segment:
[XmlArrayItem(Type = typeof(Employee))]
[XmlArrayItem(Type = typeof(Manager))]
A. Add the following XML element to the application file:
B. Add the following XML element to the machine configuration file:
B.
<?xml version="1.0" encoding="utf-8"?>
<Meeting xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Time>1100</Time>
<Company>Company</Company>
<Attendee>Mary</Attendee>
</Meeting>
B.
<?xml version="1.0" encoding="utf-8"?>
<category>car</category>
<name>racer</name>
<price>15000</price>
<condition>Excellent</condition>
B. Specify that CompanyClass
implements the IDeserializationCallback
interface.
F. Create an OnDeserialization
method that calls ProcessChildren
.
D.
[OnDeserialized]
internal void UpdateValue(StreamingContext context) {
currRate = GetCurrentRate();
}
D.
SoapFormatter formatter = new SoapFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, dept);
Security and Permissions
A.
Demand()
B.
CodeGroup group1 = new FirstMatchCodeGroup(new AllMembershipCondition(), noTrustStatement);
CodeGroup group2 = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Trusted), fullTrustStatement);
group.AddChild(group2);
A.
CodeAccessPermissions.RevertAssert();
A.
FileSecurity security = new FileSecurity("mydata.xml", AccessControlSections.All);
security.SetAccessRuleProtection(true, true);
File.SetAccessControl("mydata.xml", security);
A.
GenericIdentity ident = new GenericIdentity(userName);
GenericPrincipal currentUser = new GenericPrincipal(ident, userRolesArray);
Thread.CurrentPrincipal = currentUser;
B.
WindowsPrincipal currentUser = (WindowsPrincipal)Thread.CurrentPrincipal;
isAuthorized = currentUser.IsInRole("clerk");
D.
StrongNameIdentityPermission
C.
Evidence evidence = new Evidence();
evidence.AddHost(new Zone(SecurityZone.Intranet));
D.
StrongNamedIdentityPermission
D.
AppDomain domain = AppDomain.CurrentDomain;
domain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal);
A.
{
SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)
}
Threading and Synchronization
C. Use a WaitCallback
delegate to synchronize the threads.
C. Use a WaitCallback
delegate to synchronize the threads.
C. For each calculation, call the QueueUserWorkItem
method of the ThreadPool
class.
D.
private void PerformCalculation(object values) { /* ... */ }
private void DoWork() {
CalculationValues myValues = new CalculationValues();
Thread newThread = new Thread(new ParameterizedThreadStart(PerformCalculation));
newThread.Start(myValues);
}
Event Logging
C.
EventLog myLog = new EventLog("Application", ".");
foreach (EventLogEntry entry in myLog.Entries) {
if (entry.Source == "MySource") {
if (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning) {
PersistToDb(entry);
}
}
}
Interoperability with Unmanaged Code
C.
[DllImport("user32", CharSet = CharSet.Unicode)]
public static extern bool MessageBox(int hWnd, string text, string caption, uint type);
A. Create a class to hold DLL functions and then create prototype methods by using managed code.
A.
[DllImport("user32.dll")]
public static extern int MessageBox(int hWnd, string text, string caption, uint type);
Serialization and Deserialization
A.
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, data);
Service Management
B. Prior to installation, set the Account
, Username
, and Password
properties of the ServiceProcessInstaller
class.
C. Add a class-level System.Timers.Timer
variable to the service class code. Move the call to the DoWork
method into the Elapsed
event procedure of the timer, set the Enabled
property of the timer to true
, and call the Start
method of the timer in the OnStart
method.
B. Insert the following line of code between lines 03 and 04:
ctrl.MachineName = serverName;
E. Insert the following line of code between lines 04 and 05:
ctrl.Start();
A.
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service WHERE State=\"Paused\"");
foreach (ManagementObject svc in searcher.Get()) {
Collection.Add(svc["DisplayName"]);
}
Networking
D.
SslStream ssl = new SslStream(client.GetStream());
ssl.AuthenticateAsServer(certificate, false, SslProtocols.Tls, true);
C.
MailAddress addrFrom = new MailAddress("me@Company.com");
MailAddress addrTo = new MailAddress("you@Company.com");
MailMessage message = new MailMessage(addrFrom, addrTo);
message.Subject = "Greetings!";
message.Body = "test";
SmtpClient client = new SmtpClient("smtp.Company.com");
client.Send(message);
Cryptography
D.
DES des = new DESCryptoServiceProvider();
ICryptoTransform crypto = des.CreateEncryptor(key, iv);
MemoryStream cipherStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Write);
cryptoStream.Write(message, 0, message.Length);
C.
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] hash = sha.ComputeHash(message);
D.
TripleDES des = new TripleDESCryptoServiceProvider();
ICryptoTransform crypto = des.CreateDecryptor(key, iv);
MemoryStream cipherStream = new MemoryStream(cipherMessage);
CryptoStream cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Read);
string message;
message = new StreamReader(cryptoStream).ReadToEnd();
A.
HashAlgorithm algo = HashAlgorithm.Create("MD5");
byte[] hash = algo.ComputeHash(message);
Collections
B.
BitVector32 answer = new BitVector32(-1);
A.
class MyDictionary : Dictionary<TKey, TValue>
C.
q.Clear();
A.
System.UInt16
B.
HybridDictionary class
D.
ArrayList al = new ArrayList();
Process[] procs = Process.GetProcesses(strComputer);
foreach (Process proc in procs) {
al.Add(proc.ProcessName);
}
C.
ArrayList ar = new ArrayList();
Process[] procs;
ProcessModuleCollection modules;
procs = Process.GetProcessesByName(@"Process1");
if (procs.Length > 0) {
modules = procs[0].Modules;
foreach (ProcessModule mod in modules) {
ar.Add(mod.FileName);
}
}
D.
ArrayList al = new ArrayList();
ArrayList sync_al = ArrayList.Synchronized(al);
return sync_al;
Error Handling and Exceptions
D.
throw new CustomException("Argument is out of bounds");
C.
StackTrace
B.
Debug.WriteLineIf(fName != "Company", fName, "Test Failed");
Isolated Storage
A.
IsolatedStorageFile store;
store = IsolatedStorageFile.GetUserStoreForAssembly();
store.CreateDirectory("Preferences");
A.
IsolatedStorageFile isoFile;
isoFile = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("Setting.dat", FileMode.Open, isoFile);
string result = new StreamReader(isoStream).ReadToEnd();
Assemblies and AppDomains
A.
Stack undoBuffer = new Stack();
C.
AppDomain domain;
domain = AppDomain.CreateDomain("CompanyDomain");
B.
AssemblyName myAssembly = new AssemblyName();
myAssembly.Name = "MyAssembly";
AssemblyBuilder myAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(myAssembly, AssemblyBuilderAccess.Save);
myAssemblyBuilder.Save("MyAssembly.dll");
A. Create a DEVPATH
environment variable that points to the build output directory for the strong-named assembly.
A.
AppDomain domain = AppDomain.CurrentDomain;
string myPath = Path.Combine(domain.BaseDirectory, "Company1.dll");
Assembly asm = Assembly.LoadFrom(myPath);
Classes and Interfaces
B.
public class PrintingArgs : EventArgs {
private int copies;
public PrintingArgs(int numberOfCopies) {
this.copies = numberOfCopies;
}
public int Copies {
get { return this.copies; }
}
}
A.
public class Person : IComparable {
public int CompareToString(string other) { /* ... */ }
}
C.
public class Customer {
string addressString;
public Customer() { }
public string GetAddress() {
return addressString;
}
}
C.
public class Age : IComparable {
public int Value;
public int CompareTo(object obj) {
if (obj is Age) {
Age _age = (Age)obj;
return Value.CompareTo(_age.Value);
}
throw new ArgumentException("object not an Age");
}
}
B. Define the class such that it implements the IDisposable
interface.
D. Create a class destructor that releases the unmanaged resources.
F. Create a Dispose
method that releases unmanaged resources and calls methods on other objects to release the managed resources.
B.
public class Role : ConfigurationElement {
internal string _ElementName = "role";
[ConfigurationProperty("name", IsRequired = true)]
public string Name {
get { return ((string)base["name"]); }
set { base["name"] = value; }
}
}
D. Define an interface for the class and add the following attribute to the class definition:
[ClassInterface(ClassInterfaceType.None)]
public class Employee : IEmployee {
Miscellaneous
A. Start listening for events by calling a method of the ManagementEventWatcher
.
B. Set up a listener for events by using the EventArrived
event of the ManagementEventWatcher
.
A. The method must return a type of either IEnumerator
or IEnumerable
.
B.
Rectangle rectangle = new Rectangle(10, 10, 450, 25);
LinearGradientBrush rectangleBrush = new LinearGradientBrush(rectangle, Color.AliceBlue, Color.CornflowerBlue, LinearGradientMode.ForwardDiagonal);
Pen rectanglePen = new Pen(rectangleBrush);
Graphics g = this.CreateGraphics();
g.FillRectangle(rectangleBrush, rectangle);