Wednesday, April 05, 2017

Bulletproof fluent interfaces

I attended a Fluent Interface webinar by the inimitable Scott Lilly (see http://scottlilly.com/FIWebinar). Below is my exercise file and some thoughts around what I think are the benefits of a fluent interface.

A fluent interface gives you more control over the way your methods are called. Scott explains it as a three step process, first instantiate, then chain your methods, and finally execute (ICE). And I will present an example of a report in the classic sense, and one built in the fluent way.

download linqpad file: http://share.linqpad.net/w5gdub.linq


Thursday, March 30, 2017

Automapper in action

Automapper is an object to object mapper which helps to eliminate yak shaving. It can save you from the tedious task of creating custom code to convert data-store object models to your view model.

I put together a demo because I believe it when I see it in action.

Here's a working LinqPad version here: http://share.linqpad.net/neu8bm.linq

Or see the code online here...

Friday, March 03, 2017

FSharp XML Type provider in action

This is a working sample of an XML type provider. It's a simple scrip. Though Linqpad does crash when dealing with it. Saves a lot of time when writing a quick script to parse an xml document.


Download the linqpad file: http://share.linqpad.net/xlrrfl.linq

Thursday, February 09, 2017

A method to get a sitecore item id given a path

This method will give you a sitecore item id back if you give it a fully qualified path as input.

void Main()
{
 var itemId= GetItemId("/sitecore/content").Dump(); 
 
 //get child items
 //Items.Where (i => i.ParentID==itemId).Select (i => new {i.ID, i.Name}).Dump();
 
 //show field information
 Fields.Where (f => f.ItemId==itemId && f.Value!="")
  .Select (f => new 
  {
   FieldName=Items.Where (i => i.ID==f.FieldId).Select (i => i.Name).Single (),
   f.Value,
   f.Language
  })
  .Dump();
  
}



Guid GetItemId(string itemPath)
 {
 
  var pathParts = itemPath.Split(new char[] { '/'}, StringSplitOptions.RemoveEmptyEntries ); 
  var parentId = Guid.Empty;
  var id = Guid.Empty;
  foreach (var part in pathParts)
  {
   if (parentId == Guid.Empty && part.Equals("sitecore", StringComparison.OrdinalIgnoreCase))
   {
     parentId = new Guid("{11111111-1111-1111-1111-111111111111}");
  id = parentId;
    }
   else
   {
    id = GetChildGuid(part, parentId);
 
    if (id != Guid.Empty)
     parentId = id;
    else
    {
     String.Format("Could not find {0}", part).Dump();
     break;
    }
   }
  }
  return id;
}
 
Guid GetChildGuid (string childName, Guid parent_guid)
{
  return Items.Where(i => i.ParentID == parent_guid && i.Name == childName)
   .Select(i => i.ID)
   .FirstOrDefault();
}

Wednesday, January 18, 2017

How to flatten a list of lists into a flat list in one line of code: SelectMany is your friend

Given that you have a list of lists, how do you flatten it?



how do you flatten it?


With the SelectMany LINQ method, it's easy peasy:

var listOfLists = new List<IEnumerable<int>>() { Enumerable.Range(1, 3), Enumerable.Range(20, 3) };
listOfLists.Dump("List of lists");
listOfLists.SelectMany(lol => lol).Dump("Flat list");

Download linqpad sample, here

Friday, January 13, 2017

Assigning lambda expression to a variable

In the spirit of writing terse code, I was pleasantly surprised that you can assign a lambda expression to a local variable. A quick sample:
void Main()
{
 Func<string, string> sayHello = ((input) => { return input + "!!"; });
 System.Diagnostics.Debug.WriteLine(sayHello("hello world"));
}

Results:
hello world!!

in Func<string, string>, the first string specifies the input parameter's data type, while the last string is for the return type. If you have more than one input parameter, you'd have multiple parameters specified like this <string, string, stringstring> and the last one is always for the return type of the function.

Wednesday, January 11, 2017

My FSharp patter matching code kata

Given a list of numbers, detect when the values 2,3,4 are present one after the other.

Thursday, January 05, 2017

Extension method to dump Highlighted search results in Linqpad

Here's an extension method which lets you output the found results as html.

For example, if you wanted to show the result of a search and replace, given:
 var text = "An apple a day keeps the doctor away\n you can say that any day of the year today or tomorrow.";
 var find = "day";
 var replace = "week";
 
 text.HighlightText(find).Dump("Original text");
 text.Replace(find, replace).HighlightText(replace).Dump("updated text");

The result would be:
Original text
An apple a 
day
 keeps the doctor away
 you can say that any 
day
 of the year.
updated text
An apple a 
week
 keeps the doctor away
 you can say that any 
week
 of the year.

See extension method below:

Wednesday, December 28, 2016

Boilerplate code to compare how long two operations take

This class allows you to wrap the stuff you want timed in a disposable using block. The timer is started when you enter the block and stops when the using clause is disposed.
void Main()
{
 double elapsed1 ;
 double elapsed2 ;
 var iterations = 1e7;
 using (var timedTask = new TimedTask("Method1"))
 {//Write your code here and measure its performance 
  for (var i = 0; i < iterations; i++)
  {
   Method1_DoStuff();
  }
  elapsed1 = timedTask.ElapsedMs();
 }

 
 using (var timedTask = new TimedTask("Method2"))
 {//Write your code here and measure its performance 
  for (var i = 0; i < iterations; i++)
  {
   Method2_DoStuff();
  }
  elapsed2 = timedTask.ElapsedMs();
 }
 
 if (elapsed1 < elapsed2)
  String.Format("method1 is {0:###,###.##}x faster than method 1", elapsed2/elapsed1, elapsed1, elapsed2).Dump();
 else
  String.Format("method2 is {0:###,###.##}x faster than method 2", elapsed1/elapsed2, elapsed1, elapsed2).Dump();

}

string Method1_DoStuff() {
 var x = "hello";
 x = x + " pretty";
 x = x + " world";
 return x;
}

private static string _field;
string Method2_DoStuff() {
 if (_field==null)
  _field = "hello pretty world";
 return _field;
}

class TimedTask : IDisposable
{
 string _taskName;
 Stopwatch sw;
 public TimedTask(string taskName)
 {
  _taskName = taskName;
  sw = new Stopwatch();
  sw.Start();
 }
 public double ElapsedMs()
 {
  return sw.Elapsed.TotalMilliseconds;
 }
 
 public void Dispose()
 {
  sw.Stop();
  string.Concat("completed ", _taskName, " in ", (sw.Elapsed.Ticks / 10000.0).ToString("###,##0.00 ms")).Dump();
 }


}


The result looks something like this:
completed Method1 in 559.24 ms
completed Method2 in 45.65 ms
method2 is 12.25x faster than method 2

download linqpad .linq file

Wednesday, December 21, 2016

Export to cURL from Fiddler

As a long-time user of Fiddler to monitor request traffic. It would be nice to export a request as a cURL command. Easy to save, easy to pass around.  Follow instructions here to add Copy as cURL command to your context options:

Click Rules > Customize Rules (Ctrl+R) and type this right before the closing curly bracket (})

BindUIButton("Copy cURL")
ContextAction("Copy cURL")
public static function doCopyCurl(arrSess: Session[])
{
var oExportOptions = FiddlerObject.createDictionary();
// If you'd prefer to save to a file, set the Filename instead
//oExportOptions.Add("Filename", "C:\\users\\lawrence\\desktop\\out1.bat");
oExportOptions.Add("ExportToString", "true");
  FiddlerApplication.DoExport("cURL Script", arrSess, oExportOptions, null);
var sOutput: String = oExportOptions["OutputAsString"];

Utilities.CopyToClipboard(sOutput);
FiddlerApplication.UI.SetStatusText("Copied Sessions as HAR");
}

code from https://textslashplain.com/2015/12/30/whats-new-in-fiddler-4-6-2/

Monday, December 12, 2016

My experience getting started with .net core with vscode

I created a new folder and opened command interface there. I typed

dotnet new -t Web

 The options for type are:
- { Name = Console, isMsBuild = True }
- { Name = Web, isMsBuild = True }
- { Name = Lib, isMsBuild = True }
- { Name = Mstest, isMsBuild = True }
- { Name = Xunittest, isMsBuild = True }


I hit run and it prompted me to setup launch and tasks json files. I selected .net core and continued. Then I remembered, oh right, I need to restore. so I ran

dotnet restore

This downloaded many dlls and I felt good about the project. Then I hit F5 and...  error! Aaargh!  Why .net why?   



The problem with this error - I don't know how to open the C# output window *YET*. The journey will continue when I figure that out.

Thursday, November 10, 2016

DotNetFiddle for your mvc experimenting needs

Thanks to dotnetrocks better know a framework for bringing this to my scattered attention:

https://dotnetfiddle.net/

enjoy

Tuesday, September 20, 2016

Technology Stack - tail your log files with Baretail

Baretail does a great job of giving you a view of what's going into your log files as data is written to it.

Check it out at http://www.baremetalsoft.com/baretail/

Friday, July 29, 2016

Secret sauce for your webapi - to always return json formatted result

Add this to your App_Start\RegisterWebAPIRoutes.cs file or wherever you happen to register your webapi routes

config.Formatters.Insert(0, new JsonpMediaTypeFormatter());
reference: http://stackoverflow.com/questions/10514047/how-do-i-handle-jsonp-with-webapi

Wednesday, December 16, 2015

Unchain yourself from jQuery

As a developer, it's easy to rely on jQuery for everything. How about breaking that link on your next project.

See this post to see how easy it is to do AJAX without jQuery.

Monday, September 28, 2015

Adventures in LINQ Enumerables Extension Methods

var a  = new List<string>{"A", "Z", "C", "D", "C"};
var b  = new List<string>{"G", "D", "E", "Z", "C"};
var c  = new List<int>{1, 1, 1};


System.Linq.Enumerable.Zip(a, b, (a1,b1)=> new {a=a1,b=b1}).Dump("Zip - creates a collection with elements from list a and b matched based on index position"); 
a.Zip(b, (a1,b1)=> new{a1, b1}).Dump("Zip - shorthand");

System.Linq.Enumerable.Aggregate(c, (resultsofar,y)=> resultsofar-y ).Dump("Aggregate1"); //first number is initial value for result so far and starting from second value, function recusrses
c.Aggregate (2000, (resultsofar, cn) => resultsofar+ cn).Dump("aggregate2"); //first argument is initial value, aggregator function is then evaluated for each item in collection

System.Linq.Enumerable.Range(101, 5).Dump("Range - generates a list of numbers starting from 101 to 105");


System.Linq.Enumerable.Except(a, b).Dump("Except - generates a list of containing items from a minus values from b.  Result is A, B"); 
a.Except(b).Dump("shorthand for except");

System.Linq.Enumerable.Union(a, b).Dump("Union - union of two lists, excluding duplicates");
a.Union(b).Dump("Union shorthand");

System.Linq.Enumerable.Concat(a, b).Dump("Concat - make two lists into one bigger list"); 
a.Concat(b).Dump("Union shorthand");

System.Linq.Enumerable.Intersect(a, b).Dump("Intersect - unique list of items which exist in both lists"); 
a.Intersect(b).Dump("Intersect shorthand");
See results of these statements below...

Monday, April 27, 2015

Thoughts on setting default language for a site

This post makes a useful suggestion.
http://blog.boro2g.co.uk/automatically-set-the-language-of-the-content-editor/

I want to see how it plays out if you have a use case where a site is primarily in english but has some spanish sections, for example. You wouldn't want the user's choice of language reset every time they click on a node.

Thursday, September 18, 2014

Serializing a list of values as json properties

I was so excited to find that this is easily doable in C#.  Here is the link to the stack overflow page.


Wednesday, July 23, 2014

Javascript function to mimic c#'s String.Format() method

var format = function (input) {
var args = arguments;
return input.replace(/\{(\d+)\}/g, function (match, capture) {
return args[1*capture + 1];
});


from this github gist

Friday, February 21, 2014

Example of reusing common table expression table name

;with word as
(
 select 'hello' as word union all
 select 'goodbye' 
 
)
, thing as 
(
 select 'world' as name union all
 select 'friends'
)
, wordthing as
(
 select w.word +  ' ' + t.name statement
 from 
  word w,
  thing t
)
Select wt.statement
from
 wordthing wt


Result: