Tuesday, September 10, 2013

Thursday, August 29, 2013

MSBuild Choose When Condition


msbuild buildfile.build /target:Deploy /p:Configuration=Release;Environment=Dev
<Choose>
    <When Condition=" '$(Environment)'=='' Or '$(Environment)'=='Dev' ">
      <PropertyGroup>
        <SourceXMLFile>web.dev.config</SourceXMLFile>
        <WebServerName></WebServerName>
        <WebServerUserName></WebServerUserName>
        <WebServerPassword></WebServerPassword>
      </PropertyGroup>
    </When>
    <When Condition=" '$(Environment)'=='Test' ">
      <PropertyGroup>
        <SourceXMLFile>web.test.config</SourceXMLFile>
        <WebServerName></WebServerName>
        <WebServerUserName></WebServerUserName>
        <WebServerPassword></WebServerPassword>
      </PropertyGroup>
    </When>
  </Choose>

Sunday, July 28, 2013

Recent Books Read

 Dependency Injection in .NET

 Secrets of the JavaScript Ninja

The art of Unit Testing with Examples in .NET

Friday, June 14, 2013

Calling User Defined Function in Entity Framework 5

public string ExecuteUserDefinedFunctionReturningScalarStringValue(int inputValue)
{
    var query = "SELECT [dbo].[UserDefinedFunctionName]({0})";
    object[] param = { inputValue };
    var outputString = Context.Database.SqlQuery<string>(query, param).FirstOrDefault();

    return outputString;
}

Calling Store Procedure in Entity Framework 5

Model.Context.cs:

public virtual int DbStoreProcedureName(ObjectParameter output_string, Nullable<int> inputId)
{
    var inputIdParameter = inputId.HasValue ?
        new ObjectParameter("inputParam1", inputId) :
        new ObjectParameter("inputParam1", typeof(int));

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("DbStoreProcedureName", output_string, inputIdParameter);
}       
       
Usage:

var inputValue = 5;
var outputParam = new ObjectParameter("output_string", typeof(string));
Context.DbStoreProcedureName(outputString, intputValue);
var outputString = outputParam.Value.ToString();

Sunday, April 28, 2013

Current Visual Studio Theme: Cointen


Cointen is currently my favorite theme. It has red text, which helps keep me focused on what is important. Give it a try at http://studiostyl.es/schemes/cointen.


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


Thursday, February 28, 2013

Issue arises after fresh install of Windows Server 2012 and SQL Server 2012

What could possibly have caused this error?


Server Error in '/' Application.

Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'AjaxControlToolkit' could not be loaded.

WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:


[FileLoadException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0 System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +210 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +242 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +17 System.Reflection.Assembly.Load(String assemblyString) +35 System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +122 [ConfigurationErrorsException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +12759734 System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +503 System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +142 System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +203 System.Web.Compilation.BuildManager.ExecutePreAppStart() +152 System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1151 [HttpException (0x80004005): Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12880068 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12721257

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18033

Wednesday, January 30, 2013

MCSD: Web Applications Solutions Developer

Exam 70-480: Programming in HTML5 with JavaScript and CSS3 (Publication Date: April 22, 2013)

Exam 70-486: Developing ASP.NET MVC 4 Web Applications (Publication Date: May 22, 2013)

Exam Ref 70-487: Developing Windows Azure and Web Services (Publication Date: June 22, 2013)