Wednesday, March 20, 2013

Advanced C#

Topics:
Higher Calling Functions
Lazy Code
Asynch and Parallel

static void Main(string[] args)
{
 var elapsed = Measure(() =>
 {
  var numbers = new[]{3, 5, 7, 9, 11, 13};
  foreach(var prime in numbers.Find(IsPrime).Take(2))
  {
   Console.WriteLine(prime);
  }
 });
 Console.WriteLine(elapsed);

 //Parallel
 Parallel.Invoke(new Action[]
 {
  () => FindLargePrimes(3,100),
  () => FindLargePrimes(101,200)
 });

 //Task
 var task = new Task<IEnumerable<int>>(
  () => FindLargePrimes(3,100)
 );
 var task2 = task.ContinueWith((antecedent) =>
      {
       foreach(var number in antecedent.Result)
       {
        Console.WriteLine(number);
       }
      });
 task.Start();
 Console.WriteLine("Doing other work");
 task2.Wait();
}

private static IEnumerable<int> Find(this IEnumerable<int> values, Func<int, bool> test)
{
 foreach(var number in values)
 {
  if(test(number))
  {
   yield return number;
  }
 }
}

private static bool IsPrime(int number) [...]

private TimeSpan Measure(Action action)
{
 var watch = new StopWatch();
 watch.start();
 action();
 return watch.Elapsed;
}

Reference: Scott Allen's C# Fundamentals - Part 2

Thursday, March 14, 2013

Dynamic C#

using System.Dynamic;

public class Employee
{
 public string FirstName {get; set;}

 public void Speak()
 {
  Console.WriteLine("Hi, my name is {0}", FirstName);
 }
}
class Program
{
 static void Main(string[] args)
 {
  //old method
  object o = GetASpeaker();
  o.GetType().GetMethod("Speak").Invoke(0, null);
 
  //dynamic object
  dynamic o = GetASpeaker();
  o.Speak();
 
  //loading 3rd-party assembly and dynamic object
  Type dogType = Assembly.Load("Dogs").GetType("Dog");
  dynamic dog = Activator.CreateInstance(dogType);
  dog.Speak();
 
  //excel automation and dynamic object
  Type excelType = Type.GetTypeFromProgId("Excel.Application");
  dynamic excel = Activator.CreateInstance(excelType);
  excel.Visible = true;
  excel.Workbooks.Add();
  dynamic sheet = excel.ActiveSheet;
  Process[] processes = Process.GetProcesses();
  for(int i = 0; i < processes.Length; i++)
  {
   sheet.Cells[i+1, "A"] = processes[i].ProcessName;
   sheet.Cells[i+1, "B"] = processes[i].Threads.Count;
  }
 
  //expandoobject
  dynamic expando = new ExpandoObject();
  //or, dynamic expando = new ExpandoObject() as IDictionary<string, object>;
  expando.Name = "The";
  //or, expando["Name"] = "The"
  expando.Speak = new Action(() => Console.WriteLine(expando.Name));
 
  foreach(var member in expando)
  {
   Console.WriteLine(member.Key);
  }
 
  expando.Speak();
 
  //implements dynamicobject interface
  dynamic doc = new DynamicXml("Employees.xml");
  foreach(var employee in doc.Employees)
  {
   Console.WriteLine(employee.FirstName);
  }
 
  //C# and IronRuby interaction
 
  // running .rb file with passed c# object
  var engine = IronRuby.Ruby.CreateEngine();
  var scope = engine.CreateScope();
  scope.SetVariable("employee", new Employee { FirstName = "The C#"});
  engine.ExecuteFile("Program.rb", scope);
 
  // instantiates classes from .rb file in c# code
  dynamic ruby = engine.Runtime.Globals;
  dynamic person = ruby.Person.@new();
  person.firstName = "The Ruby";
  person.speak();
 }

 private static object GetASpeaker()
 {
  return new Employee { FirstName = "Scott" };
 }
}
internal class DynamicXml : System.Dynamic.DynamicObject, System.Collections.IEnumerable
{
 private dynamic _xml;

 public DynamicXml(string fileName)
 {
  _xml = XDocument.Load(fileName);
 }

 public DynamicXml(dynamic xml)
 {
  _xml = xml;
 }

 public override bool TryGetMember(GetMemberBinder binder, out object results)
 {
  var xml = _xml.Element(binder.Name);
  if(xml != null)
  {
   result = new DynamicXml(xml);
   return true;
  }
 
  result = null;
  return false;
 }

 public IEnumerator GetEnumerator()
 {
  foreach(var child in _xml.Elements())
  {
   yield return new DynamicXml(child);
  }
 }
}

Program.rb
class Person
 attr_accessor :firstName

 def speak
  puts @firstName
 end
end
employee.Speak

Reference: Scott Allen's C# Fundamentals Part 2

Tuesday, March 12, 2013

C# Delegate, Func, Action, and Extension Method

IEnumerable<string> cities = new[]{"Falls Church", "Annandale", "Reston"};
//delegate 1
IEnumerable<string> query = cities.Filter(StringThatStartWithA);
//delegate 2
IEnumerable<string> query2 = cities.Filter(delegate(string item)
           {
            return item.StartsWith("A");
           });
         
//expression method
IEnumerable<string> query3 = cities.Filter((item) => item.StartsWith("A"));
static bool StringThatStartWithA(string s)
{
 return s.StartWith("A");
}
public static IEnumerable<T> Filter<T> (this IEnumerable<T> input, FilterDelegate<T> predicate)
{
 foreach(var item in input)
 {
  if(predicate(item))
  {
   yield return item;
  }
 }
}
//or, FilterDelegate<T> predicate can be replaced by Func<T, bool> predicate
//Func returns a value while Action does not
//ex:
//Func<int, int> square = x => x*x;
//Func<int, int, int> add = (x,y) => x+y;
//Action<int> write = x => Console.WriteLine(x);
//write(square(add(1,3)));

public delegate bool FilterDelegate<T>(T item);

Ninject Basics

using Ninject;
class Program
{
 static void Main(string[] args)
 {
  var kernel = new StandardKernel();
  //or, passes in an instance of a class that implements NinjectModule interface
  //var kernel = new StandardKernel(new MyModule());
 
  //manages object lifetime using .InScope(), .InSingletonScope(), InThreadScope(), InTransientScope()
  //.InSingletonScope: shopper and shopper2 are the same object
  kernel.Bind<ICreditCard>().To<MasterCard>().InSingletonScope();
 
  //or, gives binding a name if there are multiple bindings to ICreditCard
  //kernel.Bind<ICreditCard>().To<MasterCard>().Named("MasterCard");
  //kernel.Get<ICreditCard>("MasterCard");
 
  //or, bind to method
  /*
  kernel.Bind<ICreditCard>().ToMethod(context =>
           {
            Console.WriteLine("Creating new card");
            return new MasterCard();
           });
  */
 
  //could rebind ICreditCard to Visa after MasterCard
  //kernel.Rebind<ICreditCard>().To<Visa>();
 
  //no need to bind Shopper class to itself, Ninject takes care of bindings automatically
  var shopper = kernel.Get<Shopper>();
  shopper.Charge();
  Console.WriteLine(shopper.ChargesForCurrentCard);
 
  var shopper2 = kernel.Get<Shopper>();
  shopper2.Charge();
  Console.WriteLine(shopper2.ChargesForCurrentCard);
 
  Console.Read();
 }
}
public class MyModule : NinjectModule
{
 public override void Load()
 {
  Kernel.Bind<ICreditCard>().To<MasterCard>();
 }
}

Reference: John Sonmez's IoC Course on Pluralsight

Monday, March 11, 2013

Getting TeamCity Build Number with MSBuild

<PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Version>$(BUILD_NUMBER)</Version>
    <SourceXMLFile>..\src\UNNAMED.Web\web.config</SourceXMLFile>
    <DestXMLFile>..\src\UNNAMED.Web\web.config</DestXMLFile>
</PropertyGroup>

<ItemGroup>
    <XmlConfigUpdates Include="ConfigUpdates-WebConfig">
        <XPath>/configuration/appSettings/add[@key='BuildNumber']/@value</XPath>
        <NewValue>$(Version)</NewValue>
    </XmlConfigUpdates>
    <BuildArtifacts Include=".\buildartifacts\"/>
    <SolutionFile Include="..\src\UNNAMED.sln"/>
</ItemGroup>

<Target Name="UpdateWebConfig">
    <Message Text="Updating Web.config"/>
    <Copy SourceFiles="$(SourceXMLFile)" DestinationFiles="$(DestXMLFile)"/>
    <XmlPoke XmlInputPath="$(DestXMLFile)" Query="%(XmlConfigUpdates.XPath)" Value="%(XmlConfigUpdates.NewValue)"/>
</Target>

<Target Name="Clean">
    <RemoveDir Directories="@(BuildArtifacts)"/>
</Target>

<Target Name="Init" DependsOnTargets="Clean">
    <MakeDir Directories="@(BuildArtifacts)"/>
</Target>

<Target Name="Compile" DependsOnTargets="Init; UpdateWebConfig">
    <MSBuild Projects="@(SolutionFile)" Properties="OutDir=%(BuildArtifacts.FullPath);Configuration=$(Configuration)"/>
</Target>

Programming IoC Container

class Program
{
 static void Main(string[] args){
  Resolver resolver = new Resolver();
  resolver.Register<Shopper, Shopper>();
  resolver.Register<ICreditCard, MasterCard>();

  var shoper = resolver.Resolve<Shopper>();
  shopper.Charge();

  Console.Read();
 }
}
public class Resolver
{
 private Dictionary<Type, Type> dependencyMap = new Dictionary<Type, Type>();

 public T Resolve<T>()
 {
  return (T)Resolve(typeof(T));

  private object Resolve(Type typeToResolve)
  {
   Type resolvedType = null;
   try{
    resolvedType = dependencyMap[typeToResolve];
   }
   catch
   {
    throw new Exception(string.Format("Could not resolve type {0}", typeToResolve.FullName));
   }
 
   var firstConstructor = resolvedType.GetConstructors().First();
   var constructorParameters = firstConstructor.GetParameters();
   if(constructorParameters.Count() == 0)
    return Activator.CreateInstance(resolvedType);
  
   IList<object> parameters = new List<object>();
   foreach(var parameterToResolve in constructorParameters)
   {
    parameters.Add(Resolve(parameterToResolve.ParameterType);
   }
 
   return firstConstructor.Invoke(parameters.ToArray());
  }

  public void Register<TFrom, TTo>()
  {
   dependencyMap.Add(typeof(TFrom), typeof(TTo));
  }
 }

 public class Visa : ICreditCard
 {
  public string Charge()
  {
   return "Charging with the Visa!";
  }
 }

 public class MasterCard : ICreditCard
 {
  public string Charge()
  {
   return "Charging with the MasterCard!";
  }
 }

 public interface ICreditCard
 {
  string Charge();
 }
}

Reference: Pluralsight course on Inversion of Control by John Sonmez

Wednesday, March 6, 2013

List Cycler with jQuery

<ul id="posts">
   <li><label>Title 1</label>Description</li>
   <li><label>Title 2</label>Description</li>
   <li><label>Title 3</label>Description</li>
</ul>

Javascript function method
var cycler = function(){
   var firstPost;
   removeFirst = function(){
      firstPost = $("#posts li:first");
      firstPost.fadeOut(appendToEnd);
   };
   appendToEnd = function(post){
      firstPost.remove();
      $("#posts").append(firstPost);
   };
   return{
      removeFirst : removeFirst,
      appendToEnd : appendToEnd
   }
}();

$(function(){
   $("#cycler").click(function(){
      cycler.removeFirst();
   });
});

Javascript class method
var ListCycler = function(parentContainer){
   var listContainer = $(parentContainer);
   var firstPost = $(parentContainer + " li:first");
   cycle = function(){
      firstPost.fadeOut(appendToEnd);
   };
   appendToEnd = function(post){
      firstPost.remove();
      listContainer.append(firstPost);
      firstPost.fadeIn();
   };

   return{
      cycle : cycle
   }
};

$(function(){
   $("#cycle").click(function(){
      var cycler = new ListCycler("#posts");
      cycler.cycle();
   });
});

Reference: http://vimeo.com/47483575

Friday, March 1, 2013

Enable Parent Paths in IIS for Classic ASP Apps


Enable NetFX3 in Windows Server 2012

C:\Users\Administrator>dism.exe /online /enable-feature /featurename:NetFX3Serve
rFeatures /Source:e:\sources\sxs /LimitAccess
Deployment Image Servicing and Management tool
Version: 6.2.9200.16384
Image Version: 6.2.9200.16384
Enabling feature(s)
[==========================100.0%==========================]
The operation completed successfully.
C:\Users\Administrator>dism.exe /online /enable-feature /featurename:NetFX3 /Sou
rce:e:\sources\sxs /LimitAccess
Deployment Image Servicing and Management tool
Version: 6.2.9200.16384
Image Version: 6.2.9200.16384
Enabling feature(s)
[==========================100.0%==========================]
The operation completed successfully.

Fusion Registry Settings in Windows Server 2012