Sunday, May 11, 2014

We (I am) are moving!

If you have been following (or liked) any of my posts in this blog and would like to hear from my site - you can subscribe/visit my new address : devdumps.com

I have re-posted some of my articles in this blog to the new blog. The idea of having a dedicated blog and site is to have better control and more commitment from my side.

I won't be closing this blog for few months but yes, won't be writing any new articles here.

Thanks
See you at my new location!

Monday, February 24, 2014

What challenges did you meet?

This year - 2014, I have made lot of promises to myself and as a result lot of commitments towards my personal and professional life. One of those commitment it to look back in every 2 months and contemplate on the most challenging work I have done, and if there has been anything at all. 

Being developer, challenge is most certain to be a technology/programming related. Since I have never done that before (looking back in every 2 months) I am quite excited about the process and what all do I have logged in my blog after an year! Quite exciting actually.

The last two months (in fact four) I have spent most of the time devloping UI using WPF stack. Though, I did find it little hard to get comfortable with styling/animation, the task that pops out is incorporating a real time ticking charting utility at my work place. I created a custom control on top of Dev Express WPF charting tool and included properties and customization to make it MVVM friendly and included logic in viewmodel to add/remove/modify a point and redrawing the chart using binding.

Lessons learnt:
The major hurdle in a task like this is getting familiar with the API. I did skip the initial work of going through the API and jumped start with basic working code. Now I know, it was a bad idea.

I think it's worth taking initial time and effort to get familiar with the API. Even a rough sketch on paper drawing relation between the major components of API helps a lot and does saves lot of time as you progress and demand more from the API. 

Next?
Next 2 months I am planning to dedicate towards WPF automation testing.

So, what challenges did you come across in last 2 months and what do you plan/expect ahead?

Monday, January 13, 2014

WPF MVVM Threading model. Why do we care?

From my early introduction to WPF I remember having read that WPF binding system takes care of thread marshalling and there is no care required while updating a control value through a view model binding.

Have been working on server side lately and didn't got to spend enough time understanding/validating the above assertion. Like all good IT answers, the above one also has "..it depends" attached to it. And again, like most technology stuff, you get to learn "dependencies" only when you get your hands dirty.

In my latest project I am responsible for a developing a performant WPF UI with real-time updates. Not to mention the efforts I had to take to get real hang of WPF (having read WPF Unleashed 3year back did help, but not in all scenarios).

Recently, I got into a issue where UI would take 30secs at startup. And it made me shine the weapons again....

Facts:
WPF Binding system does take care of marshalling control update operation to UI thread. How?

DispatcherObject is the parent class of all WPF controls. For dependency properties of a control (when binded to a property in viewmodel), all the updates are done by using Dispatcher.BeginInvoke(action). When a property notfication event is raised in viewmodel, it is handled by the control. The control call then marshals message to UI thread to call get on the property that has been modified.

The best way to understand this would be to put a breakpoint into a binded property of viewmodel. Check the Thread.CurrentThread while in the get breakpoint. This thread would be a UI thread (and not a background thread, event if setter was called on a non-UI thread. Which means all viewmodel properties could be set on any thread (not thread agnostic!!) and the update will get marshalled to the control (even though the control is UI thread agnostic).

Where is "it depends"?
This model will not work if you have ObservableCollection/CollectionViewSource in viewmodel!
There are many queries/concerns over this issue. One of the post from StackOverFlow.

In this scenario we need to be careful about the thread that created ObservbleCollection and the thread that's adding an item in this collection (thread affinity). So, in MVVM all updates to binded properties are not safe.

Also note, since it may not be possible to do everything inside viewmodel on UI thread (eg: getting items from database, or a slow operation). An observablecollection would also demand for locking! An enumerable (ObservableCollection) can not be enumerated and modified parallely. This would need to be controlled using a lock.

Why could this be of concern? And what about UI freeze at startup?
Going one step further. How "best" to marshal a message to UI thread from viewmodel. We have following options:
Application.Current.Dispatcher.Invoke()  -- Synchronous, and is a message send (not post).
Application.Current.Dispatcher.BeginInvoke() -- Asynchronous.

Options one is what we were using in our application. Which is what was causing the delay. Because while UI thread was calling InitializeComponent of a control, a set of subscriptions (marshalled to UI thread) using Invoke were causing delay. In my case, the solution was to call BeginInvoke().

Well, not exactly. Again coming to the scenario of ObservableCollection, calling myCollection.Add(item) on UI thread with BeginInvoke is not safe!
Why? Because, it won't be safe to add an item to a collection that could be enumerated by other threads!! There could be a scenario where UI thread is adding an item into this collection, and other background thread is trying to enumerate (you might get lucky here if this collection is only used by some view using binding, and is not enumerated anywhere else. But the point is, it's won't be thread safe).

The other option to get a synschronous operation done using BeginInvoke (post message) is to call BeginInvoke and look through while dispatcher did not complete. Better yet, make use of DispatcherPriority overload and set it to low priority (say Background).

Code:
DispatcherOperation result = Application.Current.Dispatcher.BeginInvoke(action, DispatcherPriority.Background);
while ( result != DispatcherOperationStatus.Completed){
     Thread.Sleep(1000); //sleep for 1 sec.
}

In my case, this turned out to be the solution. And I think should be used for the only case (ObservableCollection) where you need to worry about thread in a viewmodel!!

Hope you find it useful!!


Sunday, May 26, 2013

C# - Value type Vs Reference Type.

While writing a usual code in day-to-day development, we often avoid the minute details (plus and minus) between the two categories of an entity in C#.

Recently read about the subtleties included in the two types and some of the compelling reasons to compare the two options before creating a new entity. Most often we adhere to creating a Reference type (Class) thinking it to be scalable, performant (What is GC for?).

Post reading "Effective C# Programming", thought to document the details and to pay more attention in order to create the right type for my needs.

Why Value type?
1) Are created on Stack, does not involve GC.
2) Value types are copied when returned from a method or property. There is no danger of exposing internal structure (internals of an object).

Why not a Value type, always?
1) Limited support for OOPs! Remember, no inheritance, no polymorphism works here. Consider all as if they were sealed.
2) If backed by interface, would cost boxing.
3) Can not define a parameter less contructor (just to mention a limitation).
4) Since, passed by value, the whole object gets copied. Thus, not suggested to have a big value type.
5) Best suited to be Immutable only. There would be complication if not immutable, any user code may try to modify it but since copies are passed, the behaviour will not be right.
Why not a Reference type, always?
1) It involves heap allocation, and that too not inline. Which means there would be separate allocations (even if I am storing those objects in an array) for each object, which would eventually cause heap fragmentation, more garbage, more indirection (in terms of dereferencing).

Suggested rule of thumb:
You create value type, if
1) Type is only for data storage,
2) Public interface defined entirely by properties.
3) This type will never have subclasses.
4) This type will never be treated polymorphically.
As a side note (on comparison).
- Reference types default to null.
- Value types default to all 0s.
- Nullable is again a value type (struct) which allows storing null. It would be interesting to find out the implementation behind.

Saturday, May 18, 2013

C# Programming - Are you making use of basic features?

It takes me by surprise to realize that peer developers (.net,C#) are writing code but not making use of some of the native/simple features that could help in writing better (re-usable, maintainable, readable, and sometimes performing ) code!!

For instance, when was the last time you have seen (or written) an operator overloading in a custom class? A class written with private access modifier? Use of native attributes like Conditional, Flags ?

It's not necessary that a code written without making use of these features is bad, but then these features exists for some good reasons! I am stating below some of such features that I have been using and "miss" while reviewing others code. I am sure you will find scenarios in your existing code where you could use these features for good reasons.


1. implicit/explicit type casting operator.
I find it really useful for POCO scenario where I don't want the users to write scattered code to create a related type from instance of my class.

2. Conditional attribute.
I find it really useful to write a helper method that only stays in DEBUG code base (and hence is not deployed to production). It gives me assurance that the code would still be good without my method and the extra functionality would do the right thing while working in a DEBUG mode.

3. Private class.
I find it really useful to wrap the internal data structure for a utility code or for a business logic in a private class. Assuring that there won't be any external dependencies on my private class and I can alter this class any time. Plus, it keeps the encapsulation logic intact.

4. Resharper
If your company doesn't has licence, then you don't have a choice. But, if you have - then you "must" learn the basic shortcuts and enable them. It's really disappointing to work with a peer on a code review and get to notice that, instead of having it installed/licensed, it's not being used at all.

5. Explicit implementation of interface.
I have only heard of this term when it comes to interviews. It is a good flexibility available while dealing with interfaces. I use this implementation when I want to make sure that all my users are only working on the underlying interface. There are various good reasons to not distribute concrete implementation in an API, and this feature makes it more controlled.

6. Int32.TryParse
I hate to see a Int32.Parse(xx) code! and I see it every now and then. This one avoids the exception and is there for a good reasons. Note: Even if the parsing is mandatory I would like to use TryParse and throw user friendly exception if the parsing fails. Invalid case exception is annoying and doesn't leaves any business reasoning behind.

7. ToString()
I am also bad at this one! But it's such a pleasure to see object details while in debug mode. Especially when the details are will thought of, as in ToString with IFormatable and only provide basic details in default format.

8. Immutable classes
Damn the feature of auto-implemented properties... I always see peers using those properties without considering the existence of a field at all (I know, we can create auto-property with private get but that doesn't leaves the underlying field as readonly). There are real good reasons to write immutable classes (most selling one is when your class acts as a key). In my case, I even prefer to write a simple POCO as a immutable (if possible) class. It's such a delight to watch a class with all readonly fields, a contructor/factory to create a full instance, and then a set of getter properties.


Saturday, May 4, 2013

Unit Testing, the gherkin way.

Importance of unit test - not going to cover in this discussion.

The article is primarily focused on importance of structuring a unit test.

In my 4 years of unit testing experience the biggest challenge I have faced is in terms of writing an "almost" production quality unit tests. It gets important because the structure and quality of unit test derives how far the unit tests would be maintained!

Historically, I have been naming a unit test method by describing the logic that uni test is going to assert. That helped, but then the test was not just doing assertion... the method was also responsible for all three A's (AAA) Arrange-Act-Assert. Which kind of resulted in coupling and went against the DRY principle. We always need the same Arrange-Act across different unit tests, which was repetitive.

Found the following simple approach to arrange unit test in one of the Pluralsight videos:


public abstract class GivenWhenThen{
      [SetUp]
      public void Init(){
             Given();
             When();
    }

    public abstract void Given();

    public virtual void When(){}
}

Then, I use the following protocol to structure my tests:
Given = Namespace
When = Class
Then = Test method.

using Given_Order_Service{
//Sample Implementation:
public class When_an_empty_order_is_placed{
            private IOrderService _orderService;
            public override void Given(){
                      _orderService = new OrderService():
            }

            public override void When(){
                     _orderService.PlaceOrder(null);
            }
         
           [Test]
           [ExpectedException(typeof(EmptyBasketException)]
           public void Then_Exception_Is_thrown_with_Empty_basket_message(){
                    //assertion..
          }

      }
}