Friday, January 28, 2011

Important Classes in MEF

MEF is great. It is one of the best things that has come along in .NET 4.

Just reading the greatest beginner tutorial on MEF ever : http://blogs.msdn.com/b/brada/archive/2008/09/29/simple-introduction-to-composite-applications-with-the-managed-extensions-framework.aspx

Class names have changed in the release version of MEF that comes with .NET 4 in the System.ComponentModel.Composition namespace. Also while going through it I cannot help but think that I am not absorbing all of it. Generally the best idea to make sure you learn something is to write it down.
So here is my attempt:


Concepts
Exporting:
MEF works on attributes.
For exporting data you just mark the property you want to export with [Export] attribute
By default it will take the property type as the key to export. So you will generally want to [Export("Foo")]
e.g
[Export("Foo")]
public string Foo{get;set;}

Importing:
At the target you have an option of either [Import("Foo")] or [ImportMany("Foo")] depending on whether there will one Export or many Export items contained in catalogs (explained next).
e.g
[Import("Foo")]
public string Foo{get;set;}
OR
[ImportMany("Foo")]
public IEnumerable Foo {get;set;}

If multiple exports are found but you only have an import an exception is thrown in Compose (explained below)

Catalog:
First you make a catalog. This will contain a list of places that will Export the data you need.
Types of catalogs (Contained in System.ComponentModel.Composition.Hosting). Overload Constructs can be found at the MSDN documentation as linked:

  • AggregateCatalog(); For collecting a number of catalogs into one. 
    • Usage:
      var catalog = new AggregateCatalog();
      catalog.Catalogs.Add(othercatalogs); 
  • DirectoryCatalog(string directoryPath);
    • Usage: The string directoryPath can also be relative URLs. 
  • AssemblyCatalog(Assembly assembly);
    • Usage: generally will load the current assembly in this (Assembly.GetExecutingAssembly()). Since foreign assemblies are better loaded through DirectoryPartCatalog. 
CompositionContainer
After you have all your catalogs (either one of DirectoryPartCatalog/AssemblyCatalog or a combination of them as AggregateCatalog) you will load them into a composition container:

var container = new CompositionContiner(catalog); 

Finally Fix Up the exports into imports: 
container.ComposeParts(this);

Where this will be the instance of a class where you have the Import attributes setup. 
If everything is fine you get no exceptions and your exports have been loaded into imports.
Note: ComposeParts is actually an extension method with params. So you can do : 
comtainer.ComposeParts(classInstance1,classInstance2);
etc. 

Enjoy!

Sunday, January 23, 2011

Recovering a Report Server when you have SQL Server rights

Simply change the executing service account of your report server. Make sure that account has full access to sql server. Afterwards login with that account and access your Report Manager URL. Simple isn't it?

You might need to restart the machine for it to work though :)

Saturday, January 22, 2011

Cinch and snippets love

Cinch comes with an awesome set of code snippets you can download here (from the cinch codeplex project page).

Installation
To install them just copy the .snippet files from the zip you downloaded to one of the following:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#
C:\Program Files\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#

This is the default location for VS 2010 snippets as viewed from Tools > Code Snippets Manager > My Code Snippets.

You do not need to restart visual studio 2010 for these snippets to become effective.

Usage
In case you are unfamiliar with snippets usage. Just type in cinch and you get this:
press tab again and you get : 


Press a number for a particular snippet and press tab again. You should get the code expanded.
Some code snippets contain code that you need to copy into the constructor for your ViewModel.



Enjoy!

Setting up a mercurial repository with bitbucket and Visual Studio awesomeness

Bit Bucket is awesome. The best thing about is that they provide private repositories for free! As long as you have lesser than 5 users. This is great for a consultant developer. Ofcourse if you are a consultancy you will probably upgrade.

A great tutorial for Mercurial by Joel is available here.

Anyways. Here is a quick way to get started with mercurial with visual studio. There are the things you need to do once. And then the things you need to to for each repository.

One time stuff

  • Signup for bitbucket
  • Download and install TortoiseHg.
  • Download and install VisualHg
  • Start Visual Studio. Goto Tools->Options. Select SourceControl. Select VisualHg from the drop down. Click Ok.
  • Select any folder On your computer where you will working off. Right click in windows explorer. And select Global Settings as shown.
  • click edit file and setup your bit bucket username / password and save the file.
For each new Software Development Contract
  • Goto bitbucket and create a new repository. Selecting whether you need to keep it private or not. e.g. https://bitbucket.org/basarat/mvvm-dotnet-samples
  • Right click (anywhere inside OR on) a folder (e.g. F:\temp\DotNetMVVM) that you will be working from. Select TortoiseHg -> clone. Type in the repository URL as the source path. e.g.   https://basarat@bitbucket.org/basarat/mvvm-dotnet-samples.
  • Now create a new Visual Studio project in that folder. Its better if you Check "Create a Solution Folder". Name the solution same as the folder you cloned to e.g. "DotNetMVVM" and give the solution path of one level up e.g. "F:\temp". This is shown:
  • If you set it up right as soon as the project / solution opens you will see the source control icons in Visual Studio (These are actually determined by the presence of .hg in the SAME folder as your sln file) :
  • Just right click the solution and select HgCommit. Enter the message. This will commit to your local repository. Finally to update the server when your code is nice and ready (and you want to inflict it on the world) select hg synchronize and then push. Type in your password. 
  • Also you can permanently store you password by clicking configure -> synchronize -> Edit as shown:
Trouble shooting tortoiseHG:


TortoiseHg does not show any dialog
Setting up at another machine tortoise Hg stopped working. If I right click in windows explorer and select any item from the TortoiseHg submenu nothing came up. This is probably due to an error in the global settings file. 

I navigated to "C:\Program Files\TortoiseHg" (where I had installed tortoisehg) and just ran the hg command in the command prompt:


I had some mistake in my global settings. (Note that it gave me the global settings path as c:\users\ebasali\mercurial.ini) 
I just edited it manually to remove the erroneous lines.
You get a Url open error while cloning the repository:
Sample Error:
""

If you are using a proxy server make sure you enable it in global settings:

After this you can check use proxy server in clone.

Note: Mercurial cannot detect your internet explorer settings so you need to do this manually.

Enjoy!

Update: I got this T-Shirt as a thank you for this post. Totally not required but totally appreciated mates :)

Update March 2011: I also really liked this tutorial : http://mercurial.aragost.com/kick-start/en/basic/#divergent-lines-of-development

Update June 2011: There is another quite nice workflow. I havent made screenshots of it yet but here it is:

  •  right click while in the root folder which you want to be managed by mercurial and select Tortoise Hg -- Create Repository here. Select Ok.
  • Right click while in the folder and select Tortoise Hg -- Synchronize. Select configure. Setup the bitbucket path / password as before. And finally push. 

Wednesday, January 19, 2011

WCF End to End tracing sample

An year into the tech and I just found out that WCF now comes with an End to End tracing sample.
Check out the "Extended Tracing" sample here:
http://msdn.microsoft.com/en-us/library/aa354511.aspx

You can run it with setting up IIS as well.

  • Just check out service properties "Specific Port" and set it as 3333.
  • Open App.config and modify the endpoint address to be "http://localhost:3333/service.svc"
  • I recommend you add to the section in web.config http://dotnetmind.blogspot.com/2008/07/step-into-wcf-service.html 
  • Make sure you create the folder  "C:\logs\"
  • Run the sample
  • You should get two new files (you might need to stop the development server)
    • ExtendingTracing-client.svclog
    • ExtendingTracing-service.svclog

Tuesday, January 18, 2011

Ibrahim Bilal Underpants


These are ibrahim bilal's underpants :
Well probably not. But no one said google was perfect.


A friend of mine once said : Something I can't find on google ... Underpants


http://www.google.com/profiles/114894614475346067248

I decided to change that.

For SEO I would like to mention that this is Ibrahim Bilal's Underwear. And Ibrahim Bilal is prime in this post. Totally Prime. The key focus. The most important thing EVER and of course his Underpants. And to think just yesterday I was reading about how good software companies will have their software functional spec written as humor. So what would be the functional spec of Ibrahim Bilal Underpants if you were to write one.

So the Functional Specification of this software: 

Disclaimer
Ibrahim bilal underpants spec version 1 is incomplete till it is the number one google result
Scenario
Ibrahim bilal wakes up in the morning. He googles his underpants. Can't find it. Goes to sleep. We need Ibrahim Bilal Underpants to be on google.
Non goals
These pants will in no way replace his real underpants.
Technical Note: Make sure you check if he wears any if (IbrahimBilal.On().Contains("Underpants"))
Overview
ewwwwwwwwwwwwwwww
Details
  1. Google Ibrahim Bilal Underpants
  2. Look for this page. 
  3. If its the not first result 
    1. Click it. 
    2. Goto 1 (Technical Note: bad programming programming practice. If you actually write this and I know where you live. Sleep with one eye open. In real world use while)
  4. End


Open Issues
None ... phew!

Sunday, January 16, 2011

EloqueraDB is awesome

First off: I am not affiliated with EloqueraDB in any way. I am just a fan of great software and I love writing great software that help people get more done.

It does SQL
I feel fully confident in saying that SQL is the greatest DSL ever for data handling. Period. (A bit out of context but still). Also, It does LINQ. Chose what you want.
Just download the DesktopProject.zip and see the sheer simplicity.

You can embedded it in your application
Copy the two dlls and one exe. Reference them and go.
And if you want to go client server you get get password protected server access. Best of both worlds!


Is up to date
It is available for .NET framework 4. Means I can depend on it taking full advantage of any performance improvements in .NET 4 vs. .NET 3.5 and saves me from additional .NET 4 only installed testing.

Dynamic
You can store dynamic objects. Eloquera DB is selling this as a key differentiator and it is. It makes so many things so easier. Combine this with SQL and dynamic applications are so much simpler.

Its free for non commerical
License. If you need a quick and dirty inhouse tool with data storage. It does not get any simpler than EloqueraDB. Also commercial support is available. It is actually free for commercial as well. But if you use it in a commercial application be nice and buy it.

Simplicity
Check out the sample DesktopApplication that you can download as a zip file from their website. Simple.

Integrates nicely into MVVM. WPF applications can truly be a cinch!
This is perhaps what I love the most. You can use it as a simple ( yet highly queryable ) datastore for  your models. You just make the models implementing INotifyPropertyChanged and have properties that are themselves complex types and just serialize the complete object graph to disk. Here's the DesktopSample silghtly modified to serialize and deserialize an ObservableCollection :

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using Eloquera.Client;
using System.Collections.ObjectModel;

namespace DesktopProject
{
    public class SampleClass
    {
        public int Value { get; set; }
        public string Tag { get; set; }
        public ObservableCollection<string> ObservableCollectionTest { get; set; }
    }

    class Program
    {
        public static void Main(string[] args)
        {
            const string dbName = "SampleDb";

            var DatabasePath = Environment.CurrentDirectory;

            var db = new DB("server=(local);options=none;");

            db.DeleteDatabase(dbName, true);
            db.CreateDatabase(dbName);
            db.OpenDatabase(dbName);

            // Insert your code here

            // Sample LINQ query
            db.Store(new SampleClass() { Value = 123, Tag="Hello " });
            db.Store(new SampleClass() { Value = 124, Tag="Goodbye " });
            db.Store(new SampleClass() { Value = 123, Tag = "World!", ObservableCollectionTest = new ObservableCollection<string>() { "","I","do","lists","too"} });

            var result = from SampleClass sample in db where sample.Value == 123 select sample;



            foreach(var item in result)
            {
                Console.Write(item.Tag);      
                if (item.ObservableCollectionTest!=null)
                    foreach(var listitem in item.ObservableCollectionTest)
                    {
                        Console.WriteLine(listitem);
                    }
            }

            Console.WriteLine();

            // End of sample LINQ query

            db.Close();
        }
    }
}

A time saver. A life saver.

Great Documentation
http://eloquera.com/help/ One of the best i've seen.

An active google group
An active and functional news group by the eloquera team http://groups.google.com/group/eloquera .


I wish this company all the best. It is a breath of fresh air.

Enjoy!

Tuesday, January 11, 2011

Bad Image quality in WPF ribbon

The ribbon from Microsoft performs great with XAML resources however it always made my images look bad. I actually avoided using it for this reason. But Sacha just posted a great solution here : http://sachabarber.net/?p=847 He did it for Images in WPF 4 in general. I just wanted to mention that it makes image quality in Ribbon improve as well. Here is the style he used:


<Window.Resources>
    <Style TargetType="{x:Type Image}">
        <Setter Property="RenderOptions.BitmapScalingMode"
               Value="HighQuality" />
    </Style>
</Window.Resources>

Thursday, January 6, 2011

Setting up a .com for free courtesy of Google

Here's how I setup the following domains: http://basarat.com http://booleanart.com http://about.booleanart.com

All you need is a domain name. That you can buy for a large number of sellers. I chose ServerSea http://serversea.com/
They basically use the OnlineNIC as their domain registrar :
which in turn uses DIY DNS www.dns-diy.net for configuing the dns settings.

Modify the DNS Name Servers
So to start off I login at OnlineNIC and modify the DNS use the DIY-DNS nameservers:
These are "ns1.dns-diy.net" and "ns2.dns-diy.net". Click Modify.

Add CNAME Records routing to Google Servers:
No login to DNS-DIY and add the following CNAME Record:
(As per this the blog will be hosted at about.booleanart.com)

Note the "." in the end : "ghs.google.com."  wait for the settings to take since DNS takes time to propogate.
You can verify from Kloth Dig. Heres how it will look like:


Modify the location in your blogspot account
Now that you have the DNS setup you are good to modify the publishing address of your blogspot account.
Just goto http://draft.blogger.com/ and navigate to the Publishing settings of your blog. Goto advanced settings and setup the CNAME you used. e.g.:

If you verfied the Kloth respose before modifyin the blogspot publishing domain you should most definitely see "Congratulations, your blog is ready!".

Redirecting top level domain to your blog as well
This is optional. Also if you are hosting multiple accounts on blogspot you should set this up for one blog only.
I set http://booleanart.com to http://www.booleanart.com

Setup in DNS-DIY (notice that A records do not have a "." in the end) :
Verified:
And setup in Blogspot check "redirect booleanart.com to www.booleanart.com" :

nowhttp://booleanart.com will redirect to www.booleanart.com

Hiding the blogspot navbar:
This is easy just add the following after your variables declaration in the HTML template:


#navbar-iframe  {
display : none;
height : 0;
visibility : hidden;
}
Source : http://w3onlinesource.blogspot.com/2010/07/how-to-hide-blogspot-blogger-navigation.html



Adding a subdomain not hosted on blogspot
So now I have http://booleanart.com setup and http://www.booleanart.com and http://about.booleanart.com
I want to host http://games.booleanart.com myself.
FYI How I figured it out : I did by basically testing it out on another one of my websites (which had an unmodified nameserver) and added a subdomain in plesk. Looked at the configuration in Kloth.  Here's what I found out:



Account for uploading (Required Only Once)
The ftp.booleanart.com also needs to exist to allow file uploading :



Add a subdomain A record in DIY DNS: 
The domain is shared hosted on the server with IP address "174.133.142.98" added an A record accordingly:


Verified from Kloth:


Add a subdomain in plesk: 


And:



That's it. Enjoy!

Tuesday, January 4, 2011

Setting the current working directory to the current application

Here's how you can set the current working directory to the currently executing application in .NET:


Directory.SetCurrentDirectory(GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));



And you can get the current working directory from Directory.GetCurrentDirectory

Monday, January 3, 2011

Taking regular backups of all files in a particular folder to another partition

A simple batch file that I have setup as a cron along with other server cron jobs (using pycron). The contents of the batch file:


REM rmdir "c:\FUTURE\" /s /q
REM mkdir "c:\FUTURE\"
xcopy "D:\FUTURE" "c:\FUTURE\" /y /E


The items in REM are for when I need to start anew otherwise not required (and in fact dangerous for the time when D goes down and data from c just gets deleted).

My ideal project structuring

Everyone has their own opinion of how to structure their projects without file structure bloat.
Here's how I manage it:

  • A root folder to contain all code I am currently working on
    • A Folder for each Solution ... each folder is checked into some source control.
      • A folder for each project
      • A folder for LIBS containing built libraries used by the project
      • An Debug folder containing the Debug output 
      • A Release folder containing the Release Ouput
      • A Publish folder containing the Obfuscated Ouput I am going to send out
    • (LARGE REUSE preferably at one location) A LIBS folder which contains the source code or downloads / help pages of libaries in their own folder e.g. a folder for avalondock extracted in it is its source code and build directories etc. Copy paste from this into LIBS folder in each solution so that when checked in third parties would not have issue finding the built libraries I used. 
    • (LARGE REUSE preferably at one location) A Media folder containing all the images / sounds that I could possible desire. Copy paste from this into projects. 

That is it. Simple, clean, efficient and effective.

How many times do the hours and minutes hand overlap in 24 hours

There is a simple mathematics to this puzzle. All you have to do is 
  • find the time interval it takes for the first overlap to occur
  • inverse it to get overlaps per hour
  • multiply by 24 hours to get the answer.
So, lets find the time interval of the first overlap. 
at T hours and t minutes the location of the minute hand (m) will be (in terms of a circle of 60 degrees):
m = t
and hour hand:
h=5T+(t/60)*5

Equating the two we get:
t=60/11T
So, an overlap occurs after 60/11 minutes in the first hour 
and therefore after 
1+(60/11)/60 hours = 12/11 hours
 therefore overlaps per hour = 11/12 
and in 24 hours = 24*11/12 = 22 overlaps.