• MongoDB-Shell

    MongoDB stores the documents in BSON format. It is a binary serialisation format and a super set of JSON. It has more types than JSON which enables better integration with various languages that support these types. Languages like perl and JS have a smaller type system which can cause problems. ObjectId which uniquely identifies a document in mongodb is also part of the bson specification. id field is the primary key which is of type ObjectId. It is immutable. _Object Id = 4-byte timestamp + machine id + process id + counter

    Read more...


  • MongoDB-Getting Started

    MongoDB is a document database and I won't bore you with details about what it can do. MongoDB makes many claims, they are here. In short, MongoDB is a document database that stores data in a JSON format and then promises to make out lives easier. Installation instruction are varied depending on your OS etc..and the both varieties of bitness are also available. Download

    The shell for MongoDB is a Javascript based one, so if you know a bit of JS then you will fly in there. Start mongod from the command line, this can be done by navigating to the bin directory of installation. Provide the dbpath(the place where it stores the data) as well.

    Mongod

    If you look at the output when we start the daemon (mongod = mongo-daemon) then the last line talks about a rest interface. This can be enable by passing the --rest flag when starting the instance. The port for viewing the webpage is also there.

    Let's get into the mix of things by connecting to this mongod using the shell(mongo.exe). Navigate to the mongo directory and go mongo.exe. By default this connects to the test database. The prompt will say something like

    C:\Users\Ashutosh\mongodb\bin>mongo.exe
    MongoDB shell version: 2.4.1
    connecting to: test
    > 
    

    At any moment you can go back to mongod and check how many connections are open. Run a couple of commands like show dbs show collections to see if everything is in order.

    Create a new database by use yourdatabasename. The shell will switch it's context to that database(after creating it if it does not exist already.) Next, time we will do some stuff by creating some collections and then querying. This will be a longish series, hold on and let me smear you twitter timelines.

    Read more...


  • Python Development in Visual Studio

    What ..you must be mad !!

    IronPython has been around for some time now. Python tools for Visual Studio have recently been given a facelift. It has been lifted to become a more complete tool which we can use for Python development with Visual Studio. I have recently been flirting with Python since it is easier and quicker to just get some stuff done in Python. It can easily be a second language for a C# developer and I do intend to keep it in my toolbox. There are alternatives available including but not limited to PyDev plugin for eclipse and Aptana Studio which comes with all the bells bundled together.

    Read more...


  • Entity Framework - Table Per Type Gotcha

    Entity Framework Table Per Type (TPT) implementation has a little gotcha ( little is really relative ). When we create table per type we will have orphan rows if the parent gets deleted and there will be orphan rows in the parent if the child gets deleted. This causes a funny picture to emerge with very bad consequences.

    Gotcha

    Now, to get around this my simple workaround was to alter the relationships in my seed method.

    context.Database.ExecuteSqlCommand( @"ALTER TABLE [ParikshaDev].[Match] DROP CONSTRAINT [FK_ParikshaDev.Match_ParikshaDev.Questions_QuestionId]" );
    context.Database.ExecuteSqlCommand( @"ALTER TABLE [ParikshaDev].[Match] ADD CONSTRAINT [FK_ParikshaDev.Match_ParikshaDev.Questions_QuestionId] FOREIGN KEY (QuestionId) REFERENCES [ParikshaDev].[Questions] (QuestionId) ON DELETE CASCADE" );
    
    context.Database.ExecuteSqlCommand( @"ALTER TABLE [ParikshaDev].[Brief] DROP CONSTRAINT [FK_ParikshaDev.Brief_ParikshaDev.Questions_QuestionId]" );
    context.Database.ExecuteSqlCommand( @"ALTER TABLE [ParikshaDev].[Brief] ADD CONSTRAINT [FK_ParikshaDev.Brief_ParikshaDev.Questions_QuestionId] FOREIGN KEY (QuestionId) REFERENCES [ParikshaDev].[Questions] (QuestionId) ON DELETE CASCADE" );
    
    context.Database.ExecuteSqlCommand( @"ALTER TABLE [ParikshaDev].[Choice] DROP CONSTRAINT [FK_ParikshaDev.Choice_ParikshaDev.Questions_QuestionId]" );
    context.Database.ExecuteSqlCommand( @"ALTER TABLE [ParikshaDev].[Choice] ADD CONSTRAINT [FK_ParikshaDev.Choice_ParikshaDev.Questions_QuestionId] FOREIGN KEY (QuestionId) REFERENCES [ParikshaDev].[Questions] (QuestionId) ON DELETE CASCADE" );
    
    context.Database.ExecuteSqlCommand( @"ALTER TABLE [ParikshaDev].[Custom] DROP CONSTRAINT [FK_ParikshaDev.Custom_ParikshaDev.Questions_QuestionId]" );
    context.Database.ExecuteSqlCommand( @"ALTER TABLE [ParikshaDev].[Custom] ADD CONSTRAINT [FK_ParikshaDev.Custom_ParikshaDev.Questions_QuestionId] FOREIGN KEY (QuestionId) REFERENCES [ParikshaDev].[Questions] (QuestionId) ON DELETE CASCADE" );
    

    ForeignKey

    There are things that can be better in this code. We can have the Schema name and the Table name statically typed with the help of the context. The relationship name was arrived at by making an educated guess about the relationships and then confirming them by having a look at the db that was generated previously. I would consider this as a bug in EF. I didn't see any way to configure this behaviour with the fluent api. I expected this to be clearly stated in the documentation or a flag or a switch be made available in the api for configuration.

    Read more...


  • Entity Framework - Migrations

    Migrations are needed in our day to day work and EF migrations story has become a lot better over the last year. When your database changes rapidly then migrations are needed to keep pace. Ofcourse this is nothing new, but it wasn't available in EF before.

    Enable Migrations*

    To enable the migrations go to Tools -> Library Package Manager -> Package Manager Console. Type Enable-Migrations in the console. -Force parameter is optionally available if you want to overwrite an existing migrations.

    Read more...


  • Console2- Command Line Awesomeness

    14 Apr 2013

    1. What is this ? Ever felt that the command prompt fall a little short of your expectations ? You want it to feel like the power toy and not just a tool.

    2. Where do I get it ? You can download it from here Console2

    3. Help me set it up .Scott's Originial Blog Post Refer to Scott Hansleman's blog post

    Now, if you have successfully managed to get Console2 working note carefully what the last part in Scott's post said Console2 is a great little front-end for your existing shell, no matter what it is. Note that Console2 isn't a shell itself, it's just a face on whatever you are already using.

    1. Let's make the world a better place by adding Git Bash to the the tabs.

    Title : GitBash

    Icon : C:\Program Files (x86)\Git\etc\git.ico

    Shell : C:\Program Files (x86)\Git\bin\sh.exe --login -i

    Startup dir : c:\Users\Ashutosh ( or whatever your path is )

    Console2

    All looks nice, the world is a better place.

    Read more...


  • Entity Framework - Generic repository Pattern - Part 2

    • Part 1 - Generic Repositry Pattern
    • Part 2 - Generic Repositry Pattern Contd.

    In the previous post I wrote about an implementation of the Generic Repository pattern for EF. There is so much data on the web that it is difficult to understand what might actually work for you. All of this can drive you Crazy

    Throw in my version of crazy as well. Crazy2

    Read more...


  • TeamCity- Recover Admin Password

    04 Feb 2013

    The trials and tribulations of this world are beyond me. Sometimes, a simple gesture can save your life. I lost(forgot, forgive my small brain it has to keep up with a day job) my TeamCity login details. Searching online will lead you to this place Stackoverflow Post.

    The solution there is mighty correct barring two things. One, your TeamCity data directory path is likely to C:\ProgramData\JetBrains\TeamCity\ on a windows box and not C:\users\foo\TeamCity. Second, you need to run CMD as admin. So,

    Step 1 Stop TeamCity service ( either through services.msc or the bat files ).
    
    Step 2  Open CMD as ADMINISTRATOR
    (don't forget the admin part you will go bonkers trying to figure out what is happening) and go to C:\TeamCity\webapps\ROOT\WEB-INF\lib
    
    Step 3 type -cp server.jar; hsqldb.jar ChangePassword USERNAME PASSWORD C:\ProgramData\JetBrain\TeamCity
    

    If all is successful then you password has been reset and you can login. Here's hoping to a few hours saved for anyone who comes around to reading this.

    Read more...


  • NUnit-Code Snippet

    03 Feb 2013

    What are we doing ? We are trying to create a snippet for creating an NUnit test.

    How do we do this ? We go write a snippet.

    The snippet is here Snippet

    Save it under

    ..\Documents\Visual Studio 2012\Code Snippets\Visual C#\My Code Snippets
    

    Now go add the snippet. Go to Tools in VS -> Code Snippets Manager -> and Import after clicking on the Snippet. That's it, we are done.

    Read more...


  • Useful Extension Methods

    03 Feb 2013

    Extension methods provide a very useful way of extending the functionality of a Type (value, reference or interface). The earlier way of extending or rather adding a functionality through inheritance or making an entirely new type from scratch were tedious to say the least. Extension methods are basically static methods with the calling syntax same as that of static methods. Over the course of the last few weeks i have come to realise they reduce a lot of repetitiveness from the code when used appropriately.MSDN specification also clearly states they must be used sparingly. So,here are a few useful extension methods. The syntax has only one new thing, the use of this keyword on the type that the extension method is meant for.

    public static XElement ToXElement(this XmlNode node)
    {
       var xDoc = new XDocument();
       using (var xmlWriter = xDoc.CreateWriter())
              node.WriteTo(xmlWriter);
       return xDoc.Root;
    }
    

    So, calling the code would be something like ,

    var xelement = node.ToXElement();
    

    xelement is now an XElement. This might look very plain and simple at the outset but when you really start to have a lot of repetitive functionality over a type this could really bail you out and make the code more readable to say the least. For e.g inside a for loop if you have a lot of code that operates over a type then it could be useful to take it to an extension method and then call the extension method statically.Further, extension methods can also have overloads so that is another nifty feature. The following extension method returns the XmlAttributeCollection for a XmlNode

    public static XmlAttributeCollection GetXmlAtrributeCollection(this XmlNode node)
    {
        var xmlDoc = new XmlDocument();
        var element = node.ToXElement();
        using (var reader = element.CreateReader())
        {
          xmlDoc.Load(reader);
          return xmlDoc.DocumentElement != null ? xmlDoc.DocumentElement.Attributes : null;
        }
    } 
    

    Too much of XML ?? Lets get one really useful extension method. Lookup is an immutable class in System.Linq. It works similar to a dictionary but does not enforce unique keys , so returns an IEnumerable. Unfortunately, the creation of a Lookup is internal to .net. So we can only call ToLookup() from a Dictionary etc. So ,i needed some way of adding data to the Lookup.Here is what i came up with.

    public class Pairs 
        {
            public String Key { get; set; }
            public Object Value { get; set; }
        }
    public static class LookupExtensionMethods
        {
            public static Lookup<String,Object> AddToLookup(this Lookup<String,Object> lookup,
                                                           List<Pairs> pairlist)
            {
                var temp = (Lookup<String, Object>)pairlist.ToLookup(p => p.Key, p => p.Value);
                lookup.Concat(temp);
                return lookup;
            }
    
        public static Lookup<String, Object> AddToLookup(this Lookup<String, Object> lookup, Pairs pair)
        {
            var pairlist = new List<Pairs> {pair};
            var temp = (Lookup<String, Object>)pairlist.ToLookup(p => p.Key, p => p.Value);
            lookup.Concat(temp);
            return lookup;
        }
    }
    

    Lastly, there is no way to replace the first occurrence of a string in C# straight out of the box(I bet you did not notice that).

     public static string ReplaceFirstOccurrance(this string original, string oldValue, string newValue)
     {
         if (String.IsNullOrEmpty(original))
                    return String.Empty;
         if (String.IsNullOrEmpty(oldValue))
                    return original;
         if (String.IsNullOrEmpty(newValue))
                    newValue = String.Empty;
         var loc = original.IndexOf(oldValue);
         return loc == -1 ? original : original.Remove(loc, oldValue.Length).Insert(loc, newValue);
     }
    

    Suddenly, the world seems a lot better.

    Read more...