Tuesday, December 14, 2010

SilverLight - Fill a ComboBox


Just doing some test

Binding a ComboBox at runtime.
private void button1_Click(object sender, RoutedEventArgs e)
{
List<Car> carList = new List<Car>();
carList.Add(new Car() { Name = "Ferrari", Price = 150000 });
carList.Add(new Car() { Name = "Honda", Price = 12500 });
carList.Add(new Car() { Name = "Toyota", Price = 11500 });
comboBox1.ItemsSource = carList;
comboBox1.DisplayMemberPath = "Name";
comboBox1.SelectedIndex = 2;
comboBox1.SelectionChanged += new SelectionChangedEventHandler(comboBox1_SelectionChanged);
}
void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Car selCar =(Car) comboBox1.SelectedItem;
MessageBox.Show(selCar.Name);
}
}
public class Car
{
public string Name { get; set; }
public int Price { get; set; }
}

Binding a ComboBox at design time;
<ComboBox Height="23" HorizontalAlignment="Left" Margin="225,184,0,0" Name="comboBox2" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" >
            <ComboBoxItem Content="Value-1"></ComboBoxItem>
            <ComboBoxItem Content="Value-2"></ComboBoxItem>
            <ComboBoxItem Content="Value-3"></ComboBoxItem>
            <ComboBoxItem Content="Value-4"></ComboBoxItem>
            <ComboBoxItem Content="Value-5"></ComboBoxItem>
</ComboBox>

Monday, December 13, 2010

TripleDES Encryption using MD5 Hashing

Example in VB.Net
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
 
Public NotInheritable Class Utility

 Private Sub New()
End Sub


Private
Shared Function CreateDES(ByVal key As String) As TripleDESDim md5 As MD5 = New MD5CryptoServiceProvider()
Dim des As TripleDES = New TripleDESCryptoServiceProvider()
des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key))
des.IV = New Byte(des.BlockSize \ 8 - 1) {}
Return des
End Function


Public
Shared Function Encryption(ByVal PlainText As String, ByVal key As String) As String
Dim
des As TripleDES = CreateDES(key)
Dim ct As ICryptoTransform = des.CreateEncryptor()
Dim input As Byte() = Encoding.Unicode.GetBytes(PlainText)
Return Convert.ToBase64String(ct.TransformFinalBlock(input, 0, input.Length))
End Function


Public
Shared Function Decryption(ByVal CypherText As String, ByVal key As String) As String
Dim
b As Byte() = Convert.FromBase64String(CypherText)
Dim des As TripleDES = CreateDES(key)
Dim ct As ICryptoTransform = des.CreateDecryptor()
Dim output As Byte() = ct.TransformFinalBlock(b, 0, b.Length)
Return Encoding.Unicode.GetString(output)
End Function


End
Class

 
Example:
Dim strEncrypted As String = Utility.Encryption("Hello", "TESTKEY3327ABC09876433")
Dim strDecrypted As String =
Utility.Decryption(strEncrypted,TESTKEY3327ABC09876433")MessageBox.Show(strDecrypted)

Wednesday, December 8, 2010

Code Contracts in .NET 4

Reference : http://visualstudiomagazine.com/articles/2010/06/23/code-contracts.aspx
http://www.codeproject.com/KB/cs/CodeContracts.aspx

One of the key features of the .NET Framework is its enforcement of strong typing. But sometimes, simply enforcing that an integer is passed into a method isn't enough. We have to write additional code to make sure the integer is in a particular range or some other requirement. With Code Contracts, we get a language-neutral way to express such additional requirements in the form of preconditions, postconditions and invariants.
What is Code Contracts
Code Contracts is a subset of a larger Microsoft Research Project called Spec# (pronounced "Spec Sharp"). You can read more about this project here. Spec# is a formal language for defining API contracts. A subset of these contracts -- preconditions, postconditions and invariants -- has made its way into Visual Studio 2010 in the form of Code Contracts.
Before being able to utilize Code Contracts, you'll need to download and install it from http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx. Why the need for the download? Code Contracts has support for both Visual Studio 2008 as well as 2010. Since it's not a VS 2010-specific product, a separate download is required.
Example :
using System.Diagnostics.Contracts;

public class TestContract
    {
        int m_n1;
        int m_n2;
        public TestContract(int x,int y)
        {
            Contract.Requires(x > 10, "x should be > 10");
            m_n1 = x;
            m_n2 = y;
        }       
    }


Now try to create an object of TestContract
                TestContract obj = new TestContract(3, 20);

This will throw exception as “x should be > 10”

Parallel Programming with dot net

http://msdn.microsoft.com/en-us/library/ff963553.aspx

Example.
using System.Threading.Tasks;
int n=5;
Parallel.For(0, n, i => {
MessageBox.Show(i.ToString());
});

Wednesday, November 24, 2010

Razor Template Engine

Razor Code can be parsed using Razor template engine. http://razorengine.codeplex.com/
Following sample demonstrate how to achieve that.  Both @function and @helper are working.

SIMPLE TEMPLATE
string template = "Hello @Model.Name! Welcome to Razor!";
            string result = Razor.Parse(template, new { Name = "World" });
            MessageBox.Show(result);

@FUNCTION
string template = "@functions{ public static string RenderDiscountedPrice(decimal price){    return \"Buy now for only 10 with $1.00 off!\";}}  @RenderDiscountedPrice(10);"; // WORKS
            string result = Razor.Parse(template,null);
            MessageBox.Show(result);

@HELPER
string template = "@helper RenderDiscountedPrice(decimal price){ \"Buy now for only 10 with $1.00 off!\";} Hello @RenderDiscountedPrice(10);"; // WORKS
            string result = Razor.Parse(template,null);
            MessageBox.Show(result);

MODEL
string template = "Users List :\n @foreach(var e in Model){\n  @e.Name  @e.Designation  }";       // WORKS
                var f = new FakeEmployeesRepository();
                string result = Razor.Parse(template, f.Employees);
                MessageBox.Show(result);


Where Employees Model is as follows;
public class Employee
       {
              public int EmployeeCode { get; set; }
              public string Name { get; set; }
              public string Designation { get; set; }
       }

public class FakeEmployeesRepository : IEmployeesRepository
       {
              // Hard Coded list of employees
              private static readonly IQueryable<Employee> _fakeEmployees = new List<Employee> {
        new Employee {EmployeeCode=1,  Name = "Imran", Designation="Senior Software Engineer"},
        new Employee {EmployeeCode=2,  Name = "Andrew", Designation="Graphic Designer"},
        new Employee {EmployeeCode=3,  Name = "Michael", Designation="Project Manager"},
        new Employee {EmployeeCode=4,  Name = "John", Designation="Database Administrator" },
        new Employee {EmployeeCode=5,  Name = "Robert", Designation="Project Director"}
        }.AsQueryable();

              public IQueryable<Employee> Employees
              {
                     get { return _fakeEmployees; }
              }
       }

Monday, November 22, 2010

MVC response caching

An MVC response can be cached on client side using [OutputCache].
e.g.
public class UserController : Controller
{
[OutputCache(Duration = 60, VaryByParam = "None")] // Duration in seconds
public ActionResult List()
{
try
{
UserCache objUsers = new UserCache();
return View(objUsers.GetUsersList());
}
catch (Exception ex)
{
throw ex;
}
}
}

Object Caching in ASP.NET

System.Web.Caching.Cache is used to cache objects on serverside.
e.g.
public IQueryable<User> GetUsersList()
{
UserModel objUsers = new UserModel();
if (HttpContext.Current.Cache["USERS"] == null)
HttpContext.Current.Cache.Add("USERS", objUsers.GeFakeUserList(), null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(20), CacheItemPriority.NotRemovable, null);
return (IQueryable<User>)HttpContext.Current.Cache["USERS"];
}
 

Tuesday, November 2, 2010

Razor Parser without MVC

Razor Parser that parses a razor template, generate c# class on the fly, executes the assembly and returns output string.
Another excellent post can be found here. http://www.fidelitydesign.net/?p=208


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.CodeDom;

using System.CodeDom.Compiler;

using System.Web.Razor;

using System.Web.Razor.Generator;

using System.Web.Razor.Parser;

using System.Web.Razor.Text;

using System.IO;

using System.Text.RegularExpressions;

using System.Diagnostics;

using Microsoft.VisualBasic;

using Microsoft.CSharp;

using RazorEngine.Templating;



namespace RazorLibrary

{

    public class Razor

    {

        public string GetRazorOutput(string template, T model)

        {



            Type modelType = typeof(T);  // Get type of model



            var codeDom = new CSharpCodeProvider(); // Will be used to generate source code on the fly and compile the assembly



            //Generate a razor class generator where class name is GeneratorClass with Namespace Razor.Dynamic

            CSharpRazorCodeGenerator generator = new CSharpRazorCodeGenerator("GeneratorClass", "Razor.Dynamic", null, new RazorEngineHost(new CSharpRazorCodeLanguage()));



            // Will be used to Parse Razor template

            var parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser()); // Razor Parser with C# and Html

            // Razor requires clear, execute, write and WriteLiteral methods which are defined in TemplateBase

            Type baseType = (modelType == null) ? typeof(TemplateBase) : typeof(TemplateBase<>).MakeGenericType(modelType);

            // Add base class to the generated class i.e. public class GeneratorClass : RazorLibrary.TemplateBase>

            generator.GeneratedClass.BaseTypes.Add(baseType);



            using (var reader = new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(template))))

            {

                parser.Parse(reader, generator); // reader:Input stream and generator:visitor Pattern

            }

            var builder = new StringBuilder();



            using (var writer = new StringWriter(builder))

            {

                // Generate source code into writer, using code generator

                codeDom.GenerateCodeFromCompileUnit(generator.GeneratedCode, writer, new CodeGeneratorOptions());

            }

            var @params = new CompilerParameters();

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())

            {

                @params.ReferencedAssemblies.Add(assembly.Location);

            }



            //The call to CompileAssemblyFromSource is where the assembly gets compiled. This method takes the parameters object and the source code, which is a string

            var result = codeDom.CompileAssemblyFromSource(@params, new[] { builder.ToString() });

            if (result.Errors != null && result.Errors.Count > 0)

                throw new Exception("Error in compilation."); // This can be made better by creating custom exceptions handler to traverse the errors collection

            // Create an instance of Razor.Dynamic.GeneratorClass

            ITemplate instance = (ITemplate)result.CompiledAssembly.CreateInstance("Razor.Dynamic.GeneratorClass");

            var Templates = new Dictionary<string, ITemplate>();

            if (instance is ITemplate)

                ((ITemplate)instance).Model = model;



            instance.Execute();

            return instance.Result;



        }

    }

}


Tuesday, October 12, 2010

JQuery Template Plugin

JQuery officially released new plugins. Please check here . http://blog.jquery.com/2010/10/04/new-official-jquery-plugins-provide-templating-data-linking-and-globalization/

Example.
I would describe only main steps.

Step 1. Include file
<script src="<%= Url.Content("~/Scripts/jquery.tmpl.js") %>" type="text/javascript"></script>
Step - 2.  Template Structure :
<
<table width="100%">
<tr id=rec${UserName}>
<td width="20%">${FirstName}</td>
<td width="20%">${LastName}</td>
<td width="20%">${UserName}</td>
<td width="20%">${Email}</td>
<td align="center" width="5%" title="Edit"><img src="<%
<td align="center" width="5%" title="Delete"><img src="<%
</tr>
</table>
script id="userTemplate" type="text/x-jquery-tmpl"> =Url.Content("~/Images/IconEditRecord.png") %>" alt="Edit" onmouseover="this.style.cursor='pointer';" onclick=showdialog('${UserName}'); /></td>=Url.Content("~/Images/IconXRed.png") %>" alt="Delete" onmouseover="this.style.cursor='pointer';" onclick="deleteUser(this,'${UserName}');" /></td></

Step 3 - Where to render
<table id="UserList">

Step 4 - Ajax Call and Append Data
 



Monday, October 11, 2010

Powershell script that uses 7-zip to compress all files in a parameterizable folder

Powershell script that uses 7-zip to compress all files in a parameterizable folder that match the file pattern provided by the user.Any file that has not been modified in more than a particular time will be compressed. The compressed archive should be verified using the command-line compression tool. Once the compressed archive is validated, then the original file should be deleted. All arguments should be passed to the script at the command-line.
(Please not that this script has not been fully tested and can really be harmful for the system, try it at your own risk :D)

Param
($SourcePath = $(Read-host "Please enter the source directory path e.g. d:\data\")),
($TargetPath = $(Read-host "Please enter the target path e.g. d:\all\archive.zip")),
($Days = $(Read-Host "Files older than days?")),
($Pattern = $(Read-Host "Enter file pattern, e.g. *.txt"))
$CurrentDate = Get-Date
$LimitDate = $CurrentDate.AddDays(-$Days)
$Files  =  get-childitem $SourcePath  -include $Pattern -recurse | where {$_.LastWriteTime -le $LimitDate}
$FileNames = ""
foreach ($File in $Files)
{
write-host "File Name : $File " $File.LastWriteTime
$FileNames = $FileNames + " " + $File 
}
write-host "Files to compress : " $FileNames
if($FileNames.Trim() -ne "")
{
powershell  "&'c:\program files\7-zip\7z'" a $TargetPath   $SourcePath+$Pattern
#powershell.exe  "&'c:\program files\7-zip\7z'" t $TargetPath *.* -r
        foreach ($File in $Files)
 {
 write-host "Deleting file :"$File
 remove-item $File
 }
}
else
{
write-host "No files to compress"
}

write-host "Operation successful!"

Test 7zip archive

7z t archive.zip *.doc -r
Test the integrity of .doc files in the archive. where -r is recursive (subdirectories) switch.

7z t archive.zip *.* -r
Test the integrity of all files.

Friday, October 8, 2010

Powershell script to compress files

I have used 7zip as a command line compression tool.  http://www.7-zip.org/
Following script compresses all files that match specific file pattern e.g. *.txt, *.doc, *.png etc.
It should also work with Universal Naming Convention(UNC) Paths. e.g.
file://10.10.10.63/SharedDocs/archive.zip  etc.

$Path = $(Read-Host "Enter Path and file pattern e.g. c:\zip\*.txt")
$Files  =  get-childitem $Path  -include $Pattern -recurse
$FileNames = ""
foreach ($File in $Files)
{
write-host "File Name : $File " $File.LastWriteTime
$FileNames = $FileNames + " " + $File 
}
write-host "Files to compress : " $FileNames
if($FileNames.Trim() -ne "")
{
powershell.exe -noexit "&'c:\program files\7-zip\7z'" a c:\target\archive.zip $FileNames
}
else
{
write-host "No files to compress :D"
}