.NET

All posts tagged .NET

Dear,

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;
            progressDialogUIThread.Start();
           //Wait till child thread creates and initialize the dialog instance
            resetEvent.WaitOne();
            UpdateProgressData();
        }

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

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

            resetEvent.Set();
            //Cant pass owner here, since child thread so throws cross thread excep.
            progressDlg.ShowDialog();
        }

        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
                    Thread.Sleep(500);
                }
                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)
        {
            this.progressBar1.PerformStep();
        }

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

Hope it was helpful.

Happy Coding :)
Zen :)

Dear Reader,

Today on my Win 7 (VM install guest on Zenwalk Linux) VS 2012 RC expired. Hence i had to uninstall it. Unfortunately after it uninstalled, it did not clean up all the paths and links and corrected the changed paths of some too, in this case devenv command path (Beta build yea!). Though i restarted the VM twice, still the problem persisted. Hence i could not launch VS 2010 from Start -> Run or even from command prompt.

After googling for a while, i did end up with nothing apparently. So searching to fix this issue had to fiddle with the stupid windows registry.

So if you also face the same issue, here is the path for it:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\devenv.exe\

Short and Hope it helps.

Happy Coding,
Zen :)

Dear Reader,

I am working on a legacy code base which not only is quite challenging but troublesome as well, sometimes shit, sometimes pleasant, all in all its a roller coaster ride for me. So lately i picked up a task of implementing a feature where in had to provide a functionality of Import and Exporting some data by other indirect means i.e no manual user intervention. Based on my analysis, i found out that this feature is already present for one particular type via GUI intervention. Now i need to replicate this feature as a background activity.

Yes it might sound like what is the big fuss to blog about it? Right, even before writing this blog i though of this point many times. But i did face 1 challenge in solving this problem w.r.t design issue which i am going to share it soon. But before let me give you a brief overview about the current design and then later i shall share how i got stuck for like half day thinking about possible best solution.

Below image shows the current class design:

As you can see from the above hierarchy design structure which looks pretty much good, but for this feature which i am implementing poses a challenge because this feature which is already provided via a manual invocation via GUI menu is only supported for Master Types specifically supported for MasterC type. But unfortunately the earlier developer didn’t see this through well and implemented all the code in base class i.e BaseType.

But the similar feature which i have to implement should only be supported by all Master types which is almost similar to already implemented for MasterC, but remember the full implementation is in BaseType which logically is wrong but i am guessing that original developer didn’t had the requirement at that time of supporting all other derived types, but still it was wrong.

Any way, to implement my feature for all Master Types i had this problem of how to override this already implemented code which is in BaseType.  So i came up with couple of possible solution which has pro’s and con’s. Lemme list them below:

Solution 1:

  •  Just move the code (marking that method as virtual and override in MasterC type) which is already implemented for MasterC from BaseType to MasterC, because as of now it just only supported for MasterC as far as i know.
  • Very simple and easy to do, but has problems.
  • Product is legacy, so its high risk to move it. I never know which corner test case i could break.
  • Overriding this feature in MasterC, poses another problem where in, the feature which i am implementing should world in the background as well as same functionality (Import and Export) should work when manually invoked via GUI menu for MasterC.
  • So overriding this method for my feature will break the manual intervention feature.

Solution 2:

  • Implement subclass for this feature for MasterC, lets call the feature as FeatureX, thus naming the class as MasterCFetureX as shown, since MasterC is the odd type here having both features to be supported.

  • This way, as thought in solution 1, i can mark that method as virtual and override in MasterCFeatureX to execute a customize version of the same code already implemented for my requirement/feature and when manual invocation is done which is already existing feature for MasterC, then the virtual method in MasterC will get execute. This way, i get what i want and existing functionality is not broken.
  • But the problem is, the source where the object MasterC is created based on the menu action is not implemented via any creational patterns viz Factory. If it had been, for this sub menu item action i could create object of MasterCFeatureX an played with it. But since it is not there, implementing such patten at the UI level till business is  huge and very risky because changes and impact is huge in terms of effort and time.
  • Another problem is the level of hierarchy could grow more, thus making code maintainability tedious.
  • Many test cases are risk to be broken if chosen this way. Hence dropped.

Solution 3:

  • Very simple and straightforward but crude and filthy which i myself still do not like. But i am forced, so that feature gets delivered in time.
  • The method which is already implemented BaseType takes an argument (some container from another library). So i added a enum type called ViewFeatureTypes which had None, FeatureX, FeatureY, etc. into this container. Now when i am invoking this call for my feature from View, i set this enum type value in the container and check this value in the code in BaseType.
  • This enum can be used in various other places where i am sure such design constraints exists. So for future purposes added Enum than a bool member to this container type.
  • As said, very safe and simple yet crude and dirty. :x

Thanks & Happy Designing,
Zen :)

P.S: Please drop your feedback. I am not a good designer, but see myself there in career. So any suggestions are welcome.

Dear Reader,

This is one of the learning activity i went through recently which i would like to share. Lately i am kinda doing testing as part of team effort so that task can be finished off soon and well with in the time line.
Any way, so this module which was tested earlier was given to me for 1 final round of testing before it can be certified as complete and tested by our internal tester. So at first i just though i shall do as simple as a testing person shall do with a testing mindset, hence i borrowed all the test cases already defined.

My testing continued for a while with all the test cases given. As soon as i was finished with all the test cases which were exhaustive, all of them got passed. I was happy that all passed and i did not find any bugs. I actually felt we gonna finish off the task way ahead of dead line. So i took a break for 5 mins and went for a coffee.

This break did really kicked me hard and kept me worrying that i must have missed or i did not do enough testing. Basically i was not contended about the results i got from my activity. Though, i finished off my activity way ahead of time, still i was bit unsatisfied about the outcome.

As i immersed myself into my coffee, it did strike me up with couple of questions which i started asking myself as “what would be the output if i did this?”, “what would be the output if i do that?”.

Basically i started adding a lot experimenting test cases in my head. I heard somebody calling it as monkey testing, but its not really it is, since it is done during unit testing and not as part of module testing.

Hence i got back from my coffee break, and spend another 2 hours doing my experiment with this module with almost 10 test cases, i came up with. Gladly at the end of an hour or so, all my experimenting test cases failed. Even some resulting in complete application crash. :)

I was completely satisfied about my work and i reported to my colleagues and to be frank, they even appreciated my experiment :D

Happy Coding,
Zen :)

Dear Reader,

This is about the incident i faced with one of my colleague today wherein a word which was not noticed properly impacted in judging me completely different.

Normally I read technical books (Mostly C#, Unit testing, Refactoring, Design patterns, etc.) while i travel to office in the bus. As usual today i started reading Art of Unit Testing by Roy book. Not to forget, this book is amazing if you wish to improve your skills.

So as i kept reading, after a couple of stops one of my colleague boarded the bus and it happen so that he has to take seat next to me, hence i made some space for him, then i continued to read further. After a couple of minutes this guy turns towards me and says what is this book your reading.

I smiled and said its w.r.t to my work thinking that he does not belong to the IT field (yes i casually know this guy), he then says ok, about what specifically. This was the awkward moment for me because i did show him the cover of this book.

His immediate response was, is there a text book on unit testing too? He made a gesture and face expression as if i am a newbie in this field and was learning just now because he knew i am not. Although i did not feel embarrassed at that moment, but his weird smile made me further uncomfortable. He then started asking, why are you reading this text-book. This was another moment i felt awkwardness since he had already referred this book as “text-book” because most of us have a feeling that a text-book is just like a starter kit which is studied by college students.

He continued making further funny gestures which made me uncomfortable. I turned away from him for a moment to control my embarrassment because there were other folks who on-looked at our conversation. After a second, it suddenly occurred to me that he failed to spot one good meaningful word on the book cover. Immediately i turned back at him and smiled, which suddenly made him feel weird about my reaction. He kept staring at me for a second, after which i once again pointed him towards the cover of the book.

I pointed him towards the word “ART” on the book cover and said it’s not a text-book but It’s about improving your skills and its about writing better unit tests and maintainability code. At that instant, he felt some thing good in his mind and made a surprising face and immediately acknowledged that he did not notice the word “Art” in the title. He then said “oh nice” and went back to his sleep.

This incident kept me thinking and wondering about how just one word when unnoticed makes a big fuss or poor judgement about the person and his capabilities. I must say it was a whole new experience to me. Perhaps this is why communication is a very good topic to master in. Thankfully i came up with a good explanation to convince him that i am not a kid.

Thanks & Happy Reading/Coding,
Zen :)

Very good reading and i liked the way it is being presented. Good to take couple of points and cultivate a habit in our life :)


http://blog.penelopetrunk.com/2009/01/08/5-time-management-tricks-i-learned-from-years-of-hating-tim-ferriss/comment-page-19/#comment-311982

Dear All,

Tired of making sure you have not done any RESERVED checked out in your development branch whenever you wish to check out a file every time? Or you have always got irritated to uncheck the option (manually) Reserved in the Clear case Checkout dialog whenever you wish to check out a file especially when all your team members share same branch for development.

Do not worry, you can permanently disable automatic reserved check out in the clear case plug-in of Visual studio as shown in the below screen shot. Just uncheck Reserved option as highlighted in the below screen.

Steps to do:

  1. Go to Visual studio -> Tools -> Options
  2. Select Rational Clear Case -> General (As shown below)
  3. Click Clearcase User options button as shown below.


Hope it helps.

Thanks & Happy Coding :)
Zen

Dear Reader,

Today i was having a discussion with one my team member about exception handling when i saw my team members code (No, i wasn’t reviewing his code or some thing).

This team member had written a business logic code (Core part i would say) where the exception was handled and just thrown as shown in below sample code at couple of places :

public void SomeCoreMethod()
{
 try
 {
   //blah blah blah code 1
   //blah blah blah code 2
   //blah blah blah code 3
   //blah blah blah code 4
 }
 catch(Exception ex)
 {
   throw ex;
 }
}

The above code is absolutely fine, but it has some corner spots which any developer can over look. So below were my findings with that person which started a bit of long discussion. So this post is about that conversation which might help you if you have such dilemma situations.

So my finding was presented to that developer as below (Yes based on my stackoverflow, Jeffrey Ritcher book, Jon skeet articles, etc. and my own thoughts references)

  1. Catching generic exception is never good option. This shows that you as a developer does not know about your own code. Referenced Amazed saint blog post to that developer as a proof read.
  2. Just catching and throwing is not at all useful. Because when a catch block is encountered, the CLR has to stop that thread execution, unwind its stack, save memory state, etc. which is very costly if its done every where.
  3. Throwing an exception object as above will re-initialize the StackTrace data where in you might loose the original source of exception occurrence. So hence just use throw
  4. Rather than handling here, just let the exception flow and let us handle it in the one place perhaps UI layer? Where we can log it and then have a graceful recovery. This helps in centralized logging and better recovery and handling mechanism.

To my above points, the developer continued further discussions perhaps presented self view points which i do respect completely though it is write or wrong.

So the view points of that developer was as below:

  1. Yes it can be changed but lets see.
  2. Ok! I shall not just throw rather log it here and then throw.
  3. Is it? Nah i do not think so. I am sure it can not be happening that way : Its a violation of feature integrity meaning same operation can not be done this way and the other way.
  4. To this one more member jumped in and argued that it need not to be done at one place, but rather do it there itself and throw to which the actual colleague did not oppose nor accepted.

So for the above points i had to explain to that colleague couple of my thoughts and why i think and agree along with experts mentioned above.

  • Logging at that place and re-throwing the same is not a bad idea. But think about the future. If you have to change the logging logic, you may have to find every where this logic and change it or if you have to remove the logic completely then again you have to do it every where.
  • To prove that throw and throw ex actually differ, had to write a sample app and prove. Also i stated my explanation about why its not data/implementation integrity as below:
    Integrity issue happens only when =

If you have an Action A which can be done/solved by only 1 solution S but the outcome of S differs on conditions C1, C2, etc. : Then its a feature integrity violation.
But in this case, the same action A can be done/solved by 2 solutions S1 and S2 where as their outcome is the same depending on the way its usage and needs : Then its not at all any violation but rather flexibility.

After presenting my thoughts as stated above, the discussion seem to end and that friend did not come back with any further discussion points. I hope my view points was constructively received.

So dear reader:

Thanks & Happy Coding,
Zen :)