Thursday, 9 February 2012

SQL Server GROUPING SETS

DECLARE @Products TABLE (
  Product varchar(50),
  Category varchar(50),
  Price float
)
INSERT INTO @Products
SELECT 'Sugar','Groceries',2.35
UNION SELECT 'Bread','Groceries',1.09
UNION SELECT 'Ecomonist','Magazines',4.99
UNION SELECT 'FT','Magazines',2.99
SELECT Product,Category, SUM(Price) AS Price, COUNT(*) AS [Count]
FROM @Products
GROUP BY GROUPING SETS((Product),(Category),())
ORDER BY Product DESC, Category DESC, Price DESC, [Count] DESC
SELECT Product,[Range], SUM(Price) AS Price, AVG(Price) AS AvgPrice
FROM (
 SELECT 
	Product, 
	Price,
	[Range] = 
		CASE WHEN Price BETWEEN 0 AND 1 THEN '1$'
			 WHEN Price BETWEEN 1 AND 2 THEN '2$'
			 WHEN Price BETWEEN 2 AND 3 THEN '3$'
		     WHEN Price BETWEEN 3 AND 4 THEN '4$'
		     WHEN Price BETWEEN 4 AND 5 THEN '5$'	
		END
 FROM @Products 
) a
GROUP BY GROUPING SETS((Product),([Range]))
HAVING [Range] IS NOT NULL
ORDER BY Product DESC, [Range] DESC

image

Tuesday, 7 February 2012

C# Compare default(T) values

[TestFixture]
public class TestDefaultValue
{
	[Test]
	public void Test()
	{
		Assert.IsTrue(Helper<string>.IsDefault(default(string)));            
		Assert.IsTrue(Helper<string>.IsDefault(null));
		Assert.IsFalse(Helper<string>.IsDefault(""));
		Assert.IsFalse(Helper<string>.IsDefault("hello"));
	}        
}
public class Helper<T>
{
	public static bool IsDefault(T value)
	{
		if (EqualityComparer<T>.Default.Equals(value, default(T)))
		{
			return true;
		}
		return false;
	}
}

Tuesday, 24 January 2012

C# Runtime Error: Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

Add <startup> tag to the bottom of app.config file
<?xml version="1.0"?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

Thursday, 19 January 2012

C# Get server IP address

public static string GetIPAddress(string server)
{
    var host = Dns.GetHostEntry(server);
    if(host.AddressList.Length>0)
    {
        return host.AddressList[0].ToString();
    }
    return null;
}

Thursday, 12 January 2012

C# T4 Templating Engine

VS2010 build in templating engine.

Add new ‘Preprocessed Text Template’ called T4Template.tt to your project that looks like that

<#@ template debug="true" language="C#"#>
<#@ parameter name="FirstName" type="System.String" #>
Now: <#= DateTime.Now.ToString() #>
FirstName: <#= FirstName #>
This is a sample program to run the template
class Program
{
    private static void Main(string[] args)
    {
        var template = new T4Template();
        template.Session = new Dictionary<string, object>();
        template.Session.Add("FirstName", "John");
        template.Initialize();
        Console.WriteLine(template.TransformText());
    }
}

and output

Now: 12/01/2012 10:42:07
FirstName: John

C# Razor Templating Engine

Templating engine built upon Microsoft's Razor parsing technology
http://razorengine.codeplex.com/

Add new text file to your project called ‘RazorTemplate.txt’ that looks like that
Hello @Model.Name! Welcome to Razor!
This is a sample program to run the template
class Program
{
    private static void Main()
    {
        var template = File.ReadAllText("RazorTemplate.txt");
        var result = Razor.Parse(template, new {Name = "John"});
        Console.WriteLine(result);
    }
}
and output
Hello John! Welcome to Razor!

another example with custom model

//template
@inherits RazorEngine.Templating.TemplateBase<RazorSample.RazorModel> 
Hello @Model.Name! Welcome to Razor!
//Test
namespace RazorSample
{
    [TestFixture]
    class Tests
    {
        [Test]
        public void Test()
        {
            var template = File.ReadAllText("RazorTemplate.txt");
            var result = Razor.Parse(template, new RazorModel(){Name="John"});
            Console.WriteLine(result);
        }
    }
    public class RazorModel
    {
        public string Name { get; set; }
    }
}

Monday, 24 October 2011

Migrating from Subversion to Mercurial

This is an alternative way of migrating from SVN to Mercurial using HgSubversion as oppose to using convert extension. It allows you to push changes from local Mercurial repository to both Subversion and Mercurial during the transition period.

  • Install HgSubversion

hg clone http://bitbucket.org/durin42/hgsubversion/ <local-path>\hgsubversion

  • Add HgSubversion extension to your main hgrc file

[extensions]
hgsubversion = <local-path>\hgsubversion\hgsubversion

  • Clone existing subversion repository

hg clone http://<username>@<svn-project-path> <local-project-folder>

  • Edit project .hgrc file (/hg/.hgrc)

[paths]
default = http://<username>@<hg-remote-project-path>
svn = http://<username>@<svn-project-path>

  • Create new mercurial project in your remote Hg repository (see Rhodecode)
  • Pushing the project to remote mercurial repository

hg push

  • Pushing to subversion

hg push svn

If you’re using mercurial_keyring extension to store Hg passwords and your Svn username is the same as Hg one you need to have the same password for both.

Tuesday, 18 October 2011

Save window size & position in WPF

* Right Click on Settings.settings and Open With XML (Text) Editor

* Add Top, Left, Height, Width & WindowState settings

<Settings>
  <Setting Name="Top" Type="System.Double" Scope="User">
    <Value Profile="(Default)">50</Value>
  </Setting>
  <Setting Name="Left" Type="System.Double" Scope="User">
    <Value Profile="(Default)">50</Value>
  </Setting>
  <Setting Name="Height" Type="System.Double" Scope="User">
    <Value Profile="(Default)">800</Value>
  </Setting>
  <Setting Name="Width" Type="System.Double" Scope="User">
    <Value Profile="(Default)">1200</Value>
  </Setting>
  <Setting Name="WindowState" Type="System.Windows.WindowState" Scope="User">
    <Value Profile="(Default)">Normal</Value>
  </Setting>
</Settings>
* Add Settings property to App.xml
<Application.Resources>
    <properties:Settings x:Key="Settings" />
</Application.Resources>
* Add OnExit override to persist the settings when exiting application
protected override void OnExit(ExitEventArgs e)
{
    base.OnExit(e);
    Settings.Default.Save();
}
* Add Top, Left, Height, Width & WindowState bindings to your MainWindow
<Window x:Class="TestApp.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="MainWindow"
  Top="{Binding Source={StaticResource Settings}, Path=Default.Top, Mode=TwoWay}"
  Left="{Binding Source={StaticResource Settings}, Path=Default.Left, Mode=TwoWay}"
  Width="{Binding Source={StaticResource Settings}, Path=Default.Width, Mode=TwoWay}"
  Height="{Binding Source={StaticResource Settings}, Path=Default.Height, Mode=TwoWay}"
  WindowState="{Binding Source={StaticResource Settings}, Path=Default.WindowState}">

Monday, 19 September 2011

RhodeCode open source HG (Mercurial) server

Download RhodeCode
* http://rhodecode.org/

Prerequisites
* Install Python 2.5 or later http://www.python.org/download/
* Add to PATH \Python27 and \Python27\Scripts folders
* Install SetupTools http://pypi.python.org/packages/2.7/s/setuptools/

Create \RhodeCode folder

Install RhodeCode
* easy_install rhodecode

Configure RhodeCode
* paster make-config RhodeCode production.ini
* paster setup-app production.ini

Run RhodeCode
* paster serve production.ini

Server is now running here http://localhost:8000

To change default host:port edit production.ini file

More info about installation and setup
http://packages.python.org/RhodeCode/installation.html
http://packages.python.org/RhodeCode/setup.html

Friday, 16 September 2011

C# Deep & Shallow Copy/Clone

class Program
{
  static void Main(string[] args)
  {
    var parent1 = new Parent() {Id = 1};
    parent1.Children = new List<Child>();
    parent1.Children.Add(new Child() { Name = "One" });
    parent1.Children.Add(new Child() { Name = "Two" });
    var parent2 = new Parent() { Id = 2 };
    parent2.Children = new List<Child>();
    parent2.Children.Add(new Child() { Name = "One" });
    parent2.Children.Add(new Child() { Name = "Two" });
    var parent3 = new Parent() { Id = 3 };
    parent3.Children = new List<Child>();
    parent3.Children.Add(new Child() { Name = "One" });
    parent3.Children.Add(new Child() { Name = "Two" });
    var parentShallowCopy = parent1.ShallowCopy();
    var parentDeepCopy = parent2.DeepCopy();
    var parentDeepClone = parent3.DeepClone();
    Console.WriteLine("ORIGINAL(1) : {0}", parent1);
    Console.WriteLine("SHALLOW COPY: {0}", parentShallowCopy);
    Console.WriteLine("ORIGINAL(2) : {0}", parent2);
    Console.WriteLine("DEEP COPY   : {0}", parentDeepCopy);
    Console.WriteLine("ORIGINAL(3) : {0}", parent3);
    Console.WriteLine("DEEP CLONE  : {0}", parentDeepClone);            
    parentShallowCopy.Children[0].Name = "Zero";
    parentDeepCopy.Children[0].Name = "Zero";
    parentDeepClone.Children[0].Name = "Zero";
    Console.WriteLine("");
    Console.WriteLine("ORIGINAL(1) : {0}", parent1);
    Console.WriteLine("SHALLOW COPY: {0}", parentShallowCopy);
    Console.WriteLine("ORIGINAL(2) : {0}", parent2);
    Console.WriteLine("DEEP COPY   : {0}", parentDeepCopy);
    Console.WriteLine("ORIGINAL(3) : {0}", parent3);
    Console.WriteLine("DEEP CLONE  : {0}", parentDeepClone); 
    Console.ReadLine();
  }
}
[Serializable]
class Parent
{
  public int Id { get; set; }
  public List<Child> Children { get; set; }
  public Parent ShallowCopy()
  {
    return (Parent)this.MemberwiseClone();
  }
  public Parent DeepCopy()
  {
    Parent other = (Parent)this.MemberwiseClone();
    other.Children = new List<Child>();
    this.Children.ForEach(x => other.Children.Add(x.DeepCopy()));            
    return other;
  }
  public override string ToString()
  {
    var sb = new StringBuilder();
    sb.AppendFormat("[Id:{0},Children:[", Id);
    Children.ForEach(x => sb.AppendFormat("{0},", x.ToString()));
    sb.Remove(sb.Length - 1, 1);
    sb.AppendFormat("]]");
    return sb.ToString();
  }
}
[Serializable]
class Child
{
  public string Name { get; set; }
  public override string ToString()
  {
    return string.Format("{0}", Name);
  }
  public Child ShallowCopy()
  {
    return (Child)this.MemberwiseClone();
  }
  public Child DeepCopy()
  {
    return (Child)this.MemberwiseClone();                        
  }
}
//extends classes that are marked [Serializable]
public static class ExtensionMethods
{        
  public static T DeepClone<T>(this T a)
  {
    using (MemoryStream stream = new MemoryStream())
    {
      BinaryFormatter formatter = new BinaryFormatter();
      formatter.Serialize(stream, a);
      stream.Position = 0;
      return (T)formatter.Deserialize(stream);
    }
  }
}