Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Monday, 07 September 2015
( Action | Func | Functional )

Source is: https://github.com/djhmateer/Refactoring

The program does a:

  • Extract from a csv file of quotes
  • Transform using a ParseLine to split each line into a title and a quote
  • Load to insert into a database

Its a Console application designed to be run every night.  So just simple enough to really be able to explore techniques.  Based off http://mikehadlow.blogspot.co.uk/2015/08/c-program-entirely-with-static-methods.html

First Iteration which is using the blog post above’s architecture

// Functional style of the QuoteImporter app private static void Main() { // Compose the Functions together (without running them) Action run = () => QuoteImporter(ReadFileListOfLines, ParseLine, InsertQuoteIntoDatabase); run(); } // 1. Takes a Function with no input, which returns a list of strings // 2. Takes a Function with a string input, which returns a Quote // 3. Takes an Action with a Quote input public static void QuoteImporter( Func<IEnumerable<string>> readFileListOfLines, Func<string, Quote> parseLine, Action<Quote> insertQuoteIntoDatabase) { IEnumerable<string> lines = readFileListOfLines(); foreach (var line in lines) { var quote = parseLine(line); insertQuoteIntoDatabase(quote); } } // If there is a return type, then must be a Func<input, input..., output> public static IEnumerable<string> ReadFileListOfLines() { return File.ReadAllLines(@"..\..\quotesWithTitles.csv"); } public static Quote ParseLine(string line) { string[] values = line.Split(','); if (values.Length < 2) throw new ApplicationException("Unknown state - too few commas"); if (values.Length > 2) throw new ApplicationException("Unknown state - too many commas"); string title = values[0]; string body = values[1]; return new Quote { Title = title, Body = body }; } private static void InsertQuoteIntoDatabase(Quote quote) { string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Dev\Refactoring\Refactoring\Database1.mdf;Integrated Security=True"; using (var connection = new SqlConnection(connectionString)) { var cmd = new SqlCommand("INSERT INTO Quotes (Title, Text) VALUES (@Title, @Quote)"); cmd.Connection = connection; cmd.Parameters.AddWithValue("@Title", quote.Title); cmd.Parameters.AddWithValue("@Quote", quote.Body); connection.Open(); cmd.ExecuteNonQuery(); } }
| | # 
# 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);
| | # 
# Friday, 17 October 2014
( Expression | Func | Linq )

Linq provider with translate linq to SQL (for EF)

Expressions wrap a Func type.

static void Main() { var db = new MovieDB(); IEnumerable<Movie> query = // Lambda expression being passed in - how to filter db.Movies.Where(m => m.Title.StartsWith("Wal")) // Lambda expression - how to filter .OrderBy(m => m.ReleaseDate.Year); foreach (var movie in query) { Console.WriteLine(movie.Title); }
Then look at profiler:

SELECT [Project1].[ID] AS [ID], [Project1].[Title] AS [Title], [Project1].[ReleaseDate] AS [ReleaseDate] FROM ( SELECT DATEPART (year, [Extent1].[ReleaseDate]) AS [C1], [Extent1].[ID] AS [ID], [Extent1].[Title] AS [Title], [Extent1].[ReleaseDate] AS [ReleaseDate] FROM [dbo].[Movies] AS [Extent1] WHERE [Extent1].[Title] LIKE N'Wal%' ) AS [Project1] ORDER BY [Project1].[C1] ASC

Outer query for ordering.  Sub query for filtering – StartsWith “Wal”

How do these Func’s get translated into Expressions that go into SQL Server?

image

Ahh, not selected the extension method for IEnumerable.

Using IQueryable (which derives from IEnumerable).  But all remote linq providers implmement properties which are IQueryable.

No longer take a Func<T>, but an Expression<T>.  Where T is a Func<T>

image

Opaque – only tells us it takes an int, and returns an int.  Doesn’t really see what's inside of that method.

Expression – essentially when the extension method for IQueryable is doing.

write(square(add(1, 3)));

Invoking the square Func no longer works. (method delegate or event is expected)

image

In immediate window:

image

image

NodeType is multiple, left hand side is x, right hand side is x.  Value to produce is Int32.

Compiler doesn’t compile lambda expression to IL, but builds a data structure – an abstract syntax tree, that have objects inside that represent the operations that we have expressed in code.

Up to linq provider to take the data structure and figure out how to translate it.

Comprehension Query Syntax

var query2 = from m in db.Movies where m.Title.StartsWith("L") select m;

C# compiler translates this syntax into extension method calls.

var q2 = db.Movies.Where(x => x.Title.StartsWith("L")) .OrderBy(x => x) .Select(x => x);

Many of these LINQ oriented features are useful for everyday code

  • Functional programming
  • Reduced noise
| | # 
# 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.

| | #