Generic method to avoid long IF clauses

Dear Reader,

Recently at work, i was working with a library which had lot of properties wherein they must be verified for its Truth value before exporting or importing respective attributes to file or back to UI respectively.

Basically, the raw code initially looked roughly like below:

void ExampleMethod() {
SomeType type = new SomeType();

if (type.HasValue1)
  //Export Value1
if (type.HasValue2)
  //Export Value2
if (type.HasValue3)
  //Export Value3
if (type.HasValue4)
  //Export Value4
if (type.HasValue5)
  //Export Value5
if (type.HasValue6)
  //Export Value6
if (type.HasValue7)
  //Export Value7
if (type.HasValue8)
  //Export Value8
if (type.HasValue9)
  //Export Value9
if (type.HasValue10)
  //Export Value10
if (type.HasValue11)
  //Export Value11
if (type.HasValue12)
  //Export Value12

if (type.HasValue25)
  //Export Value25

The above case got repetitive at many places for other types in the same library based on level of their appearance in the UI viz. tree level node. The body of the if-clause all over the place remained same i.e 1 – Check for Truth, 2 – if success, Add to some final list for exporting/importing if not already present.

The method complexity in some cases went over 20 which was getting really gruesome to me. Finally, i decided to refactor the code to reduce not just the complexity but also find a unified solution for other basic types if need be.

Struck to me are 2 possible yet simple solutions yet satisfying the required criteria.

Solution 1: To use the Dictionary<Func< T >, SomeType>, but the body of all those if clauses required another 3rd parameter which hindered me to not opt the dictionary since Dictionary can’t have more than Key : Value pair thus making me to add dictionary inside dictionary which is not only complex in readability aspects but also Value dictionary may not be unique as well. So i had to discard this solution.

Solution 2: To make use of Generic Methods with delegates via lambda expression. This proved to be a working solution in this case yet very simple and effective.

void CheckAndDoSomething < T > (Func< T > property, object Value,
object otherValue) where T: struct
  Type t = typeof(T);
  if (t is bool && property())
     //Do some thing with Value and OtherValue

void ExampleMethod()
  SomeType type = new SomeType();
CheckAndDoSomething(() => type.HasValue1,value0, otherValue0);
CheckAndDoSomething(() => type.HasValue2,value1, otherValue1);
CheckAndDoSomething(() => type.HasValue3,value2, otherValue2);


Hope it helps,
Zen :)

Xiaomi Redmi File transferring with Linux.

Explained in simple steps:

1. You need ADB (Android Bridge) tools. Just paste this in your terminal as SU bash <(curl…/nexus…/master/
2. The nexus tool downloads and install appropriate version of ADB for your Linux box. Wait few minutes.
3. As SU, execute => adb start-server
4. Enable USB debugging on ur RedMe and connect to your linux box.
5. Still as SU, execute => adb devices. It shall list your android device.
6. If you get “????????? no permission” as output from step 5, then you have not started adb service as SU and other commands too.
7. Once you got things straight. Now copy files from phone to pc via “adb pull” or paste to phone via “adb push”.
8. In my case, i wanted to copy entire DIR onto phone. So i did just “adb push /PC_DIR_Path/DIR_TO_COPY /PHONE/DIR_COPIED
9. To know the path on your phone, just use any file explorer and get the details of path. In my case it was /storage/sdcard1/Music. It could be different on yours.

GOA: Dream trip come true!

The background story goes like 4 years back, where in i had been waiting and planning to visit the exotic place GOA. Every time a plan is made, some or the other reasons the folks used to back out or some other problems. Yes it took 4 years for this damn plan to get executed. We bangloreans do really have lousy busy life… :|

The start of the new year, did bring in some good luck for me :) The plan got executed. We went for 5 beaches : Vagator, calangute, anjuna, baga and condolim.

The route suggested to me was : Belgaum – amboli ghat – sawantwadi – goa. Onward journey we took Belgaum – VTU – kankumbi – surla (chorla ghat) – mapusa by inquiring with local tea shop guys at Belgaum. To our surprise, this route was much much better than sawantwadi route which was our return journey.

On this route there is no lousy RTO check post or police trouble and even the goa police check post also doesnt bother much to the travellers. I rekon this route is mostly used by the local folks than others. The traffic on this route was very very minimal. The whole Chorla ghat section is around 50kms ODD. The road conditions on this ghat is brand new and awesome. I loved driving in this section compared to amboli in all senses.

Let pics do the talk…. First trip i did not care to take enough pics…

Onward journey

The onward journey road was soo good, i loved driving till Goa from Chitradurga. And the fact that its my babez (Punto), it just rushes out all the adrenaline you need :)

Apparently security did not let us in to see VTU upclose as no lights were on.

The early morning pit stop after Chorla Ghat section drive.

Palacete Rodrigues: The lousy hotel we stayed at Anjuna beach. As per website, this place suppose (pics wise) to have beautiful rooms, big pool and good food restaurant. Pool size is soo small that you hardly can toss around. The rooms size of 4 were lousy, the cots were bad, bed spreads dirty. The food was bad or next to horrible. I personally would rate this place 1. I heard that the couples suite costing 6+k/day is good but the ones which we stayed costed 3k, was not

Lovely view from Agoda Fort

Thats the agoda forts light house.

Sinquerim Rocks, Condolim beach. Beware there is not enough parking space here.

If lit well, Suvarna vidhana soudha should have been visible :(

Curries Bar & Restaurant : Very nice place outside calangute beach area and very nice food, good prices and rooms available too. I recommend this place for any body. They have couples bedroom, family (10 member) bedrooms too and very good prices. Foods are very reasonable prices too. We loved the food though with good quality. This guy Mahesh does very clean business. Infact our next visit to goa will def choose this place.
Address: Porba Vaddo, Calangute, Bardex, Goa 403 517. Email: Ph: 9822580711

Loved the food and stuffs here.

Decision matrix implementation in C#

Dear Reader,

Yesterday i faced a problem where the combinations possibilities were many and i had to implement code for this problem. Obvious solution is to implement If – else ladder. But i absolute hate this solution because the combination were around 5C3. The combination data was about behavior aspect of a scenario. Next solution is to use Switch block. But this solution involves inner switch combinations. So down the line it gets more complicated.

Next solution was to go for dictionary. But the problem with dictionary is the key uniqueness. In my case, most of the keys were not unique. So either i had to customize the dictionary behavior (List of KeyValuePair) or go for some thing else. The earlier will lead to writing alot of code for small problem and involves more cost factor in terms of development time and testing effort.  Idea rejected.

Then i suddenly remembered to make use of Decision table. So googling a bit to learn more about decision matrix, this is what i could implement which is not just extensible but also easy to understand and easy to add/modify later on. No need to change in the actual code (finding the combo) unless the way to look up methodology changes.

Sample code:


At line 27, i am here searching for a combination key of “Condition3″ AND “ASC”, then get the result from the matrix. Line 31, have used FirstOrDefault() than First() to avoid exception when result is not found.

Hope it helps,
Zen :)

Linux: gdm (XServer) Crash with error dgm_slave_xioerror_handler

Dear Reader,

Recently upgrading XServer, GDM with many other packages, suddenly launching gthumb started to crash the XServer. Resulting me to pop back into login window. This happen all the time consistently. At first i thought it was the problem with Gthumb application itself. Tracing back the upgrade log, i did not find itself getting upgraded in a long time. So next step was to see its dependent packages. From the .dep file in the FTP server, i saw there was huge number of packages on which gthumb is dependent on. So going this way in finding which was upgraded and which was is not really a good choice. So i immediately started to look into kernel messages aka dmesg and system logs files.

I did not find much information in dmesg. Next digging further into /var/log/syslog file prompted me to this error line:

gdm-binary[5197]: WARNING: gdm_slave_xioerror_handler: Fatal X error – Restarting :0

This line itself was enough to give me assurance that it was caused by the GDM and not any gtumb or related applications. Now GDM package involves even Xserver packages too. So googling was the only left out solution. As per google, there were many suggestions given i.e Reinstalling xserver packages, editing xorg.conf file, etc. None of them was much helpful.

Next is to look at the video driver side. So looked at the Nvidia Linux drivers page, found that a long stable version is released which is 319.49. I had 319.23. The new version release notes also mentions about a bug fix on Xserver/gdm crash. So immediately went for upgrading the driver.
Voila, it worked. Now i can use gthumb, gimp and other applications which were causing the crash.
Hope it helps…

Zen :)

My Car Buying learning’s

Dear All,

Below is the learning’s, which i wish to write about coz they helped me in making sure my booking, buying, delivery process went smooth and nothing oh shit moments. Hope it will help future buyers.

Of course the SA was really helpful to me here.

These are my personal learning’s based on my seeking information from fellow TFI folks, extensive reading of TFI threads, mistakes and observations. Feel free to pick it up if you agree so (Not in correct order).

  • Always carry pen and paper: Helpful in taking notes than later “Oh Shit forgot that” moments.
  • When booking, always ask for a clear cut brake-up of charges (detailly) and written on a paper by the SA. Keep and carry that with you till PDI day.
  • Make a note of all the agreements (prices, goodies, etc.) said by the SA.
  • Know your car and its features clearly and good.
  • Read the datasheet of the model which you have chosen. Remember all the things written in the datasheet. SA might throw you some bones here.
  • Keep mentioning about TFI to SA.
  • Say youll be writing review reports, etc. @TFI. Quite helpful.
  • See if you get a gap to meet the boss of SA, again mention about TFI to him as well.
  • Dont let SA’s fool you easily. Always gather more information about the car or FIAT or prices, etc. TFI is really good source for that.
  • Try to haggle as much as possible. Aim for goodies/freebies.
  • Aim/Demand for all OEM (FIAT) made freebies from dealer for free. (Thanks Neeraj for reminding me and helping me over calls)
  • Make sure you thank SA as and when required in-front his boss or his colleagues, but please mean it. Happy SA = Happy You.
  • If SA doesnt call often and gives you updates (self initiative) , that means he isnt interested much in your buying. After your booking, give it couple of days as he/she has agreed to give you updates. Later on if no news, then he/She just not into you. Find other ways to deal. (Neeraj faced this problem)
  • Dont be rude or demanding unless you know SA is lethargic.
  • On PDI day, carry all the papers, PDI checklist with you. Be kind in requesting/notifying your SA for his time for PDI. If SA asks for a time change, try to adjust. Always Win:Win works better.
  • Do extensive PDI on your car. If car seemed to have dirt here and there, make a kind request with SA to get it washed. Yard has all facilities. Mention well ahead to SA that youll be doing extensive PDI, so its bound to take more time.
  • Carry USB stick (songs) and an Audio CD with you.
  • See if your Phone Bluetooth works with Cars Blue and Me.
  • Do note down all stuffs (Not working) in the car.
  • If you are getting Parking sensors, then ask for OEM made (if you wish), Car cover again OEM.
  • If car data sheet mentions Remote for HU. Then ask for it. Note it down to get it when taking delivery.
  • On delivery day, carry a good gift for the SA. Need not to be expensive. Worth of 1K is good.
  • Carry Sweets to give it all there, on weekdays less people will be present compared to weekend. At KHT i saw atleast 20 peeps in weekend and hardly 10 on weekdays in my 4 time visits.
  • Re-do PDI checks roughly. Ask SA to explain all the features of the car.
  • Ask as many doubts as possible.
  • Ask SA to load all contacts of your phone to cars blue and me. Some mobiles wont support this, i was informed by my SA.
  • Check voice commands and try out all keys on ur dashboard, steering mounted keys for working nature as per PDI check list.
  • Go for a short TD and observe for rattles, alignments, etc.
  • Before documentation process, make sure SA gets all the accessories as agreed is on the table. If not, remind him.
  • Before signing any official documents, check for
    1) Original Car Documents
    2) Warranty cards of car, parking sensors
    3) Key code card
    4) Battery warranty card
    5) Extended warranty card
    6) Original Tax Receipt a MUST.
    7) Insurance papers
    8) Original Invoice
    9) Fuel Coupon (If any)
    10) Other documents if any.
  • Get all above documents sealed
  • Request for Absolute Mud flaps (if agreed)
  • Request for Floor mats
  • Once all documentation is done, key shall be handed over to you.
  • Give the honor of giving him the Gift and thank him.
  • Distribute sweets starting off with the SA.
  • They shall take you to the car to give a formal handover again. Carry camera to capture this moments.
  • Thank every one and request for their continuous support in future and say you are really happy and going to write good review about them, but mean it
  • Fill the fuel.
  • Drive home safely.


Progress Modal Dialog Launch from another Thread


Today i encountered a problem to fit one of the use case, so i went ahead to develop a prototype. Because of rest of the layering architecture i had to take a bad design decision. I had to launch a progress dialog as modal dialog on top of the main window but do not block the main window thread from further data processing. So i had to launch this progress dialog in a different child thread and make the main window as its parent. The main thread shall do alot of processing and notifies the progress dialog about the updates. Basically the below layers in the main thread calculates some data and informs it to the UI  for displaying. To accommodate this i tried couple of ways and reached dead-end. Referring to couple of stackover flow threads also did not give me complete answer, but they indeed gave me some insights. Thanks to those guys.

So i came up with a prototype with a simple winform main app having a button which again creates a progress dialog as modal in a separate thread then update progress bar values from the main thread. Below is rough diagram of how it should be:

progress Dlg

So after exhaustive effort for a day, i came up with below code which seem to work out well as per the stated requirement above. Below is the code:

public class MainForm1 : Form
        int counter = 0;
        Thread progressDialogUIThread;
        bool stopProcessing = false;
        ManualResetEvent resetEvent = new ManualResetEvent(false);
        ProgressDialogForm2 progressDlg;

        private void button1_Click(object sender, EventArgs e)
            progressDialogUIThread = new Thread(new ThreadStart(InitializeDialog));
            this.Enabled = false;
           //Wait till child thread creates and initialize the dialog instance

        private void InitializeDialog()
            progressDlg = new ProgressDialogForm2();           

            progressDlg.cancelButtonEvent = new EventHandler((s, e1) =>
                switch (progressDlg.DialogResult)
                     case DialogResult.Cancel: 
                        stopProcessing = true;

            //Cant pass owner here, since child thread so throws cross thread excep.

        private void UpdateProgressData()
            for (int i = 0; i < 100; i++)//Range of Progress bar is 0-100
               //Closing dialog window on cancel button click, hence flag check. 
                if (!stopProcessing)
                  //If not checked, then window is closed and below invoke throws exception.
                    progressDlg.Invoke(new Action<int>(progressDlg.SetProgressValue),
                           new object[] { i });
                    //Just to put some delay in updating progress bar for visiblity purpose
                else this.Enabled = true;

        private void Form1_Activated(object sender, EventArgs e)
           if (progressDlg != null)
                if (!stopProcessing)//When dialog is closed, nothing to update.
                    this.Invoke(new Action(progressDlg.BringToFront));

public partial class ProgressDialogForm2: Form
        public EventHandler cancelButtonEvent;

         public void SetProgressValue(int value)

        private void button1_Click(object sender, EventArgs e)
            this.DialogResult = DialogResult.Cancel;
            if(cancelButtonEvent != null)

Hope it was helpful.

Happy Coding :)
Zen :)