Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Monday, November 17, 2014

https://chocolatey.org/

choco install Atom

choco install notepadplusplus

choco install ccleaner

choco install paint.net

choco install dropbox

choco install filezilla

choco install vlc

choco install 7zip

| | # 
# Tuesday, November 11, 2014
( VPN )

I keep my VPN alive from my desktop PC at work, so can dial in from home/other offices.  Sometimes the VPN drops (for whatever reason)

Setup a task in Task Scheduler:

image

image
When a VPN disconnect is detected, wait for a minute, then run.  Keep running every 30minutes for a day.

and the batch file that is run is:

rasdial “nameofVPN” username password

| | # 
( regex )

public static void Main(){ var security = "123-12-1234"; var pattern = @"^\d{3}-\d{2}-\d{4}$"; var result = Regex.Match(security, pattern); Console.WriteLine(result); }

d – Digit

public static void Main(){ var security = "ABC 123"; //var security = "123 ABC"; var pattern = @"(^\d{3} [A-Z]{3}$)|(^[A-Z]{3} \d{3}$)"; var result = Regex.Match(security, pattern); Console.WriteLine(result); }

Or..

public static void Main() { #if DEBUG Console.WriteLine("Mode=Debug"); #else Console.WriteLine("Mode=Release"); #endif #if TRACE Console.WriteLine("Mode=On"); #else // never called Console.WriteLine("Mode=Off"); #endif }

Trace On is called in Debug and Release modes.

Crypto

public static void Main() { string data = "asdf"; byte[] userData = GetBytes(data); using (SHA256 shaM = new SHA256Managed()) { var result = shaM.ComputeHash(userData); } } static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; }

Strong Names

A strong name consists of the assembly's identity — its simple text name, version number, and culture information (if provided) — plus a public key and a digital signature.

You can use strong naming to ensure that when you load a DLL you get exactly the DLL you were expecting and not some other DLL that happens to have the same name.

http://stackoverflow.com/questions/2982780/what-is-strong-name-in-net

| | # 
# Wednesday, November 05, 2014

As part of the c# there is a section on reflection:

Attributes eg

[Serializable] class Person { public string FirstName { get; set; } public string LastName { get; set; } }

asdf
[Fact] [Trait(“Category”, “Unit Test”)] public void MyUnitTest() { }

can derive from this:

public class CategoryAttribute : TraitAttribute { public CategoryAttribute(string value) : base(“Category”, value){ } } public class UnitTestAttribute : CategoryAttribute { public UnitTestAttribute() : base(“Unit Test”){ } }

then

[Fact] [UnitTest] public void MySecondUnitTest() {}

Interesting.

Reflection

Reflection enables an application to collection information about itself

public static void Main() { int i = 42; // GetType is a method on Object System.Type type = i.GetType(); // System.Int32 Console.WriteLine(type); }

If you want a plug-in system, and you drop in an assembly in a directory.  Need to use reflection.

class Program { public interface IPlugin { string Name { get; } string Description { get; } bool Load(MyApplication application); } public class MyApplication{} public static void Main() { Assembly pluginAssembly = Assembly.Load("testassembly"); var plugins = from type in pluginAssembly.GetTypes() //where typeof(IPlugin).IsAssignableFrom(type) && !type.IsInterface where !type.IsInterface select type; foreach (Type pluginType in plugins) { // Returns null instances IPlugin plugin = Activator.CreateInstance(pluginType) as IPlugin; } } }

and then the testassembly:
namespace testassembly { public interface IPlugin { string Name { get; } string Description { get; } bool Load(MyApplication application); } public class MyPlugin : IPlugin { public string Name { get { return "MyPlugin"; } } public string Description { get { return "My Sample Plugin"; } } public bool Load(MyApplication application) { return true; } } public class MyApplication { } }

Am not understanding this yet….
public static void Main() { Assembly myAssembly = Assembly.GetExecutingAssembly(); // Bring back classes Type[] myAssemblysTypes = myAssembly.GetTypes(); foreach (Type myType in myAssemblysTypes) { Console.WriteLine("myType Name: {0}", myType.Name); } // ConsoleAppliation2.exe Module[] myAssemblysModules = myAssembly.GetModules(); foreach (Module myModule in myAssemblysModules) { Console.WriteLine("myModule Name: {0}", myModule.Name); } // Assembly name and version var x = new MyApplication(); // mscorlib 4.0.0 // testassembly 1.0.0.0 AssemblyName[] referencedAssemblyNames = myAssembly.GetReferencedAssemblies(); foreach (AssemblyName assemblyName in referencedAssemblyNames) { Console.WriteLine("Assembly Name: {0}", assemblyName.Name); Console.WriteLine("Assembly Version: {0}", assemblyName.Version); } // Fields **not working Type t = typeof(Program); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); foreach (FieldInfo fi in fields) { Console.WriteLine("Field name {0}", fi.Name); Console.WriteLine("Field value {0}", fi.GetValue(null)); } }

not working yet :-)
var blah = new Blah(); blah.Age = 42; DumpObject(blah); } static void DumpObject(object obj) { FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); foreach (FieldInfo field in fields) { if (field.FieldType == typeof(int)) { Console.WriteLine(field.GetValue(obj)); } } } } public class Blah { public int Age { get; set; } private int _age; public Blah() { _age = 41; } }

Code that works, showing how to get values or public and private fields using reflection.

// Run a method on Blah MethodInfo doSomethingMethod = blah.GetType().GetMethod("DoSomething", new Type[] { typeof(int) }); int result = (int)doSomethingMethod.Invoke(blah, new object[] { 42 }); Console.WriteLine(result);

and the method is

public int DoSomething(int x) { return x + 1; }

CodeDom and lambdas to generate code

CodeDom to create an object graph that can be converted to a source file/binary assembly that can be executed.

public static void Main() { var compileUnit = new CodeCompileUnit(); var myNamespace = new CodeNamespace("MyNamespace"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); var myClass = new CodeTypeDeclaration("MyClass"); var start = new CodeEntryPointMethod(); var cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World!")); compileUnit.Namespaces.Add(myNamespace); myNamespace.Types.Add(myClass); myClass.Members.Add(start); start.Statements.Add(cs1); var provider = new CSharpCodeProvider(); using (var sw = new StreamWriter("HelloWorld.cs", false)) { var tw = new IndentedTextWriter(sw, " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); tw.Close(); } }

which generated:

//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MyNamespace { using System; public class MyClass { public static void Main() { Console.WriteLine("Hello World!"); } } }

wow!

Lambda functions were introduced in C#3.  It is a compact method to create an anonymous method.

// Func type takes 2 ints and returns and int. // Lambda - anonymous method Func<int, int, int> addFunc = (x, y) => x + y; Console.WriteLine(addFunc(2, 3));

Expression Trees

// The expression is first constructed with a call to Console.Write and Console.WriteLine. BlockExpression blockExpr = Expression.Block( Expression.Call(null,typeof(Console).GetMethod("Write", new Type[] { typeof(String) }),Expression.Constant("Hello ")), Expression.Call(null,typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),Expression.Constant("World!")) ); // Expression is compiled to an Action (as no return) Expression.Lambda<Action>(blockExpr).Compile()();

asdf
| | # 
# Tuesday, November 04, 2014
public static void Main() { int n = 0; // Trying to accessing a local varialbe from another thread var up = Task.Run(() => { for (int i = 0; i < 1000000; i++){ // Reads the value and adds 1 n++; } }); for (int i = 0; i < 1000000; i++){ // Reads the value and subtracts 1 n--; } // Wait for task to complete execution up.Wait(); // Get a different result each time Console.WriteLine(n); }

If the add thread reads then adds, at the same time the subtract thread reads and subtracts, we’re not going to get the expected total of 0.

int n = 0; var _lock = new object(); var up = Task.Run(() => { for (int i = 0; i < 1000000; i++) { // no way other thread can change value while this one is working on it lock (_lock) { n++; } } }); for (int i = 0; i < 1000000; i++) { lock (_lock) { n--; } } // Wait for task to complete execution up.Wait(); Console.WriteLine(n);

Volatile

Disables compiler optimisations.. enforces code order.

InterLocked

private static void Main() { int n = 0; var up = Task.Run(() => { for (int i = 0; i < 1000000; i++) { Interlocked.Increment(ref n); } }); for (int i = 0; i < 1000000; i++) { Interlocked.Decrement(ref n); } up.Wait(); Console.WriteLine(n); }

 

CancellationTasks

private static void Main() { var cancellationTokenSource = new CancellationTokenSource(); CancellationToken token = cancellationTokenSource.Token; Task task = Task.Run(() => { while (!token.IsCancellationRequested) { Console.Write("*"); Thread.Sleep(1000); } }, token); Console.WriteLine("Press enter to stop the task"); Console.ReadLine(); cancellationTokenSource.Cancel(); Console.WriteLine("Press enter to end the application"); Console.ReadLine(); }
| | # 
# Friday, October 31, 2014
( Async | Task | Threading )

As part of the 70-483 exam there is a section on threads/async, which I’m using the study book to go through.

An application runs in its own process.
Each process runs in its own thread

Windows context switches after a period.  On a single core machine giving the illusion of being able to multi task.

Thread

Only use under special circumstances.

public static void ThreadMethod() { for (int i = 0; i < 10; i++) { Console.WriteLine("ThreadProc: {0}", i); } } public static void ThreadMethod2() { for (int i = 0; i < 10; i++) { Console.WriteLine("ThreadProc2: {0}", i); } } public static void Main() { var regularThread = new Thread(ThreadMethod); regularThread.Start(); var regularThread2 = new Thread(ThreadMethod2); regularThread2.Start(); // Wait for spawned thread to end regularThread.Join(); Console.WriteLine("regularThread returned."); regularThread2.Join(); Console.WriteLine("regularThread2 returned.");

Main thread getting returns in the correct order.
public static void ThreadMethod() { for (int i = 0; i < 5; i++) { Console.WriteLine("ThreadProc: {0}", i); // Thread is finished, jump to next time slice Thread.Sleep(0); } } public static void Main() { var t = new Thread(new ThreadStart(ThreadMethod)); t.Start(); for (int i = 0; i < 10; i++) { Console.WriteLine("Main thread: Do some work."); Thread.Sleep(0); } // Wait until the other thread finishes t.Join(); Console.WriteLine("main app ended"); }

Background

public static void ThreadMethod() { for (int i = 0; i < 10; i++) { Console.WriteLine("ThreadProc: {0}", i); Thread.Sleep(1000); } } public static void Main() { var t = new Thread(new ThreadStart(ThreadMethod)); // App will exit immediately and not print anything t.IsBackground = true; t.Start(); }

Parameters

public static void ThreadMethod(object o) { for (int i = 0; i < (int)o; i++) { Console.WriteLine("ThreadProc: {0}", i); Thread.Sleep(0); } } public static void Main() { // Passing a parameter to the Thread var t = new Thread(new ParameterizedThreadStart(ThreadMethod)); t.Start(5); t.Join(); }

Stopping a Thread

public static void Main() { // Better way to stop a thread is with a shared variable bool stopped = false; // Thread initialised with a lambda (shorthand version of a delegate) var t = new Thread(new ThreadStart(() => { while (!stopped) { Console.WriteLine("Running..."); Thread.Sleep(10); Console.WriteLine("Running end"); } })); t.Start(); Console.WriteLine("Press any key to exit"); Console.ReadKey(); stopped = true; // App will always wait for the t thread to end before continuing t.Join(); Console.WriteLine("app stopped"); }

ThreadStatic


// Each thread gets its own copy of a field [ThreadStatic] public static int _field; public static void Main() { new Thread(() => { for (int x = 0; x < 10; x++) { _field++; Console.WriteLine("Thread A: {0}", _field); } }).Start(); new Thread(() => { for (int x = 0; x < 10; x++) { _field++; Console.WriteLine("Thread B: {0}", _field); } }).Start(); Console.ReadKey(); }

ThreadLocal<T>

public static ThreadLocal<int> _field = new ThreadLocal<int>(() =>{ return Thread.CurrentThread.ManagedThreadId; }); public static void Main(){ new Thread(() =>{ // 4 Console.WriteLine("Thread A ManagedThreadId: {0}", _field.Value); }).Start(); new Thread(() =>{ // 3 Console.WriteLine("Thread B ManagedThreadId: {0}", _field.Value); }).Start(); Console.ReadKey(); }

Thread pools

Creating new threads takes time and resources.  Can reuse a thread with a Thread pool.

public static void Main() { ThreadPool.QueueUserWorkItem((s) => { Console.WriteLine("Working on a thread from threadpool"); }); Console.ReadLine(); }

Thread pool limits the number of available threads, so parallelism is lesser.  However this has advantages eg if a webserver has many requests coming it, then can limit the number of threads being spawned by using a pool.

Because threads are being reused they resuse their local state.  May not rely on this state that can potentially be shared.

Tasks

Queuing a work item to a thread pool can be useful, however don’t know when its done, nor the return value.

A task scheduler is responsible for starting the task and managing it.  The task scheduler uses threads from the thread pool.

Executing a task on another thread only makes sense if you want to

  • keep the ‘UI’ free for other work
  • parallelise work to other processors
public static void Main() { Task t = Task.Run(() => { for (int x = 0; x < 100; x++) { Console.Write("*"); } }); // Wait is equivalent to .Join in threads - waits for task to finish t.Wait(); }

then:

public static void Main(){ Task<int> t = Task.Run(() =>{ return 42; }); // By reading the result, forces current thread to wait until the task has finished Console.WriteLine(t.Result); // Displays 42 }

Continuation Task

public static void Main() { Task<int> t = Task.Run(() => { return 42; // Continuation }).ContinueWith(i => i.Result * 2); Console.WriteLine(t.Result); // Displays 84 t = Task.Run(() => { return 42; }); t.ContinueWith((i) => Console.WriteLine("Canceled"), TaskContinuationOptions.OnlyOnCanceled); t.ContinueWith((i) => Console.WriteLine("Faulted"), TaskContinuationOptions.OnlyOnFaulted); // However how to get the return value out of Task? var completedTask = t.ContinueWith((i) => Console.WriteLine("Completed"), TaskContinuationOptions.OnlyOnRanToCompletion); completedTask.Wait(); }

Child Tasks

public static void Main() { // Parent task finished only when 3 children have finished Task<Int32[]> parent = Task.Run(() => { var results = new Int32[3]; new Task(() => results[0] = 0,TaskCreationOptions.AttachedToParent).Start(); new Task(() => results[1] = 1,TaskCreationOptions.AttachedToParent).Start(); new Task(() => results[2] = 2,TaskCreationOptions.AttachedToParent).Start(); return results; }); // Finaltask only runs after after parent tasks have finished var finalTask = parent.ContinueWith( parentTask => { foreach (int i in parentTask.Result) Console.WriteLine("Result of child task: {0}",i); }); Console.ReadLine(); }

 

Task Factory

To make it easier to create tasks all with the same options, can use a TaskFactory.

Task<Int32[]> parent = Task.Run(() => { var results = new Int32[3]; TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent,TaskContinuationOptions.ExecuteSynchronously); tf.StartNew(() => results[0] = 0); tf.StartNew(() => results[1] = 1); tf.StartNew(() => results[2] = 2); return results; }); var finalTask = parent.ContinueWith( parentTask => { foreach (int i in parentTask.Result) Console.WriteLine("Result {0}", i); }); finalTask.Wait();

asdf
Task[] tasks = new Task[3]; tasks[0] = Task.Run(() => { Thread.Sleep(1000); Console.WriteLine("1"); }); tasks[1] = Task.Run(() => { Thread.Sleep(1000); Console.WriteLine("2"); }); tasks[2] = Task.Run(() => { Thread.Sleep(1000); Console.WriteLine("3"); } ); // 3 Threads run simultaneously, so program takes approx 1000ms to run Task.WaitAll(tasks);

WaitAny

public static void Main() { // Create an array of tasks that return ints Task<int>[] tasks = new Task<int>[3]; // Run 3 tasks on different threads tasks[0] = Task.Run(() => { Thread.Sleep(2000); return 1; }); tasks[1] = Task.Run(() => { Thread.Sleep(1000); return 2; }); tasks[2] = Task.Run(() => { Thread.Sleep(3000); return 3; }); while (tasks.Length > 0) { // Wait for any of the tasks to finsih int i = Task.WaitAny(tasks); Task<int> completedTask = tasks[i]; Console.WriteLine(completedTask.Result); // Convert array to a list var temp = tasks.ToList(); // Remove completed task from list temp.RemoveAt(i); tasks = temp.ToArray(); } }

Parallel Class

public static void Main() { // Takes a few secs to run on 8 core machine Parallel.For(0, 10, i => { Console.WriteLine("start on {0}", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(1000); //only prints hello after thread finsihes Console.WriteLine("finish on {0}", Thread.CurrentThread.ManagedThreadId); }); var numbers = Enumerable.Range(0, 10); Parallel.ForEach(numbers, i => { Thread.Sleep(1000); Console.WriteLine("hello"); }); // 4billion var watch = new Stopwatch(); watch.Start(); ParallelLoopResult result = Parallel.For(0, 4000001000, (long i, ParallelLoopState loopState) => { if (i == 4000000000) { Console.WriteLine("Breaking loop"); loopState.Break(); } }); // 12secs on 8 core laptop Console.WriteLine(watch.Elapsed); }

Fun with parallel.

Async Await

Long running CPU bound tasks can be handed to another thread.  However when waiting for I/O bound work things are different.  We don’t want the thread paused by windows whilst waiting for the UI, as it uses memory, and can’t be used for other tasks.

Async solved this problem (keyword added in C#5).  Compiler makes a state machine.

static void Main() { // Create task and start it. // ... Wait for it to complete. Task task = new Task(ProcessDataAsync); task.Start(); task.Wait(); Console.ReadLine(); } static async void ProcessDataAsync() { // Start the HandleFile method. Task<int> task = HandleFileAsync("C:\\temp\\enable1.txt"); // Control returns here before HandleFileAsync returns. // ... Prompt the user. Console.WriteLine("Please wait patiently while I do something important."); Thread.Sleep(1200); Console.WriteLine("after sleep"); // Wait for the HandleFile task to complete. // ... Display its results. int x = await task; Console.WriteLine("Count: " + x); } static async Task<int> HandleFileAsync(string file) { Console.WriteLine("HandleFile enter"); int count = 0; // Read in the specified file. // ... Use async StreamReader method. using (var reader = new StreamReader(file)) { string v = await reader.ReadToEndAsync(); // ... Process the file data somehow. count += v.Length; Thread.Sleep(500); // ... A slow-running computation. // Dummy code. for (int i = 0; i < 10000; i++) { int x = v.GetHashCode(); if (x == 0) { count--; } } } Console.WriteLine("HandleFile exit"); return count; }

Some interesting async code.  So code coming back in a strange order, but fine.

 

Parallel Language Integrated Query (PLINQ)

public static void Main() { var numbers = Enumerable.Range(0, 10); var parallelResult = numbers.AsParallel() // Results are buffered and sorted so come back in correct order .AsOrdered() .Where(i => i % 2 == 0) .ToArray(); foreach (int i in parallelResult) Console.WriteLine(i); }

As ordered – hurts performance.

public static void Main() { var numbers = Enumerable.Range(0, 20); var parallelResult = numbers .AsParallel() //.AsOrdered() .Where(i => i%2 == 0); //.AsSequential(); //Stops query being done in parallel eg to make sure take(5) works //foreach (int i in parallelResult.Take(5)) foreach (int i in parallelResult) Console.WriteLine(i); }

Not a great example..AsSequential operator to make sure Take doesn’t mess up the order

public static void Main() { var numbers = Enumerable.Range(0, 2000000000); var parallelResult = numbers.AsParallel() .Where(i => i % 20000012 == 0); //parallelResult.ForAll(e => Console.WriteLine(e)); // Same as above - cw writes the current parallelResult.ForAll(Console.WriteLine); Action<string> thing = Console.WriteLine; thing("hello"); }

Interesting use of cw!  Also, on point, iterating in parallel.  It does not need to results before starting to iterate (in contracts to foreach. 
Parallel.Foreach is generally favoured.

Exceptions

public static void Main() { var numbers = Enumerable.Range(0, 20); try { var parallelResult = numbers.AsParallel() //.Where(i => IsEven(i)); .Where(IsEven); parallelResult.ForAll(Console.WriteLine); } catch (AggregateException e) { Console.WriteLine("There where {0} exceptions",e.InnerExceptions.Count); } } public static bool IsEven(int i) { if (i % 10 == 0) throw new ArgumentException("i"); return i % 2 == 0; }

 


Concurrent Collections

BlockCollection<T>..

Adding items is fast, and you can set an upper limit.  Will block the calling thread until there is room.  Actually uses a ConcurrentQueue by default.

public static void Main() { var col = new BlockingCollection<string>(); Task read = Task.Run(() => { while (true) { Console.WriteLine(col.Take()); } }); Task write = Task.Run(() => { while (true) { string s = Console.ReadLine(); if (string.IsNullOrWhiteSpace(s)) break; col.Add(s); } }); write.Wait(); }

ConcurrentBag<T>

A bag of items.  Enables duplicates and no order.

public static void Main() { var bag = new ConcurrentBag<int>(); bag.Add(42); bag.Add(21); int result; if (bag.TryTake(out result)) Console.WriteLine(result); // TryPeek not very useful as anohter thread may have already taken it if (bag.TryPeek(out result)) Console.WriteLine("There is a next item: {0}", result); }

then

public static void Main() { var bag = new ConcurrentBag<int>(); Task.Run(() => { bag.Add(42); Thread.Sleep(1000); bag.Add(21); }); // Only displays 42 as Bag is snapshotted before iterating Task.Run(() => { foreach (int i in bag) Console.WriteLine(i); }).Wait(); }

ConcurrentStack and ConcurrentQueue

Stack is LastIn FirstOut (LIFO) – stack of pancakes

Queue if FirstIn FirstOut (FIFO) – a British queue  :-)

public static void Main() { var stack = new ConcurrentStack<int>(); stack.Push(42); int result; if (stack.TryPop(out result)) Console.WriteLine("Popped: {0}", result); // pushes in that order stack.PushRange(new int[] { 1, 2, 3 }); // only 2 spaces in the array int[] values = new int[2]; stack.TryPopRange(values); // will show 3,2 foreach (int i in values) Console.WriteLine(i); }

asdf

public static void Main() { var queue = new ConcurrentQueue<int>(); queue.Enqueue(42); int result; if (queue.TryDequeue(out result)) Console.WriteLine("Dequeued: {0}", result); }

ConcurrentDictionary

public static void Main() { var dict = new ConcurrentDictionary<string, int>(); if (dict.TryAdd("k1", 42)) { Console.WriteLine("Added"); } if (dict.TryUpdate("k1", 21, 42)) { Console.WriteLine("42 updated to 21"); } dict["k1"] = 42; // Overwrite unconditionally int r1 = dict.AddOrUpdate("k1", 3, (s, i) => i * 2); int r2 = dict.GetOrAdd("k2", 3); }

Lots of functionality!

| | # 
# Friday, October 24, 2014
( Action | c# | Func )
var a = Days.Mon; var x = Days.Wed; var b = (int)a; var c = (int) x; } } enum Days { Mon = 5, Tue, Wed, Thur, Fri, Sat, Sun };

Interesting: sequence will be 5,6,7…

From http://www.wrox.com/WileyCDA/WroxTitle/productCd-1118612094,descCd-DOWNLOAD.html

// Is k < 10 // cw // k++ for (int k = 0; k < 10; k++){ Console.WriteLine("hello {0}", k); }

Order of execution.

var curr = "£1,234.56"; double number; double.TryParse(curr, NumberStyles.Currency,null, out number);

Interesting!

var sss = new string('c', 10);

Makes 10 c’s

checked { int test = int.MaxValue; test++; //System.OverflowException thrown }


Checking for arithmetic overflow/underflow errors

float zero = 0; float positive = 1 / zero; Console.WriteLine(positive); // Outputs "Infinity" float negative = -1 / zero; Console.WriteLine(negative); // Outputs "-Infinity" int test = int.MaxValue; test++; Console.WriteLine(test); // int.MinValue var x = int.MinValue; checked { int xy = int.MaxValue; //xy++; // Overflow exception } checked{ float xx = float.MaxValue; var xxx = xx + 1; // no exception if (xx == xxx) // loss of equality in rounding Console.WriteLine("true"); // gets here }


number stuff.

class Program { static void Main(string[] args) { var t = new Thing("hello"); } } class ThingBase { public ThingBase(string message) { Console.WriteLine("ctor of thingbase {0}", message); } } class Thing : ThingBase { public string Message { get; set; } public Thing(string message) : base(message) { Console.WriteLine("ctor of customer"); this.Message = message; } }


Calling a base constructor

Implicity vs Explicity Interface impelement http://stackoverflow.com/questions/4103300/why-implement-interface-explicitly

class Program { static void Main(string[] args) { // TeachingAssistant can't see PrintGrades - public not possible IStudent ta = new TeachingAssistant(); ta.PrintGrades(); } } class TeachingAssistant : IStudent { void IStudent.PrintGrades() { throw new NotImplementedException(); } } interface IStudent { void PrintGrades(); }

Interesting explicit interface implementation.

Action and Func

// Action takes parameters but doesn't return Action note = () => Console.WriteLine("hello"); note(); Action<string> thing = x => Console.WriteLine("thing is {0}", x); thing("ahhh"); // Func is a generic type which encapsulates delegates (callable code) Func<float, float> square; square = delegate(float x) { return x*x; }; square = (float x) => x*x ; square = x => x*x ; var result = square(3); Console.WriteLine(result);
| | # 
# Wednesday, October 22, 2014
( c# )

Rule #10 – Avoid Regions

For splitting up large classes / ugly code.  Break code into separate classes

Rule #9 – Use Exceptions for Errors

  • Instead of status codes or booleans
  • but not for control flow (ie plan to throw and catch somewhere else)
  • Should indicate errors in the program
public bool Login(string username, string password){ if (String.IsNullOrEmpty(username)){ // throw an Exception better.. maybe a problem in the caller? throw new ArgumentException("Username is empty"); // not good - implication is username/password combintation didn't work return false; } // ... return true; }

Rule #8 – Avoid Boolean Parameters

// What does true mean? WriteFile(data, true); // better WriteFile(data, flush:True); // A simple wrapper - nice WriteFileAndFlush(data); WriteFile(data); } private static void WriteFileAndFlush(byte[] contents){ WriteFile(contents, true); } public static void WriteFile(byte[] contents) { WriteFile(contents, false); } // Private so API only shows 2 methods above private static void WriteFile(byte[] contents, bool flush){ }

Rule #7 – Avoid Too Many Parameters

4 seems like too much!

If lots, are they grouped together.. ie can I make a Class?

public void LoginUser(string username, string password, IPAddress ipAddress, bool persist){ // ... } // Grouped parameters.. maybe could be validation logic on the class // to ensure have all required pieces of information public void LoginUser(UserLoginRequest request){ }

Rule #6 – Warnings are Errors

“You the developer, against forces of Entropy”!
Anything you can do to keep entropy away and keep code organised and maintained is good.

image_thumb[1]
Warning level 4 is most aggressive setting.  Treat warnings as errors: All

image_thumb[3]

Rule #5 – Encapsulate Complex Expressions

if (account.Balance > 0 && !account.IsVIP && account.DueDate > CurrentDate){ // send off a warning } // encapsule in the account class // instant recognition is good if (account.IsPasDue){ // ... }

Rule #4 – Try and avoid Multiple Exit Points

usually at bottom of method.

if (account.Balance < 1000){ return false; } else if (account.IsPastDue){ return false; } else if (account.IsVip){ return false; } return true; // better var isValid = true; if (account.Balance < 1000){ isValid = false; } else if (account.IsPastDue) { isValid = false; } else if (account.IsVip) { isValid = false; } return isValid;

Rule #3 – Try to avoid Comments

Most comments are trying to describe the purpose or intention of a piece of code

// ensure we don't send a notification to // important people if (account.IsVip && account.IsPastDue){ SendNotification = false; } // Abstracted into a method so don't need the comment! CancelNotificationForVipAccounts();

For shard libraries the VS comments /// are useful for other developers to see in intellisense what your API does.

Rule #2 – Keep Methods Short

Fit on the screen is good!

1-10 pretty safe
20
30+ start to get worried
50+ problem!

Split up by:?

  • Deciding things
  • Doing things

Rule #1 – Keep Classes Small

Large classes try to do too many things, get cluttered

Split up by Roles, Responsibilities, Delegation

| | # 
( c# )

Coding Standards

Consistency through a codebase so reader can follow and not be confused with something out of the ordinary.
Most people use: http://msdn.microsoft.com/en-us/library/vstudio/ms229043(v=vs.100).aspx

Names of methods should contain a verb - http://msdn.microsoft.com/en-us/library/vstudio/ms229012(v=vs.100).aspx

Props: Noun

Bool props affirmative: eg Isxxx, Canxxxx, HasRecords

R#, StyleCop

Naming

// Ahh strInput - not preferrable public bool Test(string strInput) { string strTrimmed = strInput.Replace(" ", ""); string strReversed = new string(strTrimmed.Reverse().ToArray()); return strReversed.Equals(strReversed); } public bool Check(string input) { input = input.Replace(" ", ""); var reversed = new string(input.Reverse().ToArray()); return reversed.Equals(input); } // Good name public bool IsPalindrome(string input) { // Symmetry - forwards and backwards var forwards = input.Replace(" ", ""); var backwards = new string(forwards.Reverse().ToArray()); return backwards.Equals(forwards); }

Building Meaning

Ahh data and no behaviour (mmmm – probably smell)

If you’re not happy with the code, write the API you want to see

[TestMethod] public void DemonstrationOfCreatingAccount() { // lateAccount better, or a Method var account = new Account(); account.Balance = 9000; account.Customer = new Customer(); account.Customer.Address = new Address(); account.Customer.Address.City = "London"; account.Customer.Address.Country = "UK"; account.Customer.IsVip = true; // Not clear that the account is PastDue account.DueDate = DateTime.Now.AddDays(-1); account.Customer.Name = "Penelope"; }
Builder design pattern better (maybe).. eg
AccountBuilder
  .DefaultAccount
   .AsVip
  .LivesIn(“London”)
  .Build

[TestMethod] public void CanCreateAccount(){ // Using a static method instead of newing up an AccountBuilder var account = AccountBuilder.DefaultAccount().Build(); Assert.IsNotNull(account); } } public class AccountBuilder{ // Something that wraps the account being created public static AccountBuilder DefaultAccount(){ return new AccountBuilder(); } public AccountBuilder(){ _account = new Account(); } public Account Build(){ return _account; } private Account _account; }

Starting off on the Builder pattern.

[TestMethod] public void AssignsDefaultValues() { var account = AccountBuilder.DefaultAccount().Build(); Assert.IsTrue(account.Balance > 0); Assert.IsTrue(account.DueDate > DateTime.Now); Assert.IsNotNull(account.Customer.Address.City); Assert.IsNotNull(account.Customer.Address.Country); Assert.IsFalse(account.Customer.IsVip); Assert.IsNotNull(account.Customer.Name); } } public class AccountBuilder{ // Something that wraps the account being created public static AccountBuilder DefaultAccount(){ return new AccountBuilder(); } public AccountBuilder(){ _account = new Account(); _account.Balance = 10000; _account.DueDate = DateTime.Now.AddDays(1); _account.Customer = new Customer(); _account.Customer.Name = "Michelle"; _account.Customer.IsVip = false; _account.Customer.Address = new Address(); _account.Customer.Address.City = "DC"; _account.Customer.Address.Country = "USA"; } public Account Build(){ return _account; } private Account _account;

Chaining:

public AccountBuilder WithLatePaymentStatus(){ _account.DueDate = DateTime.Now.AddDays(-1); // As we're chaining, need to keep returning ourselves return this; }

Code that expresses intention better

| | #