Tuesday, December 28, 2010

Having a setter for an Observable Collection

Here's another cool way to override the getter for an observable collection without breaking your MVVM:


private ObservableCollection<string> _AvailableColumns = new ObservableCollection<string>();
        public ObservableCollection<string> AvailableColumns
        {
            get { return _AvailableColumns; }
            set
            {
                _AvailableColumns.Clear();
                foreach (var item in value)
                {
                    _AvailableColumns.Add(item);
                }
            }
        }

Now you can use it like :


new RequiredColumn() {RequiredColumnName="BSC",DefaultValue="",AvailableColumns=AvilableColumns};


and it will not break your notification changes :)

Sunday, December 19, 2010

Mediator for MVVMLight like the one by SachaBarber and Marlon

I am loving and using MVVMLight V3 for everything I can find. However there is one thing I feel missing in the Messenger. You can send messages of a particular type using GenericMessage<T> however you cannot send a particular message other than resorting to Magic Strings.

This is where the mediator implementation by sacha barber comes in : http://sachabarber.net/?p=477
I really like his implementation (which in turn was a simple modification of marlon's code).

I really liked that you can just signup for messages identified by a particular enum rather than a particular type (the MVVMLight way). 

However thanks to GenericMessage it was super easy to do. But first

What is a mediator
Since the view code behind should be unaware of the VM (view model). And VM should be unaware of other VMs. The only way to state something has happened is to use a Mediator (or a messenger).
More here : http://basaratali.blogspot.com/2010/12/all-you-want-to-know-to-mvvm-with.html

The Code 
All you need to modify below is add your own message enumerations:


public enum ViewModelMessages { SearchSitesStarted = 1 , SearchCellModified = 2 ,UploadSites=3,SelectUploadFile,UploadFileUpdated};
    public class GenericMessages
    {
        public ViewModelMessages MessageType { get; set; }
        public object Payload;   
    }
    public static class Mediator
    {
        public static void Send(ViewModelMessages messageType, object payload)
        {
            Messenger.Default.Send(new GenericMessages { MessageType = messageType, Payload = payload });
        }
        public static void Register(ViewModelMessages messageType, object recipient, Action<object> action)
        {
            Messenger.Default.Register(recipient, (genericMessage) =>
            {
                if (genericMessage.MessageType == messageType)
                {
                    action(genericMessage.Payload);
                }
            });
        }
    }



Sending Messages

Super easy to do:
Mediator.Send(ViewModelMessages.SearchSitesStarted, null);


Receiving Messages

Just as easy:
Mediator.Register(ViewModelMessages.SearchSitesStarted, this, (a) => { MessageBox.Show("Search Started"); });




All you want to know to MVVM with MVVMLight

This is my attempt at helping people finding gaps in their knowledge regarding MVVM. This does not explain the items presented in bold. The objective is that if you are unclear about what I mean you will google the terms in bold and be on your way. Happy reading!

WHY (or All you ever wanted to know about MVVM)? 
Here are the Four (yes 3+1 ... bear with me) key elements in a MVVM Application :
  1. XAML which contains the binding (Often losely called View)
  2. Code behind for your xaml file (Often losely called View)
  3. View Model
  4. Model
What XAML Knows
  • Now the objective is that XAML knows nothing about your VM other than the fact that it as its datacontext. (I prefer setting it using ViewModelLocator ... it comes for free with MVVM Light. If you use the Project templates that come with MVVMLight it will add it for you). 
  • It knows nothing of the code behind. If it does... you need to make a UserControl to abstract that away. 
  • Elements that have Command property raise commands. Elements that don't should use EventToCommand that comes with MVVMLight. These commands are RelayCommands by the way. 
  • Ofcourse important properties are bound to the viewmodel and use IValueConverters when required

What code behind knows
Almost nothing. 
  • If you feel that your code behind must contain some code then there is probably a component that you are using that is not MVVM Friendly (Contains normal .net properties that you cannot bind to and get change notifications). I suggest you wrap it up in a UserControl and abstract it away into a nice bindable component. 
  • Messages. Also called the Mediator, the Messenger is useful for some events that need to start some GUI function. E.g dialog box. A dialog box should never be placed in VM because that will prevent testing functionality of the VM without resorting to GUI Tests.
What ViewModel Knows
Nothing of the View or the View Code behind or other ViewModels. Its has these means of communication with other items:
  • Bindable properties. Generally the view model will inherit from INotifyPropertyChanged and implement properties that raise the PropertyChanged event. It is preferred that you use the ViewModelBase from MVVMLight.
  • RelayCommands. A part of MVVMLight. Your XAML View raises them using Command property or EventToCommand behaviour.
  • Messages. Again some actions require GUI interaction. The VM is resposible for initiating the message for it but the View code behind is responsible for showing the stuff :) 
What the Model Knows
Your domain object. Only interaction with ViewModel. 
  • You should extend ViewModelBase (or implement INotifyPropertyChanged) for this. This will help you store instances of your model as an ObservableCollection in your ViewModel. 
  • Either there will be some ViewModel that will
    • inherit from your model or 
    • contain it as an ObservableCollection or 
    • Contain an instance as a Bindable Property. 

Finally
Now that wasn't so hard was it. Also if you know all there is to know about Binding, StaticResource, ItemTemplate you should be all set :) 

Enjoy!

Saturday, December 18, 2010

An MVVM Version of Bing Maps with Google / Yahoo / Open Street Maps integrated

I was working with Bing Maps when I found that ZoomLevel and BoundingRect were not Dependency Properties. However you can easily make them since it exposed the ViewChangeEnd event.

Also I wanted to wrap up various types of maps in a simple to use control. I got the tile sources from here
http://pietschsoft.com/post/2010/06/14/Display_Google_Maps_Imagery_using_Bing_Maps_Silverlight_Control.aspx
I just had to update the Satellite view to the latest version since the khm source no longer works.

I made a UserControl out of it. Shared it here : (SourceCodehttp://code.google.com/p/mvvmslmaps/downloads/list
In Action:

Lessons Learned
Just one: I add a MapItemsLayer to the maps in my application so I wanted to redirect the Content Property of the custom UserControl to the Content Property of my bing maps instance.

It was super easy to do :

  • Added the attribute : [ContentProperty("Children")] to your Control. 
  • Added the following as a property : 
             public UIElementCollection Children
            {
                get { return MyMap.Children; }
            }

    This means that when I add a MapItemsControl :

    <Control:MVVMMapControl x:Name="MyMap"> 
                <m:MapItemsControl x:Name="ListOfItems" ItemsSource="{Binding Sites}" ItemTemplate="{StaticResource CellTemplate}" ></m:MapItemsControl> 
            </Control:MVVMMapControl>


    It gets added as a child of my bing maps instance.

    Tuesday, December 14, 2010

    ValueTypes cannot be modified by extension methods

    I was converting a WPF code to silverlight when I noticced that Silverlight does not have the Offset Member method to the point structure. I thought I could get away with a dead simple extension method :

    namespace ConsoleApp 
    { 
    
        public static class SlUtils
        { 
            public static void OffsetSL(this System.Windows.Point p, double CenterX, double CenterY)
            { 
                p.X += CenterX; 
                p.Y += CenterY; 
                // p = new System.Windows.Point(p.X, p.Y); does not help either
            } 
        } 
    
        class Program 
        { 
            static void Main(string[] args) 
            { 
                System.Windows.Point p = new System.Windows.Point(0, 0);
                p.OffsetSL(10, 20);
                Console.WriteLine("{0},{1}", p.X, p.Y); // prints {0,0} // FAIL 
                p.Offset(10, 20);
                Console.WriteLine("{0},{1}", p.X, p.Y); // prints {10,20} 
                Console.ReadKey(); 
            } 
        } 
    } 
    
    I was so wrong :) The extension method cannot modify a value type. What you can do is return from an extension method (instead of void) the value you want... ah well you can't have Everything.

    Enjoy!

    Monday, December 6, 2010

    Exam 70-502 Passed

    The exam was great. Really I am not saying that because of my score. I am saying that because it was much more fun (for me at least) than 70-536. WPF (and now Silverlight) is a technology I am deeply passionate about. Maybe its because of my love for beauty and elegance. Maybe its because I hate to say to someone that adding a really classy button just the way you want it to your application will take me three days.

    PS: I sincerely believe that 70-536 made me a better programmer. You will not catch me asking around about StreamReader or how to determine drives in c#.  Although a quick google search would help you ... but I will not need one ... I hope :) Oh not to mention : http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension.aspx or http://msdn.microsoft.com/en-us/library/wz42302f.aspx (these weren't asked of me ... but I remembered them).

    Now how did I prepare for this exam. 
    Well I have had an eye on WPF for three years. Recommended it to a colleague two years ago (I myself was experimenting with python + flex)  and did a project in WPF about a year and a half ago. Simultaneously I had read the book WPF unleashed (http://www.amazon.com/Windows-Presentation-Foundation-Unleashed-WPF/dp/0672328917).This book is basically what got me really motivated to start doing Microsoft certifications in the first place (I devoted myself to a technology I loved). The official book would not be sufficient without this. Everyone will tell you that. Without this I wouldn't know what {Binding} meant (bind directly to datacontext) or that a style without an explicit key but a targettype gets an implicitly set key.

    It wasn't until mid of this year that I finally got the time to start doing it. First I applied for exam 70-536. Just then the new certifications came out (VS2010). But I really wanted the title WPF technology specialist, so I decided to go with the old certifications anyways. Additionally I don't feel comfortable about doing a certification without an official "book" (VS2010 book isn't out yet). For this I read the book cover to cover one and a half times (second time just the highlights to memorize what I thought deserved memorizing the first time I read it). This is the "book" http://www.amazon.com/MCTS-Self-Paced-Training-Exam-70-502/dp/0735625662/ref=sr_1_5?ie=UTF8&s=books&qid=1291632845&sr=1-5 I loved this book. Without this book I wouldn't have known that there are EnterActions for property triggers.

    I still had time (about a month due to prometric test center being booked in my city) ... I decided to read WPF Unleashed 4 http://www.amazon.com/WPF-4-Unleashed-Adam-Nathan/dp/0672331195 I intend to finish it someday but just got curious about silverlight as it is now. And then I picked up Silverlight 4 Unleashedhttp://www.amazon.com/Silverlight-4-Unleashed-Laurent-Bugnion/dp/0672333368 Now note that I am reading this book after preparing 70-502. This meant I know the value of learning ... really learning every single API that is exposed. And I couldn't put this book down. I simply love it. It showed me how to make my own controls in the very first chapter. I can see XAML now (just like I could see c#). Make my applications Blendable. And I really feel comfortable with MVVM (and yes I have made applications without MVVM ... I am not proud ... and I don't intend to do that ever again). This alone made it the best book on WPF (yes WPF... even though it does not claim it) ever!

    And that's it ... the exam was today morning at 10:30 am ... and the rest is history. Thanks for everyone who waited patiently while I prepared for this exam. Love you mom for tolerating my eternal business and keeping me well fed and energized.

    Monday, November 8, 2010

    Why .NET?

    The question is "Why .NET". Well it really starts with why a Virtual Machine (VM) runtime. The answer for me was :

    When you think of your software running unattended for large periods of time and factor in the time you have to develop said software ... VMs help. 

    Goodbye C++ / C. Hello .NET / JAVA. 
    Now, "Why .NET". Really once you have settled on VM the only options you have for mass consumer targeting are .NET and JAVA. Really. 

    So why .NET is actually a question of "Why not JAVA?" or "What makes .NET Better than JAVA?" 
    Before I continue. Note that a major part of my final year project for BE Telecom was made in JAVA. (A SIP Proxy server). So there was a time that I "Loved" JAVA. 

    JAVA as a language:
    Java still doesn't have true getters / setters. You need to type GetName SetName yourself. If its a standard push it to the compiler please. 
    The reason is that language features need to go through JCPs and it can still take years before it makes it to mass distribution. A non evolving language is either a dead language or a dying language albeit really really slowly (A note on JCP's lack of progress : http://blogs.apache.org/foundation/date/20101209 ). 

    So here are the features I love in C# as it Evolves:
    Properties
    Linq
    Dynamic Types
    Yield (oh it is so hot!)
    Async Programming
    WPF ... okay its a library ... But an AWESOME one at that. Swing just does not come ANYWHERE close anymore

    These will take a long time to make it into JAVA (if ever). JAVA is more focused on APIs rather than the Language itself. And the Desktop APIs still suck. More on that later. 

    Now for the annoyances that already made it to the language. 

    Exception me please:
    You cannot add a new exception throw all of a sudden without the compiler complaining. All for the supposed claim that it will prevent unwanted exceptions. And the fun part. It can be bypassed. Virtualize or late bind much? I do. 
    PS: Mostly people are just forced to catch and ignore exceptions. The compiler actually breeds BAD code. 

    Return:
    Okay I am being sloppy here. But while testing I like to return prematurely from a function sometime. Or maybe I write half the code. Then to test something else I put up a mock return. In JAVA I need to Comment out the remainder of the function just to compile. I prefer the C# version of the warning me but not getting in my way. Just run the code. 

    Swing:
    For those that don't know Swing is the THE premier JAVA GUI framework for the Desktop. What got me was Windows Vista going into the Windows classic look and feel stating "A running program isn't compatible with certain visual elements of windows". I would hate to explain this to my clients. http://www.hanselman.com/blog/SunsJavaJRESwitchesVistaAeroIntoBasicUIScheme.aspx

    Jeff Atwood pretty much explained everything wrong with this in 2007. Its funny how a bad Desktop UI will almost always have a mention of JAVA.
     Oh did I mention desktop applications are what made me fall in love with programming and before Flex (yes it came first)/Silverlight desktop apps are the only place I would be found. Other than "really" trivial PHP scripts :).  PS: JavaFX has terrible penetration for a reason :) 

    I like applications full of power. Desktop is the way. AUTOCAD / MAYA / MAPINFO / MATLAB / MS Office / TEMS  all great applications that are primarily on the Desktop for a reason. And if you are going to go to a runtime. You know which one to choose :). Plus I do Telecom Software. We love the Desktop. Its our home :)

    Java and Lawsuits. So much for "Open": 
    To be fair. Java defends "http://en.wikipedia.org/wiki/Write_once,_run_anywhere" very strongly. But their J2ME is no treat either. 

    Microsoft:
    Well for quite a while (a long long time ago) Microsoft's implementation of JAVA was awesome with great Developer productivity. Till Microsoft got sued for it: http://en.wikipedia.org/wiki/Microsoft_Java_Virtual_Machine
    So Microsoft came up with .NET. Maybe Redmond already had such plans but I don't know. 
    Microsoft responded for being sued by Sun: http://www.internetnews.com/ent-news/article.php/988071/Sun-Sues-Microsoft-Over-Java.htm Java still doesn't come preinstalled in windows. Your hardware vendor might do so. 

    Google:
    Yes. For android. Oracle sues Google for Java derived runtime: http://news.cnet.com/8301-30684_3-20013546-265.html . Google does not attend JavaOne : http://googlecode.blogspot.com/2010/08/update-on-javaone.html

    Oracle is a financial institution
    Oracle defends its profits VERY diligently. 
    They did make MySQL InnoDB commercial as well : http://www.cloudave.com/7356/internal-email-on-why-a-software-company-migrates-away-from-mysql/ (Note the CEO also warns against JAVA). But I saw that (thanks to other intelligent folk on the internet) coming from a mile http://basaratali.blogspot.com/2010/05/free-for-commercial-use-high.html . Postgresql is the future MySQL. 

    Finally Some JAVA love:
    Java is not all that bad. I wouldn't be caught dead writing a JAVA app for the desktop....never again. But for the server of the top of my head GWT is cool. Well at least the results are ... I haven't tried it myself. Pentaho is very cool. JasperReports are amazing. These are not "JAVA" goodness per say but hey a runtime is valued by what it runs. So I guess its third party love :) But for my raw code I still doubt I would ever go there. 

    Fun Java Quotes by People I Respect: 
    If you feel these are taken utterly out of context. Well Quotes usually are so I link to the complete context :)
    Everything on this page is my opinion. I am in no way legally liable for anyone else's actions.
    The last update time for this page should help, since technology changes and JAVA might get these features :) 

    Sunday, November 7, 2010

    Setting up mojoportal on windows 7 64bit with sqlite

    Yes ... these are all technically evaluated requirements :)

    Just downloaded and extracted the "mojoportal-2-3-5-5-sqlite-net35-deploymentfiles.zip" file. 
    Renamed "user.config.sample" to "user.config"
    Defined a new website in IIS 7.5.

    Anyways, First off I noticed my IIS was not working with ASP.net Error
    Calling LoadLibraryEx on ISAPI filter 
    Fixed it using the following: 
    cd C:\Windows\Microsoft.NET\Framework\v2.0.50727
    aspnet_regiis -ir

    Next I got the following error: 
    There is a duplicate 'system.web.extensions/scripting/scriptResourceHandler' section defined

    This is because we are using .NET 4.0 on a .NET 3.5 website :) 
    Just go to IIS application pools and change the runtime to .net 2.0 as shown: 


    Got the following error:

    An attempt was made to load a program with an incorrect format

    Lazy of me. They did mention this one. http://www.mojoportal.com/sqlitesetup.aspx
    Did exactly as they pointed out: 



    Again navigated to:
    http://localhost:8080/Setup/Default.aspx

    Got the following Error:
    Could not load file or assembly 'WebStore.UI' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded


    Downloaded the source code changeset linked to the 2.3.5.5 release.
    Extracted and Opened mojoportal.net35.sln
    Right clicked "WebStore.UI.net35" Project in the solution and chose "Build"
    Luckily ... it just built :)

    Copied the WebStore.UI file from "\WebStore.UI\bin" folder in the source to the website.

    This time setup ran fine :) But I got the following Error:
    mojoSetup has detected that the database user does not have permission to alter the database schema. You need to correct this or provide a connection string with sufficient permission.

    I deleted the "mojo.db.config" that came with the zip file.
    ran the following after cd "Data\sqlitedb"
    sqlite3.exe mojo.db.config

    .read initdb.config
    .exit

    Now setup ran fine and everything works :)

    Long live mojoPortal!

    Enjoy!

    Calling LoadLibraryEx on ISAPI filter "C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_filter.dll" failed

    After installing Visual Studio 2010 on my 64 bit windows 7 machine IIS failed open any webpages with the following error:

    "Calling LoadLibraryEx on ISAPI filter "C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_filter.dll" failed"

    The following resolved it:

    cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
    aspnet_regiis -r

    Yes ... I forced asp.net to run 32bit. I also tried:

    cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
    aspnet_regiis -r

    and it too worked. But I have a reason to run in 32Bit because I use SQLite :)

    Thursday, October 28, 2010

    Python Icons

    The official Icons used by applications in Python 2.5 are available at the following URL:
    http://www.doxdesk.com/software/py/pyicons.html

    Awesomeness in a box :)

    Monday, October 11, 2010

    Exam 70-536 Passed

    First of all you need is 700 from 1000 to pass. Did I mention i got 953. I am very happy.

    Time was 140 minutes. I was done in half an hour and did not review the answers since I either knew the answer or gave it time in the first go because I could see that time was not going to be an issue. Also first thing you do is select your language (I chose c#).

    How I prepared? Just read the official book (MCTS self paced training kit for 70-536 second edition) cover to cover. Highlighting everything I didn't know before as well as names of .Net types (classes, properties, methods etc) that I had to memorize by heart. Then went through the book again memorizing the highlights ... twice. Both times looking at them and writing them on a piece of paper. I took my annual leave for this. All in all it took one month.

    Of-course officially working on C# almost exclusively (other languages nowadays are python for short scripts and java for maintaining older codebase) helped me focus in putting in so much effort into memorizing the framework.

    Was it worth it? Yes. Here's what I feel it will do:

    • Prove I know the .Net framework so you don't need to test me for it. You can but it would be pointless. 
    • Plus it helps in programming if I know all the things I have available even if I never use them. 
    • Prove I know the basics of programming in general. Even if only syntactically. Not that anyone would question that anyways ;) 
    • Prove that I am serious about .Net :) 
    Here's what it cannot do (no certification can really):
    • Prove I am a good programmer. You will always need to test the guy you are hiring for that or just review his code :)
    Plus it looks good on the CV even if it works only subconsciously on the employer. 

    There were questions outside the book. That is were real programming experience helped e.g. knowing the basics of XML API and what an attribute or inner text means can help you narrow down the answer. Also I could guess that this is the interface with this signature function for one of the questions (although I see now that it was mentioned in the skills measured but the signature beyond the method name ToString was not present in the book). Also I just happened to read about the difference of Deflate and GZip thanks to Jeff Atwood once upon a time

    But in any case from the book alone 700 is most definitely possible. 

    Enjoy! 

    Monday, October 4, 2010

    Using WPF Themes with WPF 4 gives Error : "Ambiguous type reference"

    Using WPF Themes from http://wpfthemes.codeplex.com/ with WPF 4 and using the WPF Toolkit Feb 2010 which is latest at the moment gives the following Error:

    Ambiguous type reference. A type named 'VisualStateManager' occurs in at least two namespaces, 'System.Windows' and 'System.Windows'


    WPF Toolkit is required for themes since they took the effort to style the controls in WPF toolkit as well :)

    Solution:
    Simply direct the VSM tags to refer to the .NET4 VSM namespace. Open the theme file you want to use and do the following:

    • Add a new xmlns attribute to the root Resource Dictionary Tag: 

    xmlns:sw ="clr-namespace:System.Windows;assembly=PresentationFramework"

    • Search and replace all references to elements in vsm namespace with sw: prefix. 
    • Additionally if you want to completely remove dependency on WPF Toolkit you could simply delete the following tags:
      • xmlns:basic="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
      • xmlns:primitives="clr-namespace:Microsoft.Windows.Controls.Primitives;assembly=WPFToolkit" 
      • And remove any controls that are linked to it ... and redirect the ones available in WPF 4 to the sw namespace
    Enjoy!

    Thursday, September 23, 2010

    Metro UIs for WPF / Silverlight

    Just found an amazing looking gui framework for WPF:
    nRoute

    The WPF look and feel of the application sample is based of : http://www.nikosbaxevanis.com/bonus-bits/2010/12/building-a-metro-ui-with-wpf.html

    Update: the best way with WPF 4 and above to make a custom window chrome would be undoubtedly the WindowChrome class that comes with the Ribbon library / WPF Shell integration library (http://code.msdn.microsoft.com/WPFShell) : http://blogs.msdn.com/b/wpfsdk/archive/2010/08/25/experiments-with-windowchrome.aspx
    Expect an update on that in the future :)

    There is nothing much that can be said that isn't already present on their website. All I can do is make some application with it ... hmmmm.

    Enjoy!

    Wednesday, September 15, 2010

    Blue is THE most appealing color for mass consumption

    You have every right to disagree but statistics are against you:

    Apple: soooo many examples ... Mail icon ... Safari icon ... Ipod interface ... Safari progress bar
    Facebook. Its blue.
    Twitter. Again blue.
    Blogspot. The blogger backend interface and the blog title bar (where it says sign in) ... Guess what ... blue.
    My towel. Hey I think it counts :)

    I am glad i have always loved blue in my applications ... It is my favorite color you know ;)

    Friday, September 3, 2010

    A minor modification in the SQLite connection string. A major improvement in performance

    If you use EF (entity framework 1) with SQLite you might know that it does not have bulk import support (this is because EF doesn't provide any bulk import API. 

    So for quick code you end up with multiple import commands sent to the database in a loop. With synchronization enabled (sqlite flushes the data to the disk after every change) the performance is slow. With synchronization disabled it is BLAZING fast. Just be sure to flush the data at the end :) 

    Just add:
    synchronous=Off

    to your connection string. For a comparison of the perforamance change you can look at : http://www.sqlite.org/speed.html 
    SQLite 2.7.6:   13.061
    SQLite 2.7.6 (nosync):   0.223

    This is how much it feels in my code as well :) It now actually works faster than a portable untuned mysql (5) / postgresql (8.4) / firebird (2.2) 

    I keep loving this database more and more :)

    Found the .net settings here:

    Enjoy!

    Sunday, August 29, 2010

    Using codesmith (5.1) with postgresql for NHibernate

    You could say that this post is a modification of (http://www.codesmithtools.com/video/nhibernate.html) when you don't have working visual studio integration and/or you want to use codesmith with Postgresql+NHibernate
    This is how to use Codesmith professional version 5.1 without visual studio with Postgresql to generate nhibernate templates.


    • First download the Npgsql (version Npgsql2.0.2-bin-ms.net.zip). Extract and copy the "Npgsql.dll" and Mono.Security.dll" files to GAC (c:\windows\assembly). Note: This version of npgsql was determined from the dll not found error emitted when your test connection in Codesmith add data source dialog. 
    • Now open "CodeSmith Studio".
    • In the "Schema Explorer" docking window click "Manage Data Sources". Next click "Add". 
      • Name your datasource whatever you want. (hence referred to as "yourdatasource")
      • Select PostgreSQLSchemaProvider.
      • Put in the connection string.
    • Your database connection is setup.  
    • In the "template explorer" click on "create template folder shortcut" icon in the toolbar to create a shortcut to the folder you want to create the Codesmith project in. 
    • right click the newly created "template folder shortcut" and select "New->Codesmith Project".
    • Right click the newly create project and select "Add Output". Browsed and added the following template "C:\Users\Basiee\Documents\CodeSmith\Samples\v5.1\Templates\Frameworks\NHibernate\CSharp". Of course your username / version of codesmith / version of operating system come into play for this address. 
    • Select your "Source Database" to be "yourdatasource" whatever you called it. 
    • Modify your "assembly name" (required ... for your ease) as well as the namespaces (optional) to keep them consistent with the assembly name. 
    • Now right click the project (in Template Explorer) and select "Generate Outputs".
    Enjoy!



    Wednesday, August 25, 2010

    Best database modeling tool for PostgreSQL

    First off:

    • This tool is not free of cost (but not too expensive). No free tool came up the my requirements. Feel free to tell me if you know any. 
    • By database I mean PostgreSQL .... of course :) 
    • My requirements:
      • Should connect directly to the database. With ability to reverse engineer the design from the database as well as the ability to send the design to the database. 
      • Should be able to export the model to its own format and be able to generate a change script between two files generated from the same script. This will allow a database + file pair for each revision of the software where the table structure changes. 
      • Should provide options for setting up naming conventions. 
    I will not go into all the softwares I tried ... since to be honest I gave each software's trial version a limited run. But one came out on top as a CLEAR winner : 
    ModelRight Professional 3.5

    One note though. To get it to connect to PostgreSQL i needed to add the "bin" folder of my PostgreSQL installation in my windows "Path"
    Note: I didn't run the windows installer for postgreSQL ... i used the method here . The postgreSQL windows installer might do this but I haven't verified.
    ModelRight suggest that I could have also just copied "libpq.dll" to the installation folder of ModelRight (in my case C:\Program Files (x86)\ModelRight\ModelRight 3.5 Professional) but that did not work for me. 


    Thursday, August 12, 2010

    PostgreSQL Portable

    I just wanted a portable PostgreSQL (on windows) not for development but for distribution. This means that I only care about the data directory being portable.

    Making a portable postgreSQL
    To make the latest version portably. Heres what I had to do:

    • Just downloaded the latest stable postgreSQL windows zip file (http://www.enterprisedb.com/postgresql-904-binaries-win32?ls=Crossover&type=Crossover)
    • Extracted to a folder.
    • Made a folder called "data" inside the "pgsql" folder and made sure current logged in user (administrator btw) had full rights to the folder.
    • CDed to the pgsql\bin folder
    • ran the command:
      initdb.exe -D "../data" -U postgres -W
    • Type in the password you want for postgres superuser (lets say you put in password) and reenter to verify as prompted. 
    • In the end of the above command I could read the following:
      Success. You can now start the database server using:
          "postgres" -D "../data"
      or
          "pg_ctl" -D "../data" -l logfile start
    • All done. Now you can start the database using the following command (be sure to leave the command prompt open after this command because as soon as you close it the server will terminate):
      pg_ctl -D "../data" start
    • You can shut down the database using the following command:
      pg_ctl -D "../data" stop
    You can now connect to the database using pgadmn3 in the bin folder. If you do not need PostGIS support you are all set :) In case you do ... continue reading :)

    Adding PostGIS support to the portable postgresql
    I downloaded the latest version of postgis from here : PostGIS 1.5.2 release for PostgreSQL 9.0 for 32-bit Windows mentioned on this page.


    • I extracted it so that my directory structure was as follows:


    • Copy all the files from postgis to pgsql 
    • Edit "makepostgisdb.bat"  as follows (the sections in bold italics are the ones I modified / added):
    set PGPORT=5432
    set PGHOST=localhost
    set PGUSER=postgres
    set PGPASSWORD=password
    set THEDB=optimate
    set PGBIN=.\bin\
    "./bin/pg_ctl" -D "./data" stop
    "./bin/pg_ctl" -D "./data" start
    "%PGBIN%\psql"  -c "CREATE DATABASE %THEDB%"
    "%PGBIN%\psql"  -d "%THEDB%" -c "CREATE LANGUAGE plpgsql"
    "%PGBIN%\psql"  -d "%THEDB%" -f "share\contrib\postgis-1.5\postgis.sql"
    "%PGBIN%\psql"  -d "%THEDB%" -f "share\contrib\postgis-1.5\spatial_ref_sys.sql"
    "%PGBIN%\psql"  -d "%THEDB%" -f "share\contrib\postgis-1.5\postgis_comments.sql"
    "./bin/pg_ctl" -D "./data" stop

    REM Uncomment the below line if this is a template database
    REM "%PGBIN%\psql" -d "%THEDB%" -c "UPDATE pg_database SET datistemplate = true WHERE datname = '%THEDB%';GRANT ALL ON geometry_columns TO PUBLIC; GRANT ALL ON spatial_ref_sys TO PUBLIC"


    pause


    • Execute makepostgisdb.bat by double clicking it. Eventually you should get a screen like this:
    • At this stage you have a new PostGIS enabled database (optimate) available to you!
    • Finally copy the plugins.ini file from the pgsql folder to pgsql\pgAdmin III folder overriting the file already there. Now you have configured a cool Shp2pgsql-gui tool as a plugin for pgAdmin3 :)  You can verify it by running pgadmin3. You will see it in plugins as shown below:


    Some useful bat files
    Additionally here are some command files I use for postgreSQL (place in the main pgsql folder):
    pgadmin.bat
    "./bin/pgAdmin3.exe"


    startserver.bat
    "./bin/pg_ctl" -D "./data" start


    stopserver.bat
    "./bin/pg_ctl" -D "./data" stop
    pause



    Enjoy!
    Updated on 24th June 2011 adding documentation for postgis + some useful bat files. 

    Wednesday, July 28, 2010

    Sunday, June 27, 2010

    WPF vs. Silverlight Differences

    I just Google random things that interest me sometimes. Today it was "Awesome WPF". This lead me to this post:
    http://blogs.msdn.com/b/jimoneil/archive/2009/06/12/awesome-wpf-silverlight-guidance.aspx

    Which lead me to a detailed comparison sheet of WPF vs. Silverlight:
    http://wpfslguidance.codeplex.com/


    Enjoy!

    Friday, June 18, 2010

    The truth behind Hungarian Notation

    I am a real admirer of Charles Petzold's programming windows (and in fact all of his books). But I never knew :

    http://www.joelonsoftware.com/articles/Wrong.html

    Good to know the truth.

    Plus really useful information about naming conventions.

    Enjoy!

    Friday, June 11, 2010

    .NET Trick Question

    What do you think will be the output of the following code:

        class Program
        {
            public class StringClass
            {
                public string TheString { get; set; }
            }
     
            static void Main(string[] args)
            {
                List<StringClass> stringClassList = new List<StringClass>(){
                    new StringClass{TheString="asdf"}
                };
     
                IEnumerable<StringClass> stringClassEnumerable = stringClassList;
     
                IEnumerable<StringClass> AllItems = stringClassEnumerable.Where(item => (true));
     
                stringClassList.Add(new StringClass { TheString = "fdsa" });
     
     
                foreach (StringClass item in AllItems)
                {
                    Console.WriteLine(item.TheString);
                }
     
                Console.ReadKey();
     
            }
        }


    If you think the output is :
    asdf

    You are wrong.
    It is :
    asdf
    fdsa

    This is because the result from the where extension methods is deferred till you try to access the result (in this case the foreach loop).

    Enjoy!

    Copy Source as html for Visual Studio 2010

    Any .net programming blogger should definitely check it out:

    http://sandrinodimattia.net/blog/post/Copy-Source-as-HTML-in-Visual-Studio-2010.aspx

    Update: As pointed out on twitter : https://twitter.com/jameskovacs/status/29095602121 removing this plugin really sped up my VS2010 experience. So no Copy as html for me :)

    Enjoy!

    Thursday, June 10, 2010

    Backing up SQL Server databases using code

    A new article on code project:
    http://www.codeproject.com/KB/database/sqlbackupprogressasync.aspx

    Check it out!

    Enjoy!

    The need for events and why delegates should not (or should be) used in a chained subscription

    In case you are familiar with the syntax surrounding delegates and events in c# you might have wondered why you need to use the event keyword. The reason is encapsulation.

    In below discussion delegates are the objects that were defined without the event keyword.

    Subscriber encapsulation
    Delegates allow syntax of the form :
    someDelgate = someMethod;
    This will allow a rouge subscriber to remove all previous subscribers.
    Events allow assignment only in the encapsulating class.

    Publisher encapsulation
    Delegates allow syntax of the form :
    someObject.SomeDelegate();

    That is anyone can invoke public delegate members. Events only allow the encapsulating class to invoke the event.

    Additionally
    You can initialize events so that you do not need to do null checking before invocation using the "= delegate {}" syntax.

    PS: this was written on my iPad. Definitely pulling out my laptop in future.
    It's not bad...just weird.

    Wednesday, June 9, 2010

    Best software for PDF reading on the IPAD

    I got an Ipad. I bought it for just one reason ... reading PDFs. My job is such that I need to keep myself updated with the latest and greatest technologies in .NET. So the first thing I did was get PDF readers:

    Here's what I reviewed and why I left them:

    • Air Sharing HD: Kept crashing 
    • iGoodReader: You cannot view two pages at a time. For pdf viewing it is one page to second page only. And when code listings are between pages this becomes "Annoying"
    • iTech PDF Reader Pro: Laggy between page changes. Also couldn't browse pdf bookmarks. Above all a bad anti aliasing.

    Here what I stuck with: 
    iAnnotate PDF

    I love it with ALL MY HEART! With Good Reader and PDF Reader Pro i knew these shortcommings the moment I installed them (and concerned about the iPad purchase). This software however blew me away. It is ULTRA responsive. Completely worth it!


    Advantages:

    • One huge advantage (which I didn't even consider possible in iPAD) it has is the ability to highlight (and generally annotate) PDFs. I mean for real...into the pdf file so that it is maintained even when you view it with adobe reader on your PC.
    • You can open multiple pdf documents simultaneously ... which is simply amazing. And therefore browse them side by side
    • Search all the PDF (text) in the library!
    • Once you exit the application and open it up again ... since it is tab based .. it will open all the books that were previously open in the tabs ... and on the last viewed pages. A great time saver! Just exit -> Ipod -> back ... makes reading on this the best experience ever I have had in a long long time (much much better than adobe reader on the PC)


    Note:
    Also once you import the file it does some preprocessing (only once per file) ... so you need some patience ... but after that boy does it work. You can fly between HEAVY pdf pages with ease.

    Thanks guys (if you ever read this :))

    Enjoy!

    Sunday, June 6, 2010

    Sybase ASE 15 .NET Drivers possible issues

    These are just good tips to keep in mind anyways when using Direct ADO.NET interfaces. But here goes:

    • Always surround your Connection with Using. (this calls dispose on finishing usage)
    • Note in case you call connect be sure to balance it with a disconnect as well 
    • Set the connection timeout before you connect
    • Set the command timeout on your command
    • In case you do heavy data import. Try to set the local variables above the try block to null in the finally.
    Enjoy!

    Wednesday, June 2, 2010

    WPF / Silverlight Layout Panel specifically for data entry forms

    A great utility:

    They also present the case why using the StackPanel and the Grid is insufficient for the requirement of a user form.

    Enjoy!

    Tuesday, June 1, 2010

    On WindowStyle set to None the maximized window hides the taskbar

    Was going through the sample code in "WPF Control Development Unleashed" i saw that the custom chrome window would hide the taskbar on maximize. Lucky someone already had it fixed:
    http://blogs.msdn.com/b/llobo/archive/2006/08/01/maximizing-window-_2800_with-windowstyle_3d00_none_2900_-considering-taskbar.aspx

    Actually I got to it from this article:
    http://blogs.msdn.com/b/wpfsdk/archive/2008/09/08/custom-window-chrome-in-wpf.aspx
    It contains all you need to know about customizing the title bar in wpf application

    Enjoy!

    Monday, May 31, 2010

    Requirements for overriding GetHashCode

    The following are the requirements to remember when  you override GetHashCode System.Object function: 
    • Two equal objects must have equal hash codes
    • The Hash code of a particular object must never change (you might want to cache the result. In NHibernate's case you should use the primary keys to generate it since they do not change)
    • It should not throw exceptions 

    That's it. Plain and simple.

    Enjoy!

    Creating a Visual Studio 2010 code template

    Great Post:
    http://timheuer.com/blog/archive/2010/05/03/create-vsix-files-with-visual-studio-template-deployment.aspx

    Enjoy!

    "Terminal Server Has Exceeded the Maximum Number of Allowed Connections" Windows Server Error

    You can bypass this by connecting to the terminal server using the following on the command line:
    mstsc.exe /v:localhost:7000 /admin

    Note: in my case I had port forwarded the local 7000 to 3389 of the remote computer.

    Got this of here:
    http://www.howtogeek.com/howto/windows/command-line-hack-for-terminal-server-has-exceeded-the-maximum-number-of-allowed-connections/

    you can also use the command line:
    query session /server:servername
    and then
    reset session [ID] /server:servername
    Enjoy!

    Saturday, May 29, 2010

    Friday, May 28, 2010

    Dynamic programming with C#

    A good article + code that allows you to use c# as a completely dynamic language:

    http://www.codeproject.com/KB/cs/deep_object.aspx

    Thought i'd bookmark it. I can come in handy someday :)

    Enjoy!

    Wednesday, May 26, 2010

    C# Decimal type dissected

    I was going through C# 4 Essentials. The Decimal type description is sufficient and it is cool to imagine it as +/- N * 10k. But I was not satisfied. The above statement and below url have put me much at ease. Must have been a difficult decision to keep a 128 bit location and leave bits blank after using 102 bits:
    http://www.yoda.arachsys.com/csharp/decimal.html

    Remember machines are binary and 128 is the closest upper 2^x (for a whole number x) above 102.

    Update: Even more amazing explanation:
    http://gregs-blog.com/2007/12/10/dot-net-decimal-type-vs-float-type/
    If you are even more interested in the mathematics (non .net specific) check out the below (it will help you understand greg's post as well):
    http://sandbox.mc.edu/~bennet/cs110/flt/dtof.html
    Note: there is something to be found in each of these absent in the rest


    Enjoy!

    Tuesday, May 25, 2010

    Best feature of Visual Studio 2010

    We all have our favorite features in Visual Studio 2010. Maybe you love the new WPF design surface. For me it is hands down "Intellitrace". This feature is so unique that I am completely dazzled by it. Here are a few tutorials :
    Beginner:
    http://blogs.msdn.com/b/habibh/archive/2009/10/20/getting-started-with-visual-studio-2010-intellitrace-hello-intellitrace.aspx
    Settings:
    http://www.dotnetcurry.com/ShowArticle.aspx?ID=483
    Intellitrace Video (at the second half of this presentation). Usage with Team Foundation Server. With the Amazing Testing Manager:
    http://channel9.msdn.com/shows/VS2010Launch/Doug-Seven-Improving-Developer-Tester-Collaboration-with-Microsoft-Visual-Studio-2010/

    Thursday, May 20, 2010

    Calling Dynamic languages from .NET 4.0

    This is a cool new feature in .NET 4.0 courtesy of the Dynamic Language Runtime becoming a part of .NET 4.0. As you may know there is a new keyword "dynamic" in C# with .NET 4.0. Here's how you can use it to call python scripts from C#:

    Title:Walkthrough: Creating and Using Dynamic Objects
    http://msdn.microsoft.com/en-us/library/ee461504(VS.100).aspx


    Awesome (cause I love python)!
    PS: Any C#/Python programmer should definitely try out http://ironpython.net/
    Enjoy!

    Wednesday, May 19, 2010

    Why use Team foundation server for a single developer

    The main requirements of application lifecycle management:
    • Source control. History / branching primarily
    • Clear tracking of issues and work items.
    Plus best Source control integration with Visual Studio

    Also its super easy to setup TFS2010 basic with Visual Studio 2010.
    And it does not need any further installation on your visual studio. I am very careful of what I put in visual studio especially regarding performance and I protect it with a vengeance (as many guys who have done java development in the past are)

    Update: During configuration of TFS2010 i ran into a blue screen (windows 7). So to complete the configuration i had to delete the items it created:

    • IIS Website for Team Foundation Server
    • net stop
    • sc delete the
    • Close the configuration window as well as "Team Foundation Administration console" since at least one of them uses the TFS_configuration Database. 
    • sqlcmd -S "Basiee-PC\SqlExpress" -q "drop database Tfs_Configuration"
    Enjoy!

    Update: I am not going to lie. I did not find much usefulness in it. If you don't mind running SQL Server (taking 400 mb of your ram) in the background for a non database project just for the source control that it may be for you. It is not for me. 

    Monday, May 17, 2010

    NHibernate 2.1 with SQLite

    There is an error in the default configuration file that comes with NHibernate. It recommends the Driver Class :
    "NHibernate.Driver.SQLiteDriver" in the hibernate.cfg.xml file. This referes to the SQLite Driver found at:
    http://sourceforge.net/projects/adodotnetsqlite/
    Wrongly (I believe) mentioned at : http://community.jboss.org/wiki/DatabasessupportedbyNHibernate
    This version is no longer valid. The new (and awesome) version is http://sqlite.phxsoftware.com/
    For this you will need to specify in the configuration "NHibernate.Driver.SQLite20Driver"

    PS: cool link: http://devlicio.us/blogs/krzysztof_kozmic/archive/2009/08/14/testing-with-nhibernate-and-sqlite.aspx

    Enjoy!

    Friday, May 14, 2010

    Setting up a portable Firebird Full with VS 2010

     Setting up a Portable Firebird
    • Downloaded the ziped version of Firebird: 
    • Firebird-2.1.3.18185-0_Win32.zip
    • Extact to a folder
    • I prefer classic architecture running as an application (you do not need FB Guard also The path to file with or without a missing / in the beginning will not cause DB corruption).
    • Start the server with the bat file containing:
      "./FIREBIRD/bin/fb_inet_server.exe" -a -p 3050
    • using this you can change the port to something else. The -p switch is optional. Even allocate the port dynamically from your application. Also you can use the -n switch to start it silently:
      "./FIREBIRD/bin/fb_inet_server.exe" -a -n -p 3050
    • Stopping the portable classic server is easy. Just kill the process fb_inet_server. Of course this is assuming your application is done with everything (no pending transactions). There is no point in leaving the server running.
    Changing the SYSDBA Password (default:masterkey) Actually it is masterke (since it is limited to 8 characters). But both work :)
    • FIREBIRD\bin>gsec  -user sysdba -password masterkey
    • GSEC>modify sysdba -pw yourpass
    • GSEC>quit
    yourpass will be the new password

    Connect to the database (connection String):
    • syntax
      IPAddress_or_ServerName/Port:Drive:\CompletePathToYourDatabasefile.fdb
    • e.g
      150.236.161.183/3051:D:\database.fdb
    • for softwares (e.g. FB development studio) that do not give you the option of port separately you need to specify the server as "IP/port". They use fbclient.dll 
    For setting up Visual Studio 2010 with ADO.NET Entity Framework Designer just follow the procedure in the below post:

    http://basaratali.blogspot.com/2010/02/setting-up-firebird-development-with-vs.html

      ADDITIONAL NOTES:

      To run as SuperServer

      • Start the server with the bat file containing:
        "./FIREBIRD/bin/fbguard.exe" -a
      • Firebird should now be running fine (with an FB guard icon in the taskbar notification area) Note: there should not be any whitespace after -a switch other than newline. Otherwise FBGuard thinks you are trying to provid additional arguments and does not start.
      • You might want to put a shortcut to this script in the startup. FB Guard ensures DB restart in case it crashes.
      • Alternatively you can use fbserver.exe -a -n -p 3051
      • This way you can even overwrite the default port on the command line (-p switch). But FB Guard is recommended for SuperServer.

      Changing the default Port (3050) via the configuration file:
      • You might want to change it so that your portable version does not conflict with firebird installed by someone else.
      • open firebird.conf (in the main folder)
      • Uncomment and change the following line:
        RemoteServicePort = 3051
      • Restart Firebird
      Choice of Firebird Architectures:
      According to : http://www.slideshare.net/mindthebird/why-firebird-fact-for-decision-makers?from=ss_embed Classic can handle larger data and more users. Enough said :). Also I recommend the other presentations from : http://mindthebird.com/downloadmtb.html 

      Using ISQL to create a new database (Recommended)
      • isql is found in your firebird bin folder. Just double click it
      • Type in the following:
        CREATE DATABASE 'D:\yourdb.fdb' user 'SYSDBA' password 'masterkey';
      • Of course use your own SYSDBA password and the location of where you want the database to be.
       
      Using Firebird Maestro to create a new database
      I used Firebird Maestro to create the database. You need to use :
      • Create New Database
      • Protocol:Embedded Server
      • Database:Complete path to where you want the fdb file
      I feel it is the best manager directed specifically for firebird.

      Thursday, May 13, 2010

      PostgreSQL and .NET (Entity Framework and all)

      Npgsql is the way to go:
      http://npgsql.com/index.php/2008/11/npgsql-version-2-full-support-for-net-35-and-entity-frameworks/

      PS: another great find (I think) :
      http://npgsql.com/index.php/2009/08/how-to-set-up-entity-framework-npgsql-part-1/

      Especially like that you can use EdmGen2 to update your edmx files from the command line (like sqlmetal but for ADO.NET entity framework)



      Enjoy!

      Wednesday, May 12, 2010

      Reading xls and xlsx files from .NET

      Free library to read XLS and XLSX files from .net: 

      http://sourceforge.net/projects/koogra/


      I thought it deserved a mention :). Written in C# and available with MIT license (aka free for commercial use).

      On the commercial front I recommend (you also get to read CSV and fixed column width files reliably from same API) :
      http://www.csvreader.com/
      They have the full version available for free testing so:
      I tested there performance for XLS and XLSX.
      For XLS it can load the sample customers sheet with 65536 rows (max allowed :)) in under 1 second
      For XLSX it can load 80 thousand in reasonable time  (just wanted to check if it could handle the new row limit extension :) Also, Excel 2007 is not that happy opening this file either ).


      There is also gembox spreadsheet. But since they don't have a full featured test version I cannot comment on its performance / my opinion.

      Enjoy!

      Limitations for databases that will affect your software

      There are a large number of things to look in a database upon selection. Here are some that have caused me problems:

      • Column name size. e.g  firebird it is 31 
      • Alter table e.g. SQLite does not allow drop column
      • Authentication e.g. ScimoreDB 3.0 does not have db password protection 
      • Max DB Size : e.g. SQLite can only handle databases of 2TB 
      • Embeddability: e.g. MSSqlServer cannot be packaged as a part of your application (SQL Compact can be ... but it has its own HUGE limitations) . MySQL is a 60MB+ database. 
      • Licence : MySQL is GPL and not free for commercial use. Per installation cost as of 5/12/2010 is about $500
      • Reclaim Disk Space: Deleting data from a firebird does not shirk the database size. It is stored in the firebird free space and reused but cannot be reclaimed without backup/restore. 
      • Performance : test it out ... you never know ... depends on the database as much as on your configuration / your application code / the application interface. 
      Note: all databases mentioned here are great for a there own things e.g: Scimore has the best distributed architecture I have seen , SQLite is the best "Embedded only" database there is with an awesome .NET provider, Firebird has great entity framework support and so on.

      Enjoy! 

      Tuesday, May 11, 2010

      Oracle's select from dual for Firebird

      This will definitely come in handy:
      For firebird there is a system defined table that contains one and only one row RDB$DATABASE.

      so you can get the current time e.g. from the following query:
      select current_time from RDB$DATABASE;

      Enjoy!

      Sunday, May 9, 2010

      Free for commercial use + high performance + feature rich + client server + embeddable databases

      Here's why what is tested and rejected:

      SQLite: Client+server is not good (SQListening has a few limitations so don't go there! e.g. multiple columns with same name cannot be returned)  + writes lock the whole file (under milliseconds and reading is still allowed ... but you should be aware ... ) . And due to inherant complications of reliability of file sharing systems it cannot work over LAN (biggest bummer). Drop column is not supported (and that is something that my database will do quite commonly ... counter activation/deactivation etc. )

      MySQL: Not free for commercial use (GPL). 500$ . Not to mention that oracle now owns it (and I am still convinced it will result in a conflict of interest). PS: it is highly feature limited.
      http://www.borland.com/resources/en/pdf/white_papers/ib_vs_MySQL.pdf  Note : Interbase(IB) was the original source of Firebird in case you did not know.

      ScimoreDB: Great but not feature rich (e.g. no upsert support , limited data types ... improved in version 3.0 (RC version) and password protection to be added by 3.5 ... but not yet )

      So it boils down to:
      Note both are GREAT databases. This is just my opinion as I have to make a choice of one :) .








      Firebird:
      + Easier to Embed
      + Lesser strict system requirements
      + Easier to master :) .. with the right book ... "The Firebird Book"
      + Smaller installation (under 25 MB if you go crazy and include everything redundant as well)
      + Mature ADO.net Entity framework Visual studio designer.
      -ve Does not free disk space on deleting old data (put does recover it for usage by new data). You need to backup and restore. Will be fixed in firebird 2.5 though :)

      PostgreSQL:
      + .net 4.0 compiled driver already available ( may/9/2010 ). .net driver is called npgsql
      + more features (but I don't need them) e.g. PL/Python!  + partitioning + HUGE tables + partitions
      -ve Can only work on NTFS. Not neccessarily a bad thing at all. They dont trust FAT ... and I don't blame them :). I wouldn't put firebird on it either (cause it will be limited to 4GB and once that overflows your database has a high likelihood of corruption)
      -ve 30MB+ install. Not bad at all but still.


      You should try out both. Tell me what you chose. I chose Firebird. It has greater .net support ... and .net guys seem to like it more .. probably because of its easier portability (one file db .. no installation required for running firebird on windows)

      BTW for PostgreSQL I am reading PostgreSQL 8 for windows.
      For Firebird I just read the manual and then reading  "The Firebird Book".

      Enjoy!

      Thursday, May 6, 2010

      SQLite for Visual Studio 2010

      I just downloaded SQLite version "SQLite-1.0.66.0-setup". The EF designer works as expected on Visual Studio 2010. Well Done TEAM! you guys Rule!

      Thanks and I will try to give as much back as I can. Amazing product. Best there is for a startup by FAR!

      Enjoy!

      Update June 19 2011 : As mentioned in the comment below SQLite for .NET now has a home sqlite.org !  : http://system.data.sqlite.org/index.html/doc/trunk/www/index.wiki

      You can download the latest version from here : http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki

      Update June 28 2011 : As mentioned by John below the Designer support with the latest version is not available as of yet. You are free to use the old version of system.data.sqlite that comes with designer support for VS2010.

      Wednesday, May 5, 2010

      Profiling applications with Visual Studio 2010

      Previously I had Visual Studio 2008 Professional. I read about profiling applications in .NET and discovered that it was not offered with Visual Studio 2008.

      Now I have access to Visual Studio 2010 Ultimate. There are many tutorials for this out there. But only one I could find that showed the basic walk though:
      http://msdn.microsoft.com/en-us/library/ms182398.aspx

      After this if you have used profiling in java (damn easy and free) you should not miss anything.

      Monday, May 3, 2010

      Upserts in various database systems

      Upsert is a common database term that is used to signify the operation "Update the row... if an entity with the same key does not exist then insert it"

      Here's how I do it in various databases:

      MYSQL

      REPLACE / IGNORE Keywords
      It follows the same syntax as insert except that it replaces the old row if the same entity exists:
      REPLACE INTO tablename VALUES ( 'whatever' )
      In case you want to ignore the insert in case the keys exists you could do:
      INSERT IGNORE INTO tablename VALUES ( 'whatever' )

      SQLite
      Did I tell you I love SQLite? Anyways:
      ON CONFLICT clause

      Microsoft SQL Server
      Didn't encounter the REPLACE but used ignore quite commonly. You can acutally do it on a table level

      CREATE TABLE TEST(
          [ID] [int] NOT NULL,
           CONSTRAINT [PK_TEST] PRIMARY KEY CLUSTERED
          (
              [ID] ASC   
          )WITH (IGNORE_DUP_KEY = ON) ON [PRIMARY]

      ) ON [PRIMARY]







      Enjoy!

      Friday, April 30, 2010

      Not relying on Visual Studio dbml creator and using SQLMetal

      For VS 2008: I like to keep all the data structure in the database (foreign key relationships etc.) and do not have much use of defining them manually in the dbml generated by Visual Studio. So I generally use a bat file like to following to generate the dbml file from the database (sql server compact example):

      "C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\SqlMetal.exe" ENDData.sdf /dbml:ENDData.dbml /serialization:unidirectional

      This is for linq to SQL.

      Now I use ADO.net entity framework so that I can use other non ms (free ;) ) databases. That has the update schema from database option which is cool.

      Enjoy!

      Thursday, April 22, 2010

      What all to request when the server is bought by the client (customer)

      Another project successfully completed! Hurray!

      But it took longer than expected. I had to reconfigure it Five Times! Primarily due to power and firewall issues.

      So here is a short list that I keep handy henceforth:
      • Hardware : Processor
      • Hardware : RAM
      • Hardware : Harddisk (+ backup space)
      • Software : Operating System
      • Software : Permanent administrator access on the machine
      • Location : Power Stays on all the time!
      • Location : All nodes you need access to should be accessible from the location. 
      Also I like to do the following to the windows server:
      • Enable Remote Desktop
      • Disable "Error Reporting" from your computer's advanced properties (this can cause some console application to be stuck at a user prompt). In windows vista it is available under : gpedit.msc -> computer configuration -> Administrative Templates -> Windows Components -> Windows Error Reporting -> Disable Windows Error Reporting -> Enabled.
      • Disable the shutdown event tracker. This will prevent auto logon in case of power failures. gpedit.msc->computer management -> Computer Configuration -> Administrative Templates -> System -> Display Shutdown Even Tracker -> Disabled -> OK (http://support.microsoft.com/kb/293814)

      I will update this list as I go on in life :)

      Enjoy!
      PS: VS2010 and Silverlight 4 is here ... can't wait to go back and take it for a spin!
      UPDATE: love VS2010 :)

      .NET Embedded database

      SQLLite is awesome. And by far the one I trust most for stability.

      However it cannot function over windows shares. This means that there really isn't much of a distributed system available.

      So I was reviewing the "FREE" options. This came up:
      http://en.wikipedia.org/wiki/Embedded_database

      Will review the free ones with good .NET support.
      These in particular:
      ScimoreDB
      EffiProz

      Scrimore is highly respected (i knew that before).
      But EffiProz is improving (previously i remember it's codeplex page http://effiproz.codeplex.com/ now its http://www.effiproz.com/Downloads.aspx . Doesn't mention beta on the new page)

      Its is going to be about performance and how easy it is to change from embedded to client / server.

      Monday, April 19, 2010

      WPF and WCF RIA Services

      RIA services is not just for silverlight. Someone asked me this after watching the Siliverlight 4 keynote.

      Below is a WPF sample application:
      http://code.msdn.microsoft.com/RiaServices/Release/ProjectReleases.aspx?ReleaseId=3587
      Title: 'Add Service Reference' to a Domain Service

      Update : 20th September 2011 : The wpf sample link no longer works and I cannot find the updated link. Check out http://blogs.msdn.com/b/brada/archive/2009/11/22/ria-services-a-domainservice-is-a-wcf-service-add-service-reference.aspx for a sample of winforms. Effectively the same thing :)

      Enjoy!

      Sunday, April 18, 2010

      ASP.net Embedded web servers

      Free:
      http://code.google.com/p/aspnetserve/
      http://www.asp.net/downloads/archived-v1.1/cassini/

      Not free:
      http://www.asp.net/downloads/archived-v1.1/cassini/

      You can host wcf (giving built in librarires in .NET) but silverlight + wcf  is what I need. Haven't tested any for this ... yet!

      Enjoy!

      Wednesday, April 14, 2010

      My favorite feature of WPF 4 (yet)

      I simply love that they added cached composition!
      http://weblogs.asp.net/scottgu/archive/2009/10/26/wpf-4-vs-2010-and-net-4-0-series.aspx

      The sole purpose of WPF : GUI
      And this alone will make my GUI's SO much faster.
      I knew something this cool was going to happen ... That's why I moved to WPF in the first place.
      Thanks Microsoft!

      Friday, April 9, 2010

      Using WCF service with Windows XP SP2 and Windows Server 2003

      All previous installations of wcf I had done to date were on windows 7 and windows vista. Had to do one on windows server 2003. Read http://msdn.microsoft.com/en-us/library/aa751792.aspx . Here's how I did it:

      Note: Step 3 is only required since I installed IIS (from manager server -> add a new role) after installing .net 3.5 sp1

      open visual studio cmd (required for step 3)


      1. cd "c:\windows\Microsoft.net\framework\v3.0\Windows Communication Foundation"
      2. ServiceModelReg.exe /a /x
      3. aspnet_regiis -ir

      Enjoy!

      Thursday, March 18, 2010

      Great C# targeted tutorials

      This post is a place holder for more tutorials as I read them. Most of these search results return many versions and I will link to the one I found most complete.

      Singeton Pattern : http://www.yoda.arachsys.com/csharp/singleton.html
      WPF Window in a new thread : http://www.c-sharpcorner.com/UploadFile/suchit_84/MULTITHREADEDWPFWINDOW05232009013940AM/MULTITHREADEDWPFWINDOW.aspx

      Saturday, March 6, 2010

      Expression Blend 3 Active Document View Stuck at XAML

      Expression Blend 3 will not show the "Design View" and the "Split View" for xaml documents contained in project types other than "Windows Application" (Visual Studio -> Properties -> Application -> Output Type)

      What I like to do is set the application type to console application and write some debug output to the console for testing. This made Expression Blend 3 Design View stop working so I figured it out from there :)

      Enjoy!
      PS: I love SQLite! Awesome Awesome c# project : http://sqlite.phxsoftware.com/