Saturday, 2 July 2016
Friday, 31 October 2014
Monday, 13 October 2014
Example of DataRepository pattern
Here is a quick example of a data repository pattern used with EF. Note the UpdateEntity method in AccountRepository purely returns the entity to be updated, this perhaps should be named more clearly.
This example was taken from Miguel Castro and uses MEF as it's DI container.
Wednesday, 17 September 2014
Tuesday, 1 July 2014
QuickGraph: Modelling the London Underground in C#
In this example we model the London Underground, well more specifically the Victoria, Bakerloo and Circle lines.
We ask the question: what is the shortest path between Marylebone and Victoria?
This requires a change at Oxford Circus from the Bakerloo to Victoria line. Thanks to QuickGraph we can easily model the London underground as a graph.
The way this works is that we have our TrainLine and Station classes each populated with the relevant names. Each TrainLine has an ordered list of it’s Stations. We then loop through each of the TrainLines and their Stations to create a graph, adding “edges” between each of the stations. This map is then used by the library to calculate the shortest path. Source: https://github.com/stevenh77/QuickGraphExample/
Simple Many to Many design
A linked list would be a more logical representation of stations for a train line but for this example we’re using a list.
Sunday, 29 June 2014
DetectStale within a stream
The DetectStale<T> extension method within the Reactive Trader RX example application detects when a stream has stopped producing values and injects an IsStale indicator to allow the UI to react.
The idea is that while the stream is steadily providing values all is good. As soon as a value hasn’t been received within a set period of time, a new value is sent down the stream to say “this steam has gone stale”.
First here is an example of it being used within a test:
The DetectStale internally uses a timer to know whether it should be sending in effect an null/empty stale value. Here are another couple of tests for the DetectStale extension method: Here is the DetectStale code itself: You can the source subscription on line 42 calling the normal/expected OnNext method with the value. After that they call the scheduleStale method containing the timer with Stale / null value.
Monday, 23 June 2014
From Task to Rx to Streaming data
Here is a simple example of a ViewModel calling a LoadCustomers service:
public async Task LoadCustomers()Note: I’m using the PRISM extension method that allows for adding a range to an observable collection, giving less notifications. The error handling has been removed to focus on the code.
{
IsLoading = true;
Customers.Clear();
var customers = await services.GetAllCustomers();
Customers.AddRange(customers);
IsLoading = false;
}
Here’s the equivalent for Rx:
public async Task LoadCustomers()
{
IsLoading = true;
Customers.Clear();
services.GetAllCustomers().ToObservable()
.SubscribeOn(NewThreadScheduler.Default)
.ObserveOnDispatcher()
.Subscribe(
customers => Customers.AddRange(customers),
() => IsLoading = false);
}
The SubscribeOn extension method is ensuring the GetAllCustomers call is being made on a separate thread to keep the UI as free as possible. Once the response comes back, the ObserveOnDispatcher ensures the UI thread runs our Customers.AddRange code along with the IsLoading = false code which is running on the Observable OnCompleted event.
So any benefits from this? Not really. But imagine our GetAllCustomers wasn’t just a call to a web endpoint.
First we’ll remove the ToObservable() extension method and code up the observable ourselves so we understand what’s actually going on under the hood:
public async Task LoadCustomers()
{
IsLoading = true;
Customers.Clear();
var source = Observable.Create<IEnumerable<Customer>>(
async o =>
{
var response = await services.GetAllCustomers();
o.OnNext(response);
o.OnCompleted();
return Disposable.Empty;
});
source
.SubscribeOn(NewThreadScheduler.Default)
.ObserveOnDispatcher()
.Subscribe(
customers => Customers.AddRange(customers),
() => IsLoading = false);
}
Now if we start to require more work being done to retrieve data than just a web call, like perhaps converting DTOs to UI models, this can be done within the observable code. Remember this work is not being done on the UI thread so our app is nice and responsive.
Now imagine our services returned observables rather than DTOs or UI models:
public void LoadCustomers()
{
services.GetAllCustomers()
.SubscribeOn(NewThreadScheduler.Default)
.ObserveOnDispatcher()
.Subscribe(customers => Customers.AddRange(customers));
}
We now have a viewmodel that is dealing with observables and doesn’t care whether that data is coming from a web service call, file I/O or a Nirvana (Universal) endpoint that is streaming data.
Saturday, 7 December 2013
Using TPL to avoid callback hell
In this example, we fire off three service calls which individually have a continuation of converting the resultant DTO to a model object.
We then call a fourth service, to get the Spot which only fires once all the previous three service calls have completed and created their model object.
var tasks = new Task[]
{
services.GetAsTask<DTOs.MoneyMarketRate>()
.ContinueWith(t => MoneyMarketRate = Mapper.Map<DTOs.MoneyMarketRate, MoneyMarketRate>(t.Result)),
services.GetAsTask<DTOs.InvestmentBoundaries>()
.ContinueWith(t => InvestmentBoundaries = Mapper.Map<DTOs.InvestmentBoundaries, InvestmentBoundaries>(t.Result)),
services.GetAsTask<DTOs.TradingDate>()
.ContinueWith(t => TradingDate = Mapper.Map<DTOs.TradingDate, TradingDate>(t.Result)),
};
Task.Factory.ContinueWhenAll(
tasks,
ts => services.GetAsTask<DTOs.Spot>()
.ContinueWith(t => Spot = Mapper.Map<DTOs.Spot, Spot>(t.Result)));
The problem with this code is that the exceptions are not properly handled. For that we can leverage async and await:
try
{
var tasks = new []
{
services.GetAsync<DTOs.MoneyMarketRate, MoneyMarketRate>(x => MoneyMarketRate = x),
services.GetAsync<DTOs.InvestmentBoundaries, InvestmentBoundaries>(x => InvestmentBoundaries = x),
services.GetAsync<DTOs.TradingDate, TradingDate>(x => TradingDate = x),
};
await TaskEx.WhenAll(tasks);
await services.GetAsync<DTOs.Spot, Spot>(x => Spot = x);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
I also refactored the service executor to use async and await and move the setting to the property to an action that can be passed in.
public class ServiceExecutor
{
const string BaseAddress = "http://localhost:8080/Services/";
public async Task GetAsync<TDto, TModel>(Action<TModel> actionToSetPropertyValue)
{
var client = new WebClient();
var serviceName = typeof(TDto).Name + ".ashx";
var response = await client.DownloadStringTaskAsync(new Uri(BaseAddress + serviceName, UriKind.Absolute));
var dto = JsonConvert.DeserializeObject<TDto>(response);
actionToSetPropertyValue.Invoke(Mapper.Map<TDto, TModel>(dto));
}
}
Refactored source: https://github.com/stevenh77/UsingTasksToAvoidCallbackHellWithAsyncAndWait/
Tuesday, 22 October 2013
ExcelMediaTypeFormatter
Working example of implementing an ExcelMediaTypeFormatter for WebApi.
Source: https://github.com/stevenh77/ExcelFormatterForWebApi/
Full blog write up to follow….
Wednesday, 31 July 2013
List<string> to string
var strings = new List<string> { "blah", "de", "hoo", "ha" };
var result = strings.Aggregate((i, j) => i + " " + j);
Console.Write(result);
And with a complex type, where a response has a collection of messages, each with a text property:
var messages = this.Response
.Messages
.Select(m => m.Text)
.Aggregate((i, j) => i + " " + j);
Friday, 19 July 2013
Sequential vs Parallel Service Requests
Sequential
public async Task<HttpResponseMessage> DownloadWithHttpClient()
{
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://stevenhollidge.com/sample.json?" + DateTime.Now.Ticks);
var response = await httpClient.SendAsync(request);
return response;
}
private async void HttpClientGoButton_OnClick(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 9; i++)
{
await DownloadWithHttpClient();
}
}
Parallel
public async Task<HttpResponseMessage> DownloadWithHttpClient()
{
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://stevenhollidge.com/sample.json?" + DateTime.Now.Ticks);
var response = await httpClient.SendAsync(request);
return response;
}
private async void HttpClientGoButton_OnClick(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 9; i++)
{
DownloadWithHttpClient();
}
}
Thursday, 27 June 2013
Updating MVC view based on model updated in code
The following code increments a model property in MVC3 and updates the UI:
[HttpPost]
public ActionResult Edit(Movie model)
{
var temp = model.Age + 1;
ModelState.Remove("Age");
model.Age = temp;
if (ModelState.IsValid)
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
//return RedirectToAction("Index");
}
return View(moviedb2);
}
Thursday, 23 May 2013
Overloading methods for derived classes
Using dynamic keyword to resolve double dispatch, overloaded methods using derived types at compile time.
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OverloadedMethod
{
class Program
{
static void Main(string[] args)
{
var processor = new Processor();
var shapes = new List<Shape> {new Circle(), new Triangle()};
foreach (var shape in shapes)
{
// option 1
processor.GetType()
.GetMethod("Execute",
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new[] { shape.GetType() },
null)
.Invoke(processor,
new object[] { shape });
// or option 2 (requires known definition of all drived types and a line per type)
if (shape is Circle) processor.Execute(shape as Circle);
else if (shape is Triangle) processor.Execute(shape as Triangle);
// option 3... BOOM!!!! Works a treat :)
processor.Execute(shape as dynamic);
}
}
}
class Shape { }
class Circle : Shape
{
public int Circumference { get { return 10; } }
}
class Triangle : Shape
{
public int HypotenuseLength { get { return 20; } }
}
class Processor
{
internal void Execute(Circle circle)
{
Console.WriteLine("Executing with a Circle with circumference {0}!", circle.Circumference);
}
internal void Execute(Triangle triangle)
{
Console.WriteLine("Executing with a Triangle hypotenuse length of {0}!", triangle.HypotenuseLength);
}
}
}
Source: https://github.com/stevenh77/OverloadedMethod/
So what about this, using an extension method? Apparently Circle doesn’t have a definition for Execute…
Source: https://github.com/stevenh77/OverloadedMethodExtensions/
using System;
using System.Collections.Generic;
namespace OverloadedMethod
{
class Program
{
static void Main(string[] args)
{
var shapes = new List<Shape> {new Circle(), new Triangle()};
foreach (var shape in shapes)
{
// option 4: so what about this....?
// (shape as dynamic).Execute(); // doesn't work
ExtensionMethods.Execute(shape as dynamic); // this works!
}
}
}
class Shape { }
class Circle : Shape
{
public int Circumference { get { return 10; } }
}
class Triangle : Shape
{
public int HypotenuseLength { get { return 20; } }
}
static class ExtensionMethods
{
public static void Execute(this Circle circle)
{
Console.WriteLine("Executing with a Circle with circumference {0}!", circle.Circumference);
}
public static void Execute(this Triangle triangle)
{
Console.WriteLine("Executing with a Triangle hypotenuse length of {0}!", triangle.HypotenuseLength);
}
}
}
Wednesday, 9 January 2013
How to load types from a reference into memory
Thanks to the JIT, references are only loaded into memory once required. Here’s how to access them before they are required:
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += (sender, resolveArgs) => Assembly.ReflectionOnlyLoad(resolveArgs.Name);
var types = Assembly.ReflectionOnlyLoad("DllNameGoesHere").GetExportedTypes();
Sunday, 18 November 2012
Creating Excel file in C#
Before you start you’ll want to install Open XML SDK 2.0 for Microsoft Office:
http://www.microsoft.com/en-us/download/details.aspx?id=5124Now create a new C# console app and add a reference to the DocumentFormat.OpenXml assembly.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace CreatingExcelFile
{
class Program
{
static void Main(string[] args)
{
// Make a copy of the template file.
File.Copy(@"blank.xlsx", @"generated.xlsx", true);
// Open the copied template workbook.
using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(@"generated.xlsx", true))
{
// Access the main Workbook part, which contains all references.
WorkbookPart workbookPart = myWorkbook.WorkbookPart;
// Get the first worksheet.
WorksheetPart worksheetPart = workbookPart.WorksheetParts.ElementAt(2);
// The SheetData object will contain all the data.
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
// output our headers
var data = new[] { "ID", "TRADE", "PRICE"};
var row = CreateNewRow(1, data);
sheetData.AppendChild(row);
// Begining Row pointer
int rowIndex = 2;
// For each item in the database, add a Row to SheetData.
foreach (var trade in GetTradeData())
{
// the data written in each row
data = new [] {trade.Id.ToString(), trade.Asset, trade.Price.ToString()};
// create the Excel row with our data
row = CreateNewRow(rowIndex, data );
// Append Row to SheetData
sheetData.AppendChild(row);
// increase row pointer
rowIndex++;
}
// save
worksheetPart.Worksheet.Save();
}
}
private static Row CreateNewRow(int rowIndex, params string[] data)
{
// New Row
Row row = new Row { RowIndex = (UInt32)rowIndex };
for (int i = 0; i < data.Length; i++)
{
// A = 65 for the first column, B = 66, C = 67...
string column = ((char) (65 + i)).ToString();
// New Cell
Cell cell = new Cell
{
DataType = CellValues.InlineString,
CellReference = column + rowIndex
};
// Create Text object
Text t = new Text {Text = data[i]};
// Append Text to InlineString object
InlineString inlineString = new InlineString();
inlineString.AppendChild(t);
// Append InlineString to Cell
cell.AppendChild(inlineString);
// Append Cell to Row
row.AppendChild(cell);
}
return row;
}
public static IList<Trade> GetTradeData()
{
var list = new List<Trade>(6)
{
new Trade() {Id = Guid.NewGuid(), Asset = "APPLE", Price = (decimal) 33.89},
new Trade() {Id = Guid.NewGuid(), Asset = "BMW", Price = (decimal) 1.23},
new Trade() {Id = Guid.NewGuid(), Asset = "CAPCOM", Price = (decimal) 87.46},
new Trade() {Id = Guid.NewGuid(), Asset = "FUSE", Price = (decimal) 4.24},
new Trade() {Id = Guid.NewGuid(), Asset = "IBM", Price = (decimal) 103.66},
new Trade() {Id = Guid.NewGuid(), Asset = "MICROSOFT", Price = (decimal) 45.55}
};
return list;
}
}
public class Trade
{
public Guid Id { get; set; }
public string Asset { get; set; }
public decimal Price { get; set; }
}
}
Source: https://github.com/stevenh77/CreatingExcelFile
For Silverlight AgOpenXml library has samples for Word and Excel: http://agopenxml.codeplex.com
Sunday, 7 October 2012
File streaming to Silverlight
Requirement
Expose an end point on a web server that accepts a id value and returns a file.
Solution
using System;
using System.IO;
using System.Web;
namespace FileStreaming.Web
{
public class DownloadFile : IHttpHandler
{
private const string FilesDirectory = @"\Files\";
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString == null || context.Request.QueryString["reportid"] == null)
{
return;
}
var reportId = int.Parse(context.Request.QueryString["reportid"]);
var filename = ConvertReportIdToFileName(reportId);
var fullPath = Path.Combine(HttpContext.Current.Server.MapPath(FilesDirectory), filename);
var contentType = GetContentType(filename);
using (var reader = new StreamReader(fullPath))
{
var result = reader.ReadToEnd();
context.Response.ContentType = contentType;
context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", filename));
context.Response.Write(result);
}
}
private string ConvertReportIdToFileName(int reportId)
{
switch (reportId)
{
case 1:
return @"report1.xlsx";
case 2:
return @"report2.docx";
case 3:
return @"report3.pdf";
default:
throw new ArgumentException("Unknown ReportId");
}
}
private string GetContentType(string file)
{
var fileExtension = file.Substring(file.Length - 4, 4).Replace(".", "");
switch (fileExtension)
{
case "xlsx":
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case "docx":
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "pdf":
return "application/pdf";
case "json":
return "text/json";
case "xml":
return "text/xml";
default:
return "unknown";
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Source code
Saturday, 29 September 2012
C# Synchronization
Here are four examples of synchronization, firing three pieces of work and blocking until any of the three complete:
- Tasks
- ManualResetEvents with a WaitHandle
- ManualResetEvent
- Monitor Wait and Pulse
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Synchronisation
{
internal class Program
{
private static void Main(string[] args)
{
new TaskWaitAnyExample().Execute();
new ManualResetEventWithWaitHandle().Execute();
new ManualResetEventExample().Execute();
new MonitorWaitAndPulse().Execute();
}
}
public abstract class Example
{
protected string name = "Example";
public abstract void Execute();
protected void MethodA()
{
Console.WriteLine("{0}: Entering MethodA", name);
Thread.Sleep(20000);
Console.WriteLine("{0}: Exiting MethodA", name);
}
protected void MethodB()
{
Console.WriteLine("{0}: Entering MethodB", name);
Thread.Sleep(10000);
Console.WriteLine("{0}: Exiting MethodB", name);
}
protected void MethodC()
{
Console.WriteLine("{0}: Entering MethodC", name);
Thread.Sleep(1000);
Console.WriteLine("{0}: Exiting MethodC", name);
}
}
public class TaskWaitAnyExample : Example
{
public override void Execute()
{
name = "TaskWaitAnyExample";
Console.WriteLine("{0} (from .NET 4.0):", name);
var taskA = Task.Factory.StartNew(MethodA);
var taskB = Task.Factory.StartNew(MethodB);
var taskC = Task.Factory.StartNew(MethodC);
Console.WriteLine("Waiting for one task to finish");
Task.WaitAny(taskA, taskB, taskC);
Console.WriteLine("Signal received, time to move on{0}", Environment.NewLine);
}
}
public class ManualResetEventWithWaitHandle : Example
{
public override void Execute()
{
name = "ManualResetEventWithWaitHandle";
Console.WriteLine("{0} (from .NET 1.1):", name);
WaitHandle[] waitHandles = new WaitHandle[]
{
new ManualResetEvent(false),
new ManualResetEvent(false),
new ManualResetEvent(false)
};
ThreadPool.QueueUserWorkItem(o => { MethodA(); ((ManualResetEvent)waitHandles[0]).Set(); });
ThreadPool.QueueUserWorkItem(o => { MethodB(); ((ManualResetEvent)waitHandles[1]).Set(); });
ThreadPool.QueueUserWorkItem(o => { MethodC(); ((ManualResetEvent)waitHandles[2]).Set(); });
Console.WriteLine("Waiting for one signal that one work item has finished");
WaitHandle.WaitAny(waitHandles);
Console.WriteLine("Signal received, time to move on{0}", Environment.NewLine);
}
}
public class ManualResetEventExample : Example
{
private readonly ManualResetEvent manualResetEvent = new ManualResetEvent(false);
public override void Execute()
{
name = "ManualResetEvent";
Console.WriteLine("{0} (from .NET 1.1):", name);
ThreadPool.QueueUserWorkItem(o => { MethodA(); manualResetEvent.Set(); });
ThreadPool.QueueUserWorkItem(o => { MethodB(); manualResetEvent.Set(); });
ThreadPool.QueueUserWorkItem(o => { MethodC(); manualResetEvent.Set(); });
Console.WriteLine("Waiting for one signal that one work item has finished");
manualResetEvent.WaitOne();
Console.WriteLine("Signal received, time to move on{0}", Environment.NewLine);
}
}
public class MonitorWaitAndPulse : Example
{
readonly object locker = new object();
bool signalSent;
public override void Execute()
{
name = "Monitor Wait and Pulse";
Console.WriteLine("{0} (from .NET 1.1):", name);
ThreadPool.QueueUserWorkItem(o => DoWork(MethodA));
ThreadPool.QueueUserWorkItem(o => DoWork(MethodB));
ThreadPool.QueueUserWorkItem(o => DoWork(MethodC));
Console.WriteLine("Waiting for one signal that one work item has finished");
lock (locker)
while (!signalSent)
Monitor.Wait(locker);
Console.WriteLine("Signal received, time to move on{0}", Environment.NewLine);
}
private void DoWork(Action action)
{
action.Invoke();
lock (locker)
{
signalSent = true;
Monitor.Pulse(locker);
}
}
}
}
Thursday, 27 September 2012
Test for Generic Type
Useful helper method I found on StackOverflow
using System;
using System.Collections.Generic;
namespace TestForGenericType
{
class Program
{
static void Main(string[] args)
{
var test = new List<string>();
bool result = test.GetType().IsSubclassOfRawGeneric(typeof(List<>));
// result = true
}
}
static class ReflectionUtils
{
public static bool IsSubclassOfRawGeneric(this Type toCheck, Type baseType)
{
while (toCheck != typeof(object))
{
Type cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (baseType == cur)
{
return true;
}
toCheck = toCheck.BaseType;
}
return false;
}
}
}