What Does Value of core.autocrlf Git Setting Mean?

I have been confused about the core.autocrlf setting in the past and I found out pretty clear explanation on Git for windows installer so I thought I’d share it here so others can benefit from it.


On checkout, git will convert line endings to window style i.e. CRLF and on commit, it will convert to unix line endings i.e. LF


On checkout, git will not do any conversion and preserve line ending but on commit, it will convert to unix line ending i.e. LF


On checkout, git will not do any conversion and preserve line ending also
on commit, it will not do any conversion and preserve line endings.

Delete all tweets from Twitter

Just as we found a way to delete all posts from Facebook, we can apply the same technique to Twitter. Follow the steps below to wipe clean all your old tweets on Twitter.

  1. Log in to Twitter using Chrome browser
  2. Go to your timeline
  3. Scroll all the way down to your first tweet in order to load all the tweets in the UI.
  4. Open developer console (F12)
  5. Paste the following javascript snippet in the ‘Console’ tab
function dT(){var e=document.getElementsByClassName("js-actionDelete");e&&e.length>0&&(e[0].click(),setTimeout(function(){var e=document.querySelector("div#delete-tweet-dialog button.delete-action");e&&e.click()},1e3))}var deletor=setInterval(dT,1e4);

It will now delete your old tweets every 10 seconds for as long as the browser window is open. Enjoy!

Delete all posts from Facebook

I have a habit of cleaning up my social media profile every now and then and starting over fresh. However manually deleting posts can be a pain, specially if you’re doing it after a long time.

I could technically use Facebook SDK and write a program to do this for me however it seems that Facebook APIs only allow deleting those posts that are made from the same app that is deleting the posts. However I can go to my activity page on Facebook and delete posts one by one manually.

So I decided I’ll just automate this using javascript snippet. Follow the steps below to wipe clean all your old posts (include pics) on Facebook.

  1. Log in to Facebook using Chrome browser
  2. Go to your activity log
  3. Scroll all the way down to your first post in order to load all the posts in the UI.
  4. Open developer console (F12)
  5. Paste the following javascript snippet in the ‘Console’ tab
function dP(){var e=document.querySelector(".audienceSelectorNoTruncate ~ div.uiPopover a");e&&e.click();var t=document.querySelectorAll("a[ajaxify*=delete]");t.length>0&&t[t.length-1].click(),setTimeout(function(){var e=document.querySelector("div[role=dialog] form[rel=async] button[type=submit]");e&&e.click()},1e3)}var deletor=setInterval(dP,1e4);

It will now delete your old post every 10 seconds for as long as the browser window is open. Enjoy!

Also check out Delete all tweets from Twitter

pyMVC A Python Flask MVC Web Application Framework

At Hyves, we wanted to re-write a legacy web application in python Flask. I was in charge of setting up the boiler plate code that would be necessary to get a skeleton app, up and running.

For writing large application it is helpful to separate the concerns in different components and MVC pattern serves that purpose quite well. However Flask is a micro framework and doesn’t give you patterns or APIs to do MVC like application. You have to write all the code to make routing with controllers and actions work.

So I chose to write a small MVC application on top of flask that can be used as a starting point for writing controllers, views, etc while leveraging the power of flask and its plugins. A design decision I made was to make the framework object oriented and avoid any top level (free flowing) functions and global state. The code is now available on github as pyMVC.

If you know python and object oriented programming and you’ve worked in any MVC framework before then you’ll be able to find similar patterns in this skeleton. Feel free to fork it, make pull requests and leave comments and suggestions.

Squiggle 3.1 Final Released

Squiggle 3.1 has just been released. This is mostly a maintenance release and has only minor bug fixes. No new features.
Since it is compatible with 3.0 it is perfectly fine for some people in the network to be on 3.0 and others to be on 3.1.
So a slow and gradual upgrade should work.

In next release I’ll try to implement some of the features from Issue Tracker
You can get the latest release from Download page

What is wrong with Static Classes?

There are many concepts in computer programming which are commonly recommended against but rarely does anyone explain you why things like goto, singleton, static classes, etc can cause problems if not used with care. Today we’re going to see:

  • What kind of problem can a static class introduce
  • When it makes sense to create a static class
  • How to refactor the code which was using a static class

So to cover all of the above points let us take the example of our imaginary programmer friend ‘Tim’.

Tim was asked to write a product order placement component. One of the features of that component was that it could send email confirmation of the order to the user so he wrote something like the following:

    class OrderSystem
        public void AddOrder(User user, Product product)
            // Persist the order in DB

            Email.Send(user.Email, "Order confirmation", "Your order has been placed");

As you can see he created a static class Email with a Send method that takes bunch of arguments and sends the email. Lets see what was he thinking when he wrote this.

  • This is the simplest way to do it. Very clean one line code to send emails.
  • I don’t need ‘instances’ of the mail class. I just want to send email. Why create instance?
  • If there isn’t going to be any instance then lets make it a static class.

Later his supervisor asked him to write a unit test for this.

  • When he began writing a unit test he couldn’t verify that email was sent in a easy and straightforward way.
            void AddOrderTest()
                var orderSystem = new OrderSystem();
                var user = new User(1, "john", "john@example.com");
                var product = new Product(101, "pepsi");
                orderSystem.AddOrder(user, product);
                var order = orderSystem.GetOrder(user, product);
                Assert.... // What do I write here to check if email is sent? Should I log into inbox and pull his emails?
  • He went ahead and actually wrote code to login to mailbox of user and see if the mail has arrived but then he realized he is not only testing his OrderSystem but also the mail delivery system. If the mail delivery system fails then his unit test fails. Failing test would mean there is something wrong with his order system but in reality the problem could either be in the network, the smtp server or somewhere else in the universe between the mailbox and his system.
  • Then he passed on the code to his colleague for review. The colleague first of all wanted to evaluate the design so he collapsed the code blocks and just looked at the interface. It wasn’t immediately clear that this component also has a dependency on email subsystem. Why? Because the implementation secretly and directly talks to the Email static class. Email subsystem doesn’t have to be injected into it anywhere. It doesn’t go in the constructor or in any property. It doesn’t seem that this system sends an email at all. Its after you look at the implementation of the class, when you realize that this class also has a dependency on another class.

Some people might say. Oh well! We don’t write unit tests and we don’t mind looking at implementation of classes to understand whats going on. We’re after all not the most productive team on earth. We take our time in fixing bugs and understanding code after all thats what our infinite sprint cycles are for. We’re ‘Agile’.

Nevermind, the story continues. Later Tim is asked to make it so that we either send sms or email confirmation based on the settings of the user.
If he changes the code to add an ‘IF’ statement then he is introducing two code paths in his method.

        public void AddOrder(User user, Product product)
            // Persist the order in DB
            if (user.ConfirmationMethod == ConfirmationMethod.Email)
                Email.Send(user.Email, "Order confirmation", "Your order has been placed");
                Sms.Send(user.Mobile, "Your order has been placed");
  • The more number of distinct code paths a method has the more tests you have to write to cover all the code paths and ensure correctness.
  • The more number of distinct code paths a method has the more chances of bugs you have due to variation of code paths and states.
  • Now his test also fails if there is problem in SMS sending subsystem hinting as if there is a problem in his method.

In reality Tim was really asked to introduce a new mechanism of confirmation message sending but he wen’t and modified the order system class which is irrelevant but he ‘had to’ because the mechanism of sending email was ‘baked’ into the implementation.

Some may argue at this point, “Well he could have faced all these problems even if the class was not static”. Yes that’s right but could he arrive at the right solution keeping the class or his mentality static?

So Tim realized that sending a confirmation message is something that needs to be abstracted out. He needs to be able to plug in the right implementation and he should be able to solve most of the issues related to adding new ways of delivery, reduced cyclomatic complexity, unit testing etc. He was right in his thoughts up to this point but he was somehow obsessed with static classes and loved the simplicity of being able to do something in one line without creating any objects or anything so he chose a wrong solution to the problem which was something like the following:

    abstract class OrderSystem
        public void AddOrder(User user, Product product)
            // Persist the order in DB

        protected abstract void SendConfirmation(User user);

As you can see he turned his class into an abstract class with a SendConfirmation method. Now he thought he would create one derived class for sending email and one for sending sms and he can mock this easily for unit testing purpose also.

Some may say, “Fair enough! Guy has a decent solution to the problem.”

So when you go to a restaurant do you have different kinds of waiters for taking orders for different kind of food?
Umm I want to eat vegetable so I’ll call that waiter wearing green shirt. Oh you want some meat? Lets call that waiter wearing red shirt. Doesn’t make sense right? The job of the waiter is to note down the dish you want to eat. The change of choice of dish for each customer is abstracted out in something called ‘order menu’. You don’t create different kind of waiters for different kind of dishes.

So he solved the problem by further damaging the design. Besides what would you do if you want to send sms and email both?

Alright so whats the ‘right’ way of solving the problem? The answer should be clear by now. We need to abstract out confirmation mechanism into a non static class like so:

    abstract class ConfirmationSender
        public abstract void SendConfirmation(User user);

    class SMSConfirmationSender: ConfirmationSender
        public override void SendConfirmation(User user)
            // Send sms here how ever you want

    class EmailConfirmationSender : ConfirmationSender
  • Now his AddOrder method can take the ConfirmationSender as a parameter or in the constructor of the class depending upon whether the mechanism changes per user or based on system setting.
  • From the interface of the class it is very clear that this class has a dependency on another class. You don’t need to look at the implementation of the method to realize it also has to send confirmation via email or sms.
  • You can unit test this method without having to actually check mailbox of the user.
  • Your test will no longer fail because of problem in email delivery mechanism because unit test will mock the ConfirmationSender and only verify if the confirmation was sent or not.
  • For adding new confirmation delivery mechanisms you don’t have to modify the OrderSystem. The less this code gets modified the more stable and bug free it will be.
  • The cyclomatic complexity will not increase with each new confirmation mechanism. Or even if you don’t want to send confirmation at all, you can just create a NullConfirmationSender that doesn’t do anything and just feed that to the method.
  • So like I said earlier. He could have all these problems even if the email sender was not a static class but if it is a static class it encourages all the wrong patterns and introduces the problems.

    Some may say, “Ok so static class is evil then?” No! It does make sense to make a class static when

  • It doesn’t have any state to maintain.
  • The methods are very simple unit of operations that are ‘universal truth’ and won’t ever change.

The best example of perfect static class and method is Math class with methods like Min(num1, num2), Max(num1, num2), Sqrt(num), Abs(num), Sin(num).
Definition of Minimum, Maximum, Sin, Cos, etc. will never change. They are very small, highly concise fast operations. Whether a class has dependency on Math class at all, doesn’t even matter.

Some may say, “I’ve seen static classes with state in code written by top notch programmers”. Well every rule has an exception. You need to be able to judge what makes sense in what scenario, how much you care, how much time you have, how much ‘agile’ your team is, etc.

You might ask, “What about singletons? Shouldn’t we make a class static when there is only one instance in our universe for that?”. No! First of all the fact you need to have a single instance in your modeled universe, has nothing to do with whether class should be static or not. Static means “I don’t have state. I’m a helper.” If you really really want a single instance throughout your application you can opt for Singleton pattern.

“Why two times ‘really’ in your statement?”, you might ask. Well because such a strict definition of single instance can limit the possibility to have parallel worlds in your application and also you can still enforce single instance by using dependency injection framework and correct life time hints while registeration instead of making the class singleton. If you don’t use dependency injection and you want to make it clear by ‘design’ that you don’t want more than one instance lurking around in the app then you can opt for the Singleton.

Introducing Squiggle Multicast Service

In revision 4 of Squiggle 2.6 I’ve introduced a major change which I normally not do in revision updates. Squiggle 2.6.4 now included the Multicast Service and the Squiggle Client supports connecting to it of course.

Squiggle Multicast is helpful where the router does not support multicast communication (or it has been deliberately blocked by network admin). All you have to do in such scenario is that:

  • You have to download Squiggle 2.6b Multicast.zip from Download page
  • Extract it on one of the machine in the network
  • In Squiggle.Multicast.exe.config specify the ip and port (of the same machine) on which you want to publish multicast service
  • Install it as a service by running the command “Squiggle.Multicast.exe -i” in command prompt
  • Make sure that the service is running
  • In all of your Squiggle clients in network, go to the settings tab and specify the same IP and Port in presence address and port fields
  • Now sign-in from all the clients

Now some background. Recently Squiggle stopped working at my work place because maybe they changed the router or disabled multicast communication. I didn’t investigate much since it was an opportunity for me to work around it by introducing the multicast service. Besides I’ve already received a few emails from different people who couldn’t use Squiggle for the same reason.

So now you might be thinking is Squiggle a client/server application in that scenario? I’d say no. Because multicast service effectively only forwards the login/logout and status update messages. Once the clients receive such a message from the service they go in to peer to peer mode and talk directly for getting detailed user information or chatting.


How to Implement MVVMP Pattern

First I explained what MVVMP is and then I illustrated how it makes more sense than MVVM. Now I’m going to show you how to implement MVVMP a.k.a. Model View ViewModel Presenter pattern using PRISM and WPF.

I have created a stub project that I’ll explain just now and I have built a sample calculator application using that to demonstrate the use of pattern. Our Stub Prism application has following 3 projects

1) Shell
2) Infrastructure
3) SampleModule

Shell project contains the Shell Window and the bootstrapper. I will not go into details of things that require knowledge of prism since the main purpose of this blog post is to explain MVVMP.

Our second project i.e. Infrastructure needs to have a few interfaces and base classes which are as follows:

  • IView: Every view interface has to derive from this interface and it has a convinent DataContext property that allows us to set the datacontext for the views.
  • IPresenter: Again every presenter has to implement this interface. It has a view property that we will use to return the view from presenter when it is resolved from container.
  • ViewModelBase: This is the base class for all view models that has one important property called KeepAlive
  • PresenterBase: This base class does the basic job of instantiating the view model and assigning the presenter instance to KeepAlive property.

The ViewModelBase needs to have KeepAlive propery because we need presenter to stay alive for as long as view is alive and there is nothing that is referencing the presenter.
View doesn’t get garbage collected because it is loaded in VisualTree
ViewModel doesn’t get garbage collected because it is DataContext of view and hence referenced by View
Presenter doesn’t get garbage collected because it is referenced by ViewModel using KeepAlive property

If we don’t have this property then presenter will get garbage collected after some time and your view will become dysfunctional.

So at this point we have all the essential ingredients we need to build our MVVMP based application.

The final step is to now have the set of view,presenter and viewmodel instantiated and stitched when the module is initialized so in the Initialize method of our module we register all the types against their respective interfaces.
The RegisterViewWithRegion call is as follows:

RegionRegistry.RegisterViewWithRegion(RegionNames.SampleRegion, () => Container.Resolve<IPresenter<ISampleView>>().View);

Notice that instead of specifying the ViewType we’re using the getContentDelegate overload which allows us to instantiate the presenter by resolving it using Unity and then we can return the public View property.
Here we are using Presenter first pattern i.e. we resolve the presenter and we is instantiated as a side effect (because it is a constructor dependency of presenter).
So thats it; when the shell is loaded, the presenter is automatically created, the resulting view is injected in shell and the presenter can now manipulate the ViewModel using its ViewModel property and View using the ViewProperty.

This pattern can also be used in a wpf application that doesn’t use prism.
It only depends on dependency injection mechanism therefore you need something like Unity to instantiate and inject the views in presenters or you can use some kind of factory class to do that for you (Poor man’s DI).
I have also created a sample wpf application that demonstrates MVVMP without using prism.

The projects are hosted at http://mvvmpsample.codeplex.com
Download the code and use it in your own project without any restrictions (MIT License).

Model View ViewModel Presenter pattern in the Kitchen

To better illustrate my self cooked MVVMP pattern I have created the following image

Here chicken is the model and the person is the view. This means that view ultimately consumes the model but before it is in consumable form it has to go through Presenter (i.e. get cooked) and then presented in a ViewModel (plate) to consume from. This is the most sane way of doing things.

Now in a typical MVVM pattern what people do is that they combine the presenter and viewmodel into one thing called ViewModel i.e. they add business logic in the viewmodel instead of separating it in Presenter. So semantically it means that people tend to eat straight from the pressure cooker when the food is ready instead of pouring it in the plate. For them the cooker not only cooks but also serves as the container to eat from.

In MVVMP the ViewModel contains the properties solely for the purpose of data binding on the view and holding references to ICommand . Presenter contains IView and ViewModel references and acts as a command and control center for both.

So yes Tom (the person) can practically eat the chicken directly from the cooker once it is cooked but that won’t be very civilized way of doing things similarly in the world of programming MVVM doesn’t seem civilized to me therefore we have MVVMP (Model View ViewModel and Presenter) pattern.

How I localized Squiggle Messenger

There are plenty of ways to Localize a WPF application e.g. LocBaml, ResX, Markup Extension, Resource dictionary, Attached properties,  e.t.c. http://wpflocalization.codeplex.com/

I wanted a way that is fast, doesn’t require writing a lot of code, allows the end users to also localize and doesn’t make releasing a new version a problem for me.

So I chose to go with Resource Dictionary approach. There is a Translation.xaml file in Resources folder which imports the system namespace and declares a bunch of strings. In UI xaml I have dynamic resource extension pointing to strings in that dictionary. The dictionary is merged in App.xaml so its available to all screens.

Some strings were in code as well so I created a Translation.cs file in the resources namespace which has statistic properties, one for each string used in code. In the static constructor of the class I loop over the properties of the class and load the values by looking up the resources of the application by key names equal to property names. So in code those strings were replaced by references to those static properties.

So the users can just replace the translation file with the one of their own and enjoy a localized Squiggle.