Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Wednesday, 07 October 2015
( c# | Euler | Euler Functional | F# )

https://projecteuler.net/archives  is a fantastic list of puzzles which are solvable by programming.

I find them excellent for exploring into a language.

https://github.com/djhmateer/Euler

Strategy is to explore F#, then see how in C# it can be written

Problem1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

F#

// Solution5 - List.filter let total' = [1..999] // filter on a function (predicate) |> List.filter(fun i -> i % 5 = 0 || i % 3 = 0) |> List.sum printfn "result %i" total

C#

// Solution 1 - Iterative approach int sum = 0; for (int i = 1; i < 1000; i++) { if (i % 3 == 0 || i % 5 == 0) sum += i; } Console.WriteLine(sum); // Solution 2 - F# inspired solution - using Enumerable var result = Enumerable.Range(1, 999).Where(x => x % 3 == 0 || x % 5 == 0).Sum(); Console.WriteLine(result);
| | # 
# Wednesday, 24 June 2015
( c# )

From Marc Seemann’s SOLID course on Pluralsight

http://geekswithblogs.net/BlackRabbitCoder/archive/2011/02/17/c.net-little-wonders-the-concurrentdictionary.aspx

https://github.com/djhmateer/githubscratch

"Is a thread safe counterpart to Dictionary"

AddOrUpdate - an attempt at Upsert

[Fact] public void ConcurrentDictTest(){ var dict = new ConcurrentDictionary<int, string>(); // add key 1 value thing1 to the dictionary, or update key1 to thing1 dict.AddOrUpdate(1, "thing1", (i,s) => "thing1"); dict.AddOrUpdate(2, "thing2", (i,s) => "thing2"); dict.AddOrUpdate(1, "thing1", (i,s) => "thingUpdated"); // get a value from the dict, and if not there will insert // useful for caching! // 1 is there, so doesn't need to get its value // call the delegate to get the value // lambda expression var result = dict.GetOrAdd(1, _ => Something(1)); // lambda expression var result8 = dict.GetOrAdd(8, i => "hello" + i); // an anonymous method var result3 = dict.GetOrAdd(3, delegate { return Something(3); }); var result4 = dict.GetOrAdd(4, arg => Something(3)); // It recognises the signature, so don't need to pass the 5 var result5 = dict.GetOrAdd(5, ValueFactory); // could pass the value anyway var result6 = dict.GetOrAdd(6, ValueFactory(6)); var result7 = dict.GetOrAdd(7, Something); } private string ValueFactory(int i){ return "hello again " + i; } private string Something(int i){ return "hello"; }
| | # 
# Wednesday, 18 March 2015
# Tuesday, 06 January 2015
( c# | JSON | Spotify )

Goal: Get API calls working to Spotify using a console app

http://www.royjacobs.org/blog/2012/11/13/importing-m3u-playlists-into-spotify/ – c# importer (no auth)

image
Using a deprecated call

image
Interesting I’m getting 224 results back!

image
Can type in the Href and test have got the correct song back.

Searching

http://ws.spotify.com/search/1/track?q=Metallica+One
This old Metadata API, which is now deprecated (but still working).

image
Old API returning XML.

https://api.spotify.com/v1/search?q=metallica&type=artist
The Web API

image
JSON Formatter extension for Chrome

https://developer.spotify.com/web-api/console/
Interactive Console for exploring the API

  • Album
  • Artist
  • Track
  • Playlist

Exploring the json and viewing the image URL’s that are returned

image

An image of the band
https://i.scdn.co/image/15d9ccb37a96d49f69f44f999fb1e9e46f9b3ccd

Am using Newtonsoft’s JsonConvert.DeserializeObject<T> to get into a POCO:

image
Used the API to get a simple search going on the web.

Exploring the json returned results, finding that some artists return 3,4 or 0 images.  So put some simple view logic in to force display of 200 width.  And put in a sample default band (muse) on page load of http://www.davesjokes.co.uk/Home/SpotifyArtistSearch

image

Offset and Limit

https://developer.spotify.com/web-api/search-item/
https://api.spotify.com/v1/search?query=muse&offset=20&limit=20&type=artist

Limit default is 20, max is 50.

Timing

var stopWatch = new Stopwatch(); stopWatch.Start(); string json = CallSpotifyAPI(artistName); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:0}",ts.TotalMilliseconds); ViewBag.APITime = elapsedTime;
TotalMilliseconds is handy.  Format makes sure no decimal points in the ms.

image
Timing code.  Next and previous buttons.  All GET requests now – form submits via querystring.  Title is different if no search.

| | # 
# Friday, 24 October 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, 22 October 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

| | # 
# Tuesday, 21 October 2014
( c# | Functional )

Building abstractions using functions

Build own primitives.. classes last module… methods/functions this module

Higher order functions

Take 1 or more fns as an input, or return fns

internal static class Program2 { private static void Main(string[] args) { var numbers = new[] { 3, 5, 7, 9, 11, 13, 15 }; foreach (var prime in numbers.FindPrimes()) { Console.WriteLine(prime); } } private static IEnumerable<int> FindPrimes(this IEnumerable<int> values) { //iterate //test if prime //return a difference sequence of ints var result = new List<int>(); foreach (var number in values) { if (IsPrime(number)) { result.Add(number); } } return result; } private static bool IsPrime(int number) { bool isPrime = true; for (long i = 2; i < number - 1; i++) { if (number % i == 0) isPrime = false; } return isPrime; } }

Extension method on IEnumerable<int>

internal static class Program2 { private static void Main(string[] args) { var numbers = new[] { 3, 5, 7, 9, 11, 13, 15 }; // Passing in the IsPrime function into Find foreach (var prime in numbers.Find(IsPrime)) { Console.WriteLine(prime); } } // Find is a higher order function, as it takes another function as a parameter // composable with other functions private static IEnumerable<int> Find(this IEnumerable<int> values, Func<int, bool> test) { //iterate //test if prime //return a difference sequence of ints var result = new List<int>(); foreach (var number in values) { //if (IsPrime(number)) { if (test(number)) { result.Add(number); } } return result; } private static bool IsPrime(int number) { bool isPrime = true; for (long i = 2; i < number - 1; i++) { if (number % i == 0) isPrime = false; } return isPrime; } }

Find is a Higher Order Function.

Lazyness

Lazy evaluation – allows you to write an expression that’s not executed until the last possible moment.  And only if we need the result (program forces us to execute).

  • Avoid expensive calculations that we don’t need
  • Data structures of an infinite size
private static void Main(string[] args) { var numbers = new[] { 3, 5, 7, 9, 11, 13, 15 }; // Passing in the IsPrime function into Find foreach (var prime in numbers.Find(IsPrime).Take(2)) { Console.WriteLine(prime); } } // Find is a higher order function, as it takes another function as a parameter // composable with other functions private static IEnumerable<int> Find(this IEnumerable<int> values, Func<int, bool> test) { //iterate //test if prime //return a difference sequence of ints var result = new List<int>(); foreach (var number in values) { Console.WriteLine("Testing {0}", number); if (test(number)) { result.Add(number); } } return result; }

image
Didn’t expect this. 

image
Swap out the internal list for yield return.

Generates code for IEnumerable under the hood.

Essentially pauses the execution of the method for the caller to process the current result.  When the caller needs the next result, execution will resume where it last left off.

private static void Main(string[] args) { var numbers = new[] { 3, 5, 7, 9, 11, 13, 15 }; // Passing in the IsPrime function into Find //foreach (var prime in numbers.Find(IsPrime).Take(2)) { foreach (var prime in GetRandomNumbers().Find(IsPrime).Take(2)) { Console.WriteLine(prime); } } // Interesting this function stops when 2 primes are found (as Take(2) above) static IEnumerable<int> GetRandomNumbers(){ yield return 3; yield return 6; yield return 8; yield return 9; yield return 11; yield return 13; }

asdf

private static void Main(string[] args) { var numbers = new[] { 3, 5, 7, 9, 11, 13, 15 }; // Passing in the IsPrime function into Find //foreach (var prime in numbers.Find(IsPrime).Take(2)) { foreach (var prime in GetRandomNumbers().Find(IsPrime).Take(2)) { Console.WriteLine(prime); } } static IEnumerable<int> GetRandomNumbers(){ Random rand= new Random(); // Infinite loop while (true){ yield return rand.Next(1000); } }

Nice – tries random numbers until it gets 2 primes.

An infinite sequence of integers

Timing and Retries

Higher order functions not related to querying.

public class Timekeeper { public TimeSpan Measure(Action action) { var watch = new Stopwatch(); watch.Start(); action(); return watch.Elapsed; } } internal static class Program2 { private static void Main(string[] args) { var timekeeper = new Timekeeper(); // Passing in a function to Measure var elapsed = timekeeper.Measure(() => { foreach (var prime in GetRandomNumbers().Find(IsPrime).Take(2)) { Console.WriteLine(prime); } }); Console.WriteLine(elapsed); }


Interesting! 1:48 of 3:37 in Timing and Retries

public static T WithRetry<T>(this Func<T> action) { var result = default(T); int retryCount = 0; bool succesful = false; do { try { result = action(); succesful = true; } catch (WebException ex) { retryCount++; } } while (retryCount < 3 && !succesful); return result; } private static void Main(string[] args) { var client = new WebClient(); Func<string> download = () => client.DownloadString("http://microsoft.com"); // This is a Higher Order Function, even though it doesn't look like it var data = download.WithRetry();

Interesting!

Partial Application and Currying

Partical application is adapting a function into a function which doesn’t need a paramter

public static Func<TResult> Partial<TParam1, TResult>( this Func<TParam1, TResult> func, TParam1 parameter) { return () => func(parameter); }

Currying .. (Haskall Curry).

public static Func<TParam1, Func<TResult>> Curry<TParam1, TResult> (this Func<TParam1, TResult> func) { return parameter => () => func(parameter); }

Async and Parallel

a benefit of functional..parallelism

AsParallel in TPL.

static void Main(string[] args) { var timekeeper = new Timekeeper(); var elapsed = timekeeper.Measure(() => FindLargePrimes(1, 200000)); Console.WriteLine(elapsed); } private static IList<int> FindLargePrimes(int start, int end) { var primes = Enumerable.Range(start, end - start).ToList(); return primes.Where(IsPrime).ToList(); }

and now in parallel

static void Main(string[] args) { var timekeeper = new Timekeeper(); var elapsed = timekeeper.Measure(() => FindLargePrimes(1, 200000)); Console.WriteLine(elapsed); } private static IList<int> FindLargePrimes(int start, int end) { var primes = Enumerable.Range(start, end - start).ToList(); return primes.Where(IsPrime).ToList(); } private static IList<int> FindLargePrimesInParallel(int start, int end) { var primes = Enumerable.Range(start, end - start).ToList(); return primes.AsParallel().Where(IsPrime).ToList(); }

For more control over the execution

// Expecting a Task which returns an IEnumerable<int> var task = new Task<IEnumerable<int>>( () => FindLargePrimes(3, 100) ); task.Start(); Console.WriteLine("Doing other work"); // Wait until unblocked task.Wait(); foreach (var number in task.Result) { Console.WriteLine(number); }

and more..

// Expecting a Task which returns an IEnumerable<int> var task = new Task<IEnumerable<int>>( () => FindLargePrimes(3, 100) ); // Chaining var task2 = task.ContinueWith((antecedent) => { foreach (var number in antecedent.Result) { Console.WriteLine(number); } }); task.Start(); Console.WriteLine("Doing other work"); // Wait until unblocked task2.Wait();
| | # 
# Friday, 17 October 2014
  • Encapsulation
  • Inhertence
  • Polymorphism

Encapsulation

Glance test… what abstractions are there… ie for a code review, shouldn’t be primitive types around.

class Program { static void Main(string[] args) { var date = new List<DateTime>(); var open = new List<decimal>(); var high = new List<decimal>(); var low = new List<decimal>(); var close = new List<decimal>(); var lines = File.ReadAllLines(args[0]); for (int i = 1; i < lines.Length; i++) { var data = lines[i].Split(','); date.Add(DateTime.ParseExact(data[0], "M/d/yyyy", CultureInfo.InvariantCulture)); open.Add(decimal.Parse(data[1])); high.Add(decimal.Parse(data[2])); low.Add(decimal.Parse(data[3])); close.Add(decimal.Parse(data[4])); } for (int i = 0; i < date.Count - 4; i++) { if (open[i] > high[i + 1] && close[i] < low[i + 1]) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Pivot downside {0}", date[i].ToShortDateString()); } if (open[i] < low[i + 1] && close[i] > high[i + 1]) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Pivot upside {0}", date[i].ToShortDateString()); } } } }

Business logic doesn’t present itself as no abstractions (only primitive abstrations)

The Big Encapsulation

Break up procedures into Methods

Higher density of information

class Program { static void Main(string[] args) { const string filename = "msft.csv"; var ana = new StockQuoteAnalyzer(filename); ana.LoadQuotes(); ana.AnalyzeQuotes(); } } class StockQuoteAnalyzer { private readonly string _filename; readonly List<DateTime> _date = new List<DateTime>(); readonly List<decimal> _open = new List<decimal>(); readonly List<decimal> _high = new List<decimal>(); readonly List<decimal> _low = new List<decimal>(); readonly List<decimal> _close = new List<decimal>(); public StockQuoteAnalyzer(string filename) { _filename = filename; } public void LoadQuotes() { var lines = File.ReadAllLines(_filename); for (int i = 1; i < lines.Length; i++) { var data = lines[i].Split(','); _date.Add(DateTime.ParseExact(data[0], "M/d/yyyy", CultureInfo.InvariantCulture)); _open.Add(decimal.Parse(data[1])); _high.Add(decimal.Parse(data[2])); _low.Add(decimal.Parse(data[3])); _close.Add(decimal.Parse(data[4])); } } public void AnalyzeQuotes() { for (int i = 0; i < _date.Count - 4; i++) { if (_open[i] > _high[i + 1] && _close[i] < _low[i + 1]) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Pivot downside {0}", _date[i].ToShortDateString()); } if (_open[i] < _low[i + 1] && _close[i] > _high[i + 1]) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Pivot upside {0}", _date[i].ToShortDateString()); } } } }

Defining classes to separate rules and responsibilities.. http://www.wirfs-brock.com/DesignBooks.html

Object responsibilities and roles – keep separated:

  • Knowing
  • Deciding
  • Doing

Little Abstractions

6 classes now instead of 2

Is this too much – a big problem in design!  If its a throwaway program, then yes.

  • KISS
  • YAGNI

Design should be iterative, and driven by immediate needs.  Some consideration for what's going to change in the future.  Concrete use/test cases are good.

Replacing dot net primitives, with own abstractions..

Separate

  • Knowing (domain) eg StockQuote encapsulates knowledge (including compares)
  • Deciding (business logic) eg Analyzer, ReversalLocator
  • Doing (input, output to screen etc..)

StockQuoteAnalyzer isn’t tied to the ConsoleApp anymore. Can be used in webapp, service etc..

image

11/14/2004 look for.

image
Opened above the previous high, and below the previous low.

Inheritance

Template method pattern (abstract base class)

But it tightly binds things together.  Bad. Harder to make changes.

Interfaces

A class can implement multiple interfaces.

Directional Dependencies

Passing in a dependency

Modern OOP

  • Encapsulation is king
  • Interfaces and composable
  • Small abstractions are powerful
| | # 
# Wednesday, 15 October 2014

Language Integrated Query
LINQ provides a general purpose query facility

MS… IEnumerable<T>

static void Main() { // Can hide anything behind IEnumerable eg a database // doesn't define interesting methods.. so MS added extension methods IEnumerable<string> cities = new[] { "Ghent", "London", "Las Vegas", "Hyderbad" }; foreach (var city in cities) { Console.WriteLine(city); } }


Utility class - old way of doing it:

class Program { static void Main() { var date = new DateTime(2002, 8,9); int daysTillEndOfMonth = DateUtilities.DaysToEndOfMonth(date); Console.WriteLine(daysTillEndOfMonth); } } public static class DateUtilities { public static int DaysToEndOfMonth(DateTime date) { return DateTime.DaysInMonth(date.Year, date.Month) - date.Day; } }

By adding this we have an extension method.

class Program { static void Main() { var date = new DateTime(2002, 8,9); // Using an extension method int daysTillEndOfMonth = date.DaysToEndOfMonth(); Console.WriteLine(daysTillEndOfMonth); } } public static class DateUtilities { public static int DaysToEndOfMonth(this DateTime date) { return DateTime.DaysInMonth(date.Year, date.Month) - date.Day; } }

Compiler trick.  Makes the syntax nice. Extension method needs to be in the same namespace.

using System; using System.Collections.Generic; using Extensions; namespace Grades { class Program { static void Main() { // Can hide anything behind IEnumerable eg a database // doesn't define interesting methods.. so MS added extension methods IEnumerable<string> cities = new[] { "Ghent", "London", "Las Vegas", "Hyderbad" }; // Take this datasource, and give me all citites that start with L IEnumerable<string> query = cities.StringThatStartsWith("L"); foreach (var city in query) { Console.WriteLine(city); } } } } namespace Extensions { public static class FilterExtensions { // Extension method for IEnumerable<string> // Data source is IEnumerable<string> public static IEnumerable<string> StringThatStartsWith(this IEnumerable<string> input, string start) { foreach (var s in input) { if (s.StartsWith(start)) { // builds an IEnumerable yield return s; } } } } }

Implementing a simple extension method on IEnumerable<string>
This is the way that LINQ operators are defined.
static void Main() { // Can hide anything behind IEnumerable eg a database // doesn't define interesting methods.. so MS added extension methods IEnumerable<string> cities = new[] { "Ghent", "London", "Las Vegas", "Hyderbad" }; // A very generic operator..need to look at lambda expressions. cities.Where() // Take this datasource, and give me all citites that start with L IEnumerable<string> query = cities.StringThatStartsWith("L"); foreach (var city in query) { Console.WriteLine(city); } }

Lambda Expressions

Making more flexible with a delegate.. So can have an IEnumerable<T>

class Program { static void Main() { IEnumerable<string> cities = new[] { "Ghent", "London", "Las Vegas", "Hyderbad" }; // More flexible, as have a Filter method that can take delegates // that point to other things IEnumerable<string> query = cities.Filter(StringTheStartWithL); foreach (var city in query) { Console.WriteLine(city); } } static bool StringTheStartWithL(string s) { return s.StartsWith("L"); } } public static class FilterExtensions { public static IEnumerable<T> Filter<T> (this IEnumerable<T> input, FilterDelegate<T> predicate) { // foreach item in the input, invoke the predicate (method) // if predicate returns true, add to IEnumerable returning foreach (var item in input) { if (predicate(item)) { // builds an IEnumerable yield return item; } } } } public delegate bool FilterDelegate<T>(T item);


A more flexible approach than writing an extension method for each case
// C#2 Anonymous delegate IEnumerable<string> query = cities.Filter(delegate(string item) { return item.StartsWith("L"); });

This does exactly the same – don’t need a named method.  Can inline it.  A delegate calling an anonymous method.

Goes to operator

// Lambda expression.. LHS is signature of the method (takes a string - type inference) // Body returns a bool of item.StartsWith("L") IEnumerable<string> query = cities.Filter(item => item.StartsWith("L")); foreach (var city in query) { Console.WriteLine(city); }

Lambdas are the way to write delegates in C#3 and above

Func

Passing around small snippets of information to express how to perform an operation – very interesting!

Func is a generic type which encapsulates delegates (callable code)

// Delegate that takes an integer as a parameter, and returns a bool //Func<int, bool> Func<int, int> square = x => x * x; // Parameters requied for 0 or 2+ parameters Func<int, int, int> add = (x, y) => x + y; Console.WriteLine(square(3)); Console.WriteLine(add(3,4)); // Action is just like Func with no return value Action<int> write = x => Console.WriteLine(x); write(16);


Great thing about Func is we no longer need to define delegates
public static class FilterExtensions { // By using Func<T,bool> we don't need to define a delegate public static IEnumerable<T> Filter<T> (this IEnumerable<T> input, Func<T,bool> predicate) { // foreach item in the input, invoke the predicate (method) // if predicate returns true, add to IEnumerable returning foreach (var item in input) { if (predicate(item)) { // builds an IEnumerable yield return item; } } } public static IEnumerable<T> Filterx<T> (this IEnumerable<T> input, FilterDelegate<T> predicate) { // foreach item in the input, invoke the predicate (method) // if predicate returns true, add to IEnumerable returning foreach (var item in input) { if (predicate(item)) { // builds an IEnumerable yield return item; } } } } public delegate bool FilterDelegate<T>(T item);

Using the inbuilt extension method which is just like above using a Func<T>
IEnumerable<string> query = cities.Where(city => city.StartsWith("L")) .OrderByDescending(city => city.Length);

Start of Funcs and Expressions.

| | # 
( c# )

3 Pillars of OOP

  • Encapsulation – most important.  Hides complexity. Methods encapsulate, Classes encapsulate.. build modules
  • Inheritance – Overrated for code reuse.  Can make hard to change.  Abstract Classes/Interfaces make better.
  • Polymorphism - Overrated for code reuse

Inheritance

Inherits behaviour/members from another class.  Can only inherit from a single class.  Chain is unlimited.

1 Class derives from another.

ctors will not be inherited.

image

class ThrowAwayGradeBook : GradeBook { public ThrowAwayGradeBook(string name) : base(name) { Console.WriteLine("throwaway ctor"); } }

and the base:
public class GradeBook { public GradeBook(string name = "There is no name") { Name = name; grades = new List<float>(); Console.WriteLine("gradebook ctor"); }

Interesting that the base classes ctor is called first.
GradeBook book = new ThrowAwayGradeBook("Scott's book");

This means that the methods we’d invoke on book eg book.ComputeStatistics would be the GradeBook Class, no the ThrowAwayGradeBook Class.  Needs to be ThrowAwayGradeBook type.

Polymorphism

Many shapes. ThrowAwayGradeBook “Is a” GradeBook

with virtual defined as type of Object (runtime).. type of variable

GradeBook book = new ThrowAwayGradeBook("Scott's book");

Make it virtual
public virtual GradeStatistics ComputeStatistics() { Console.WriteLine("Gradebook compute"); GradeStatistics stats = new GradeStatistics();

and override
public override GradeStatistics ComputeStatistics(){ Console.WriteLine("Throwaway compute"); float lowest = float.MaxValue; foreach (var grade in grades){ lowest = Math.Min(lowest, grade); } grades.Remove(lowest); return base.ComputeStatistics(); }

So then true polymorphic behaviour.

Abstract Classes

Abstract classes cannot be instantiated.. eg want a base type.  Can define members
eg public string Title {get;set;}
public virtual void Draw() { // .. }
public abstract void Open();

A concrete type.. Open needs to be there.

A more pure type.. an abstract type.. of GradeTrackers.

GradeTracker book = CreateGradeBook();

then

private static GradeTracker CreateGradeBook() { GradeTracker book = new ThrowAwayGradeBook(); return book; }

Where GradeTracker is an Abstract class:

public abstract class GradeTracker{ public abstract void AddGrade(float grade); public abstract GradeStatistics ComputeStatistics(); public abstract void WriteGrades(TextWriter textWriter); public string Name { get { return _name; } set { if (String.IsNullOrEmpty(value)) { throw new ArgumentException("Name cannot be null or empty"); } if (_name != value) { var oldValue = _name; _name = value; // Announce to world that something has changed if (NameChanged != null) { var args = new NameChangedEventArgs { OldValue = oldValue, NewValue = value }; // Invoke the delegate NameChanged(this, args); } } } } public event NameChangedDelegate NameChanged; private string _name; }

image

Interfaces

  • Interfaces contain no implementation detail
  • A type can implement multiple interfaces (whereas with an abstract you can’t)

Any object which implements this interface is guaranteed to the have members this interfaces defines.

public interface IGradeTracker { void AddGrade(float grade); GradeStatistics ComputeStatistics(); void WriteGrades(TextWriter textWriter); string Name { get; set; } event NameChangedDelegate NameChanged; void DoSomething(); }

Important Interfaces

  • IDisposable – releases resources (files, connections)
  • IEnumerable – supports iteration
  • INotifyPropertyChange – raises events wehn properties change
  • IComparable – compares for sorting

Implementing IEnumerable so that can iterate over the object

public interface IGradeTracker : IEnumerable { void AddGrade(float grade); GradeStatistics ComputeStatistics(); void WriteGrades(TextWriter textWriter); string Name { get; set; } event NameChangedDelegate NameChanged; void DoSomething(); }

Then abstract it down:

public abstract class GradeTracker : IGradeTracker { public abstract void AddGrade(float grade); public abstract GradeStatistics ComputeStatistics(); public abstract void WriteGrades(TextWriter textWriter); public string Name { get { return _name; } set { if (String.IsNullOrEmpty(value)) { throw new ArgumentException("Name cannot be null or empty"); } if (_name != value) { var oldValue = _name; _name = value; // Announce to world that something has changed if (NameChanged != null) { var args = new NameChangedEventArgs { OldValue = oldValue, NewValue = value }; // Invoke the delegate NameChanged(this, args); } } } } public event NameChangedDelegate NameChanged; public abstract void DoSomething(); private string _name; public abstract IEnumerator GetEnumerator(); }

then

public class GradeBook : GradeTracker { public GradeBook(string name = "There is no name") { Name = name; grades = new List<float>(); Console.WriteLine("gradebook ctor"); } public override void AddGrade(float grade) { if (grade >= 0 && grade < 100) { grades.Add(grade); } } public override GradeStatistics ComputeStatistics() { Console.WriteLine("Gradebook compute"); var stats = new GradeStatistics(); float sum = 0f; foreach (float grade in grades) { stats.HighestGrade = Math.Max(grade, stats.HighestGrade); stats.LowestGrade = Math.Min(grade, stats.LowestGrade); sum += grade; } stats.AverageGrade = sum / grades.Count; return stats; } public override void WriteGrades(TextWriter textWriter) { textWriter.WriteLine("Grades:"); int i = 0; do { textWriter.WriteLine(grades[i]); i++; } while (i < grades.Count); } public override void DoSomething() { throw new NotImplementedException(); } public override IEnumerator GetEnumerator() { return grades.GetEnumerator(); } // Backing field (private) protected List<float> grades; }

So when iterate over a GradeBook will get back the grades.
| | # 
# Tuesday, 14 October 2014
( c# )

Branching

int age = 20; // Conditional operator or ternary operator // 1st has to return true or false string pass = age > 20 ? "pass" : "no pass";

Switching

default path is optional

type: ints, char, strings, enums

But can’t do AverageGrade >= 90…

char – have to use single quotes… struct so a value type.

Iterating

4 ways

  • foreach (arrays or collections)
  • for (initializer, condition, iterator)
  • Do (always runs at least once)
  • while (condition is checked before..)

Jumping

  • break – would break out of a foreach
  • continue – would skip anthing after that in a foreach loop
  • goto – jump to a label
  • return – can return in a void method!
  • throw – throw an exception

Exceptions

Should be exceptional, ie not normal program flow eb bad input value

eg throw new ArgumentException(“21 is not valid”)

public string Name { get { return _name; } set { if (String.IsNullOrEmpty(value)) { throw new ArgumentException("Name cannot be null or empty"); } if (_name != value) { var oldValue = _name; _name = value; // Announce to world that something has changed if (NameChanged != null) { var args = new NameChangedEventArgs { OldValue = oldValue, NewValue = value }; // Invoke the delegate NameChanged(this, args); } } } }

Stack

image

Data structure… every time call a method we push it onto the stack.. and finished we pull off the stack.
So we go up the stack to the calling Program.cs at line 11 which passed in an illegal value (null)

Common Exceptions

ArgumentException
ArgumentNullException – a null ref is passed to a method that does not allow nulls
NullReferenceException – if a variable doesn’t point to an object..

Handling Exceptions

try
catch

Exceptions travel back up the call stack

putting a text file in a project.  Copy to output directory: Copy if newer

try{ string[] lines = File.ReadAllLines("grades.txt"); foreach (string line in lines){ float grade = float.Parse(line); book.AddGrade(grade); } } catch (FileNotFoundException ex){ Console.WriteLine("Could not locate the file grades.txt"); return; } catch (UnauthorizedAccessException ex){ Console.WriteLine("No access"); return; }

Or lower level:

C# variables are block scoped.

FileStream stream = null; StreamReader reader = null; try { book = new GradeBook(); stream = File.Open("grades.txt", FileMode.Open); reader = new StreamReader(stream); string line = reader.ReadLine(); while (line != null) { float grade = float.Parse(line); book.AddGrade(grade); line = reader.ReadLine(); } } catch (FileNotFoundException ex) { Console.WriteLine("Could not locate the file grades.txt"); return; } catch (UnauthorizedAccessException ex) { Console.WriteLine("No access"); return; } // If an unmanager resource eg database, network, windows resource // memory is managed so that will be GC'd finally { if (reader != null) { reader.Close(); } if (stream != null) { stream.Close(); } }

Or with a using:
GradeBook book; try { book = new GradeBook(); // Using will call Dispose method // compiler will tell you if doesn't implement IDispose using (FileStream stream = File.Open("grades.txt", FileMode.Open)) using (StreamReader reader = new StreamReader(stream)){ string line = reader.ReadLine(); while (line != null){ float grade = float.Parse(line); book.AddGrade(grade); line = reader.ReadLine(); } } } catch (FileNotFoundException ex) { Console.WriteLine("Could not locate the file grades.txt"); return; } catch (UnauthorizedAccessException ex) { Console.WriteLine("No access"); return; }

Stacking of the usings.

Custom Exceptions

Useful for business problems eg InvalidAccountException

Derive from Exception

Use an exception suffix.

| | # 
( c# )

http://blog.pluralsight.com/learning-path-c-microsoft-exam-70-483

http://pluralsight.com/courses/table-of-contents/csharp-fundamentals-csharp5

.NET Framework

CLR - Common Language Runtime (similar to the JVM) - runs/manages your application

Don’t need to worry about what kind of machine

FCL - Framework Class Library - software components to build applications

A library of

Eg desktop apps here

ASP.NET

WCF

BCL - Base Class Library (subset of FCL)

C# - just one language

clip_image001

clip_image002

MSIL - MS Intermediate Language

The CLR reads IL into Native instructions

Classes

A class is a blueprint for creating objects

Class Members

  • State
  • Behaviour (typically Methods)

Float -single precision floating point number.. 7 digits

Double - double .. 16digits

class Program { static void Main(string[] args) { // Currently using an implicit ctor var book = new GradeBook(); // ints implicity convert to floating point number book.AddGrade(5); // default type is a double.. and cant convert to a float as would lose precision //book.AddGrade(89.5); // tell compiler that this is a float book.AddGrade(89.1f);   // So there is no variable pointing to the first GradeBook object which is in memory, it is garbage var book2 = new GradeBook(); book2.AddGrade(75); } }   class GradeBook { public GradeBook() { grades = new List<float>(); }   public void AddGrade(float grade) { grades.Add(grade); }   // Field using Field Initialiser Syntax.. which calls the List ctor ie () //private List<Float> grades = new List<Float>(); // Same as doing it in the ctor private List<float> grades; }  

Can use F10 to start a debug on first line!

A class is a blueprint for creating objects

A class can also be used to type a variable eg GradeBook

Ctrl-F10 - Run to Cursor.. Brilliant!

Classes - what you use to instantiate Objects, Classes are what you use to Type a Variable

Objects -

Variables - Store things. A Field is a variable, just inside a Class. A variable can point to an Object

Reference Types

Classes are reference types

Variables point to objects, they don't 'hold' the objects

2 variables pointing to the same object

OOP

Class names are usually Nouns eg GradeBook

Methods are usually Verbs eg AddGrade

Encapsulation - enclosing (perhaps hiding) certain details of how the software works

Encapsulation (hiding..or surrounding)

Reduce complexity of an application by creating more classes

static void Main(string[] args) { var book = new GradeBook(); book.AddGrade(5); book.AddGrade(89.1f);   GradeStatistics stats = book.ComputeStatistics(); } }   class GradeStatistics {}   class GradeBook { //ctors public GradeBook() { grades = new List<float>(); }   //methods public void AddGrade(float grade) { grades.Add(grade); }   public GradeStatistics ComputeStatistics() { return new GradeStatistics(); }   //fields List<float> grades; }

Access Modifiers eg public/private (eg hide from other programmers)

Static - apply to a method or a field… don't need to create an instance

Console.WriteLine is a static method.

Reference Types

Eg a reference or a pointer to an object / Class

GradeBook g1 = new GradeBook(); GradeBook g2 = g1; //g1 = new GradeBook(); g1.Name = "Scott's book"; Console.WriteLine(g2.Name);

Pointers. If we uncomment, then no output is shown.

Values Types

Eg int (or Int32 synonym) holds the value, double, floats, DateTime

They are faster!

Most primitive types are values.

Typically immutable

int x1 = 4; // Will copy the value from x1 into x2 int x2 = x1; x1 = 100; // Will print 4 Console.WriteLine(x2);

Method Parameters

Pass by value by default. Always passing a copy of the value.

 

static void GiveBookAName(GradeBook book) { book.Name = "The Gradebook"; }   static void Main(string[] args) { // Reference type GradeBook g1 = new GradeBook(); // Both g1 and g2 have a pointer to the same Gradebook GradeBook g2 = g1;   // Doesn't matter if a Value or Ref type, always pass by value (the value is a pointer to the object) GiveBookAName(g2); Console.WriteLine(g1.Name);

Now lets look at ints

static void IncrementNumber(int number) { // number is a copy of the value passed in. number += 1; }   static void Main(string[] args) { // Reference type GradeBook g1 = new GradeBook(); // Both g1 and g2 have a pointer to the same Gradebook GradeBook g2 = g1;   // Doesn't matter if a Value or Ref type, always pass by value (the value is a pointer to the object) GiveBookAName(g2); Console.WriteLine(g1.Name);   // int is a value type int x1 = 4; // always pass by value and copy into variable number up above IncrementNumber(x1); // will print 4 Console.WriteLine(x1);

IncrementNumber will not change x1

Rarely if ever used these keywords: ref

// Pass by reference static void GiveBookAName(ref GradeBook book) { book = new GradeBook(); book.Name = "The New Gradebook"; }   static void IncrementNumber(ref int number) { number += 1; }   static void Main(string[] args) { // Reference type GradeBook g1 = new GradeBook(); // Both g1 and g2 have a pointer to the same Gradebook GradeBook g2 = g1;   // So the value of g2 can be changed (The New Gradebook) // when passing by value, the value can't be changed but the object it points to can be. GiveBookAName(ref g2); Console.WriteLine(g2.Name);   // int is a value type int x1 = 4; IncrementNumber(ref x1); // will print 5 Console.WriteLine(x1);

Ref assumes the variable being passed in has already been initialised, and doesn't need to assign anything to it

Out(put) - doesn't need to be assigned first, has to make as assignment

Better way is to have a return value!

Struct

A class definition is a reference type

A struct(ure) is a value type

Struct as meant as special cases eg DateTime

A single value..

Enum

An Enum(eration) creates a value type

 

How can you tell if a Reference Type or Value Type?

F12 go to definition:

clip_image009

DateTime: A struct so it’s a value type.

clip_image010

Int (alias for Int32) A struct so it’s a value type.

clip_image011

Using metadata as documentation to find out what DateTime.Month will return

clip_image012

Enum is a value Type

| | # 
# Monday, 13 October 2014
( c# | Delegate | Events )
  • Allows a class to send notifications to other classes or objects
    • Publisher raises the event
    • One or more subscribers process the event

eg Button –> click –> subscriber1, subscriber2

Events are based on delegates

Delegates

  • I need a variable that references a method
  • A delegate is a type that references methods (just like a class or struct)
    • public delegate void Writer(string message);

Delegates can be very useful.

// The type public delegate void NameChangedDelegate(string oldValue, string newValue); static void Main() { // NameChanged variable references a method OnNameChanged NameChangedDelegate NameChanged = new NameChangedDelegate(OnNameChanged); NameChanged("old", "new"); } // This method will execute when a private static void OnNameChanged(string oldvalue, string newvalue) { Console.WriteLine("Name changed from {0} to {1}", oldvalue, newvalue); }

and..

public delegate float RateDelegate(float a); private static float OnRate(float a) { throw new NotImplementedException(); } static void Main() { //RateDelegate rate = new RateDelegate(OnRate); // rate is a delegate variable RateDelegate rate; rate = (float a) => a*2; float x = 2f; float y = rate(x); float yy = rate(x);

Interesting code showing a delegate type being assigned to a method, and anonymous method.

 

eg want to know what

multiple subscribers to listen.. this is what events are for.

// Backing field (private) private string _name; public string Name { get { return _name; } set { if (_name != value) { var oldValue = _name; _name = value; // Announce to world that something has changed if (NameChanged != null) { // It has no idea what will be called, only that the signature will be string oldValue, string newValue NameChanged(oldValue, value); } } } } // Field of type NameChangedDelegate public NameChangedDelegate NameChanged;

Type:
public delegate void NameChangedDelegate(string oldValue, string newValue);

Listeners:
{ //... // Hooking up the delegate to point to another method // Setting the public Field (of type NameChangedDelegate) to a new delegate and passing the method // however anyone else can overwrite this //book.NameChanged = new NameChangedDelegate(OnNameChanged); // multicast delegate book.NameChanged += OnNameChanged; book.NameChanged += OnNameChanged; book.NameChanged += OnNameChanged2; // ahh would wipe out the previous ones book.NameChanged = new NameChangedDelegate(OnNameChanged2); book.Name = "Allen's Book"; WriteNames(book.Name); Console.WriteLine(stats.AverageGrade); Console.WriteLine(stats.LowestGrade); Console.WriteLine(stats.HighestGrade); } private static void OnNameChanged2(string oldvalue, string newvalue) { Console.WriteLine("***"); } // This method will execute when a private static void OnNameChanged(string oldvalue, string newvalue) { Console.WriteLine("Name changed from {0} to {1}", oldvalue, newvalue); }

Notice the error above – wipes out the previous method delegate calls.

Next to use an event – prevent wiping out subscribers.

Events

Events are just delegates. 0:11 of 8:35

class Program { // The type public delegate void NameChangedDelegate(string oldValue, string newValue); static void Main() { // NameChanged variable references a method OnNameChanged NameChangedDelegate nameChanged = new NameChangedDelegate(OnNameChanged); nameChanged("old", "new"); } // This method will execute when a private static void OnNameChanged(string oldvalue, string newvalue) { Console.WriteLine("Name changed from {0} to {1}", oldvalue, newvalue); } }

Here is the working code with a delegate

class Program2 { // The type public delegate void NameChangedDelegate(string oldValue, string newValue); public static event NameChangedDelegate NameChanged; static void Main() { // NameChanged variable references a method OnNameChanged NameChanged += new NameChangedDelegate(OnNameChanged); NameChanged("old", "new"); } private static void OnNameChanged(string oldvalue, string newvalue) { Console.WriteLine("Name changed from {0} to {1}", oldvalue, newvalue); } }

Same with an Event.

class Program3 { public delegate void NameChangedDelegate(object sender, NameChangedEventArgs e); public static event NameChangedDelegate NameChanged; static void Main() { // NameChanged variable references a method OnNameChanged NameChanged += new NameChangedDelegate(OnNameChanged); //Convention in events: never pass arbitrary params NameChanged(null, new NameChangedEventArgs {OldValue = "old", NewValue = "new"}); } private static void OnNameChanged(object sender, NameChangedEventArgs e) { Console.WriteLine("Name changed from {0} to {1}", e.OldValue, e.NewValue); } } public class NameChangedEventArgs : EventArgs { public string OldValue { get; set; } public string NewValue { get; set; } }

Event using EventArgs (convention).  Using a static method so had to pass null instead of this.

 

Syntactically the same

public event NameChangedDelegate NameChanged;
No longer legal to assign to an event (which wiped out previous method delegate calls above)

Thats what special about events – needs a += or –= assignment

public class NameChangedEventArgs : EventArgs { public string OldValue { get; set; } public string NewValue { get; set; } }

Derives from EventArgs
public delegate void NameChangedDelegate(object sender, NameChangedEventArgs args);
 
private static void OnNameChanged(object sender, NameChangedEventArgs args){ Console.WriteLine("Name changed from {0} to {1}", args.OldValue, args.NewValue); }
Convention in events: never pass arbitrary params.. sender (eg gradebook) itself, then object that encapsulates other stuff

Members

Members are used to craft an abstraction

  • Fields and properties for state
  • Methods for behaviour
  • Events for notification
| | # 
# Friday, 10 October 2014
( c# )

From K Scott Allen, Pluralsight C#5 video

Methods – define behaviour

  • Access modifier eg public
  • Return type eg void
  • Name eg WriteAsBytes
  • Parameters eg int value

Params takes a variable number of arguments
Signature – Name, and number and types of parameters – method overloading is having multiple methods same name, but different signatures (return type is not in signature)

Formatting options eg X (hex)

static void Main(string[] args) { WriteBytes(22f); } private static void WriteBytes(float value) { byte[] bytes = BitConverter.GetBytes(value); foreach (var b in bytes) { Console.Write("0x{0:X} ", b); } Console.WriteLine(); }

Talking about method overloading in GetBytes which has 10 different overloads.

Overloading WriteBytes

Params

   Console.Write("0x{0:X} {2} {1} ", b, "Dave", "Mateer");
Console.Write("0x{0:X} {2} {1} ", b, "Dave", "Mateer");

How does Console.Write know how many overloads?

image
Because of params array of objects

static void Main(string[] args) { int number = 20; WriteBytes(number); WriteBytes(22f); WriteNames("Dave","Bob", "Alan"); } private static void WriteNames(params string[] names){ foreach (var name in names){ Console.WriteLine(name); } }

Could be useful – string formatting, passing to a logfile

Fields

Fields are variables of a class – typically private.

Readonly useful when only want the field changed in the ctor, or when you declare it.

Properties

Often use to expose and control fields.
Get and Set accessor

class GradeBook2 { // Field private string _name; // Auto implemented property (compiler makes a field) public string Address { get; set; } // Property - capitalised public string Name { get { return _name; } // Common use of set logic - validation set { // value is what someone else wants to write into your property if (!String.IsNullOrEmpty(value)) { _name = value; } } }

then
public GradeBook() { grades = new List<float>(); } public GradeBook(string name){ grades = new List<float>(); Name = name; }

Overload a ctor, but duplicated code.. so a better way is:

public GradeBook() : this("No name") { } public GradeBook(string name) { grades = new List<float>(); Name = name; }

Or in C#4 default value of parameter

public GradeBook(string name = "No name") { grades = new List<float>(); Name = name; }


Can have a readonly property

Difference between Field and Property

Property allows validation code on incoming values
Some bit egs serialization, databinding (moving data from an object to a control on the screen) only work with props

Typically expose data through props

| | # 
# Thursday, 09 October 2014
( c# )

Types live in assemblies

Reference Types

Classes
string (but behaves like a value type – it is immutable)
Arrays

Value Types

int (Int32)
Struct
DateTime (Struct)

Immutability

Value types are immutable (can’t change)

string (as some strings can be quite large, that is a reason for having it as a value type).  But behaves like a value type in many ways eg immutable

class Program {
    static void Main(string[] args)
    {
        Immutable();
        //PassByValueAndRef();
    }

    private static void Immutable()
    {
        // Value Type
        DateTime date = new DateTime(2002, 9, 11);
        // this wont do anything
        date.AddDays(1);
        // need to assign the return (as date is immutable)
        date = date.AddDays(1);
        Console.WriteLine(date);

        // string is a reference type but behaves like a value type eg immutable
        string name = " Scott ";
        // does nothing
        name.Trim();
        name = name.Trim();
        Console.WriteLine(name);


    }
}

Assemblies

Assemblies are .exe or .dll

GAC – Global Assembly Cache.  A central location to store assemblies.  eg common types like string, etc..

image
All the types that are references in this console app.

Note mscorlib (which holds string, Int32 etc…) is not in the references list.. difficult to write a program without it!

image
Referenced System.Speech.
Asemblies 6:37

SpeechSynthesizer synth = new SpeechSynthesizer();
synth.Speak("Hello world!");

| | # 
# Monday, 24 February 2014
# Thursday, 20 February 2014
( c# | SQL )

"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached."

Useful to see where the app pool connections are coming from:

--exec sp_who
exec sp_who2

http://stackoverflow.com/questions/670774/how-can-i-solve-a-connection-pool-problem-between-asp-net-and-sql-server

The issue I had was code not wrapped in a using..so it wasn’t calling a connection.close().

| | # 
# Monday, 12 August 2013
( c# )

http://msmvps.com/blogs/jon_skeet/

https://github.com/jskeet/DemoCode 

and needed http://www.yoda.arachsys.com/csharp/miscutil/ to get it to compile.

Used Async / Await to do a nefarious goto style program (Basic-esque).  .NET4.5 using C#5

image

Useful bit of code which sets the entry point of the application based on what you press here.

image

The trick…

Using the operator keyword… and implicit keyword.. to do things like

foo = + foo

this would new up a foo class.

| | # 
# Thursday, 01 August 2013
( c# | SQL )

        static void Main(string[] args)
        {
            string text = File.ReadAllText(@"e:\temp\query.sql");

            string text2 = "";

            //split by /r/n - ie line
            var allLines = text.Split('\n');
            for (int i = 0; i < allLines.Length-1; i++)
            //for (int i = 0; i < 3000; i++)
            {
                var line = allLines[i].Trim();

                var bits = line.Split('\'');

                var value1 = bits[1];
                var value2 = bits[3];
                var value3 = bits[5];

                var message ="INSERT [PreStaging].[Import_AccountEmployeeMapping] ([AccountName], [EmployeeID], [UER2_PlatformID]) VALUES (N" +
                            "'" + value1 + "', "
                            + value2 + ", "
                            + value3 + ")";

                text2 += message + Environment.NewLine;

                if (i % 1000 == 0) Console.WriteLine(i);
            }
           
            File.WriteAllText(@"e:\temp\query2.sql", text2);
        }

A C# console application.

| | # 
# Tuesday, 21 May 2013
( c# )

Some interesting code:  Why does cc get magically changed?

public const int N = 10;

        static void Main(string[] args)
        {
            int[] a = new int[N];
            int[] b = new int[N];
            int[] cc = new int[N];

            // fill the arrays 'a' and 'b' on the CPU
            for (int i = 0; i < N; i++)
            {
                a[i] = -i;
                b[i] = i * i;
            }

            // why is cc being returned without an out param, or a return type from the method
            // is it int[] reference value type?

            // passing a reference type parameter by value.  Parameter cc is a reference to the array
            // it is possible to change the elements of cc from within add method
            // a copy of the reference cc is passed to the method
            add(a, b, cc);

            // display the results
            for (int i = 0; i < N; i++)
            {
                Console.WriteLine("{0} + {1} = {2}", a[i], b[i], cc[i]);
            }
        }

        static void add(int[] a, int[] b, int[] c)
        {
            int tid = 0;    // this is CPU zero, so we start at zero
            while (tid < N)
            {
                c[tid] = a[tid] + b[tid];
                tid += 1;   // we have one CPU, so we increment by one
            }
        }

Passing reference type by value

Or we could pass reference type by reference:

public const int N = 10;

        static void Main(string[] args)
        {
            int[] a = new int[N];
            int[] b = new int[N];
            int[] cc = new int[N];

            // fill the arrays 'a' and 'b' on the CPU
            for (int i = 0; i < N; i++)
            {
                a[i] = -i;
                b[i] = i * i;
            }

            // why is cc being returned without an out param, or a return type from the method
            // is it int[] reference value type?

            // passing a reference type parameter by value.  Parameter cc is a reference to the array
            // it is possible to change the elements of cc from within add method
            // a copy of the reference cc is passed to the method
            add(a, b, ref cc);

            // display the results
            for (int i = 0; i < N; i++)
            {
                Console.WriteLine("{0} + {1} = {2}", a[i], b[i], cc[i]);
            }
        }

        static void add(int[] a, int[] b, ref int[] c)
        {
            int tid = 0;    // this is CPU zero, so we start at zero
            while (tid < N)
            {
                c[tid] = a[tid] + b[tid];
                tid += 1;   // we have one CPU, so we increment by one
            }
        }

A good explanation is on http://msdn.microsoft.com/en-us/library/0f66670z(v=vs.71).aspx

| | # 
# Tuesday, 20 November 2012
( c# )

    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hello");
            var text = File.ReadAllText(@"e:\stuff.txt");

            //split by /r/n
            var allNames = text.Split('\n');
            for (int i = 0; i < allNames.Length; i++)
            {
                allNames[i] = allNames[i].Trim();
            }

            //split into firstname and lastname
            var list = new List<Person>();
            for (int i = 0; i < allNames.Length; i++)
            {
                Person person = new Person();
                var listOfNameBits = allNames[i].Split(' ');
                string first = listOfNameBits[0].ToString();
                string last = listOfNameBits[1].ToString();

                person.FirstName = first;
                person.LastName = last;
                list.Add(person);
            }

            string text2 = "";
            foreach (var p in list)
            {
                text2 += p.FirstName + "," + p.LastName + Environment.NewLine;
            }

            File.WriteAllText(@"e:\stuff2.csv", text2);
        }
    }

Taking a text file of names, and splitting into firstName, lastName then writing back to disk as a CSV.

| | # 
# Tuesday, 05 June 2012
( c# | Recursion )

recursion is a function that calls itself iteratively until it reaches a stopping point

While exploring how to do Euler15 - http://stackoverflow.com/questions/2200236/project-euler-15

[Test]
public void DoSomething()
{
    int total = Recursive(5);
    Assert.AreEqual(10, total);
}

static int Recursive(int value)
{
    int valueToReturn = 0;
    if (value >= 10)
    {
        return value;
    }
    value++;
    //passes valueToReturn back 5 times from the output of 5 different calls to Recursive
    valueToReturn = Recursive(value);
    return valueToReturn;
}

http://www.dotnetperls.com/recursion

and to solve something a bit more complex:

Factorials – I like this example. http://www.mathdotnet.com/doc/IridiumCodeSamples.ashx?HL=factorial useful to check

[Test]
        public void FactorialTests()
        {
            int result = Factorial(4);
            Assert.AreEqual(24, result);
        }

        int counter = 0;

        private int Factorial(int number)
        {
            counter++;
            Console.WriteLine("{0}", counter);
            //if we've got to the place to start doing work..
            if (number == 0)
                return 1;
            int returnedValue = Factorial(number - 1);
            counter--;
            Console.WriteLine("{0}", counter);
            //first returnedValue will be 1.. number will be 1
            //second returnedValue will be 1.. number will be 2
            //third returnedValue will be 2..number will be 3
            //fourth retrunedValue will be 6...number will be 4

            int result = number*returnedValue;
            return result;
        }

and the easier to understand non factorial version:

[Test]
public void FactorialAsLoop_Given4_Return24()
{
    int result = FactorialAsLoop(4);
    Assert.AreEqual(24, result);
}

//loop
private int FactorialAsLoop(int number)
{
    //4*3*2*1
    for (int i = number-1; i >= 1; i--)
    {
        number = number*i;
    }
    return number;
}
| | #