Friday, January 25, 2013

Events and Multithreading


This is  the second and final part of this series. Will focus now a bit on what happen when we add multithreading to our work with events.

Cleaning Up Events and Context Information


In the previous post I mentioned some issues using lambdas and anonymous methods on events. The unsubscribe problem had a tricky "solution" by declaring a "cleanup" method inside the class that holds the event.
 
public void CleanupSubscribers()
{
    SayHelloCompleted = null;
}

The problem here is obvious since the cleanup method will remove all subscribers from the event. Hence, individually removing listeners from the event gets tricky when using lambdas/anonymous methods. So in this case the recommendations would be:
  1. Do not use lambdas if you need to unsubscribe.
  2. If you do so, use the cleanup method UNLESS your code is multithreaded. 
NOTE: this only applies to the use of lambda expressions and anonymous methods, as for regular named methods you can always remove them easily. 

Race condition, late invocation and more...


Now let's keep with multithreading, because it gets really messy. If we take a look at the previous event invocator OnSayHelloCompleted we will notice the code might seem redundant, right?

   public void OnSayHelloCompleted(HelloEventArgs e)
   {
       var handler = SayHelloCompleted;
       if (handler != null)  
             handler(this, e);
   }

Questions: why hold a reference to the event, then check for null? why not check it for null directly? The reason behind that is that multicast delegates are immutable; so adding/removing subscribers actually creates a new copy. That being said, in line 3, we hold a reference to the list of subscribers into the variable handler, so no matter if SayHelloCompleted event is modified, the local copy will keep the same value through lines 4 and 5.

So we do that to make it "thread-safe", and it worth noticing that both Visual Studio and Resharper pre-populates the invokers this way.

Problem: We can invoke a listener AFTER the the listener itself was removed form the list. WHAT?! yes,.. just like that. We remove the race condition but we get a kind of "unwanted" call problem.

The Bad Optimization


Some people think they "optimize" the code by doing this:
 
//WRONG WAY
public void OnSayHelloCompleted(HelloEventArgs e)
{
   if (SayHelloCompleted!= null)  //is not null at this time
        SayHelloCompleted(this, e); //it can be null if another thread modifies the event
}

This is a clear case of a race condition and you should avoid this.

Alternative...


A suitable alternative could be to always instantiate the event with an empty delegate. Thus, removing the need for a null check.
 
//instantiate with empty delegate
private event SayHello SayHelloCompleted = delegate { };

public void OnSayHelloCompleted(HelloEventArgs e)
{
   //no need for a null-check
   SayHelloCompleted(this, e);
}

Since the event is never accessed from the outside of the class directly, it will never be null.

Controversy: I have read many comments about people complaining that this will cause a "performance" issue, it does not. There is a performance overhead of course, but is minimal, you can do the tests and see for yourself.

Now, don't you think something like this should already be in C# 5.0? I think so...we already have async and await and all that, but events are a bit behind.(IMO) 

Friday, December 07, 2012

The lambdas, the anonymous and the events

Combining lambdas, anonymous methods and events feels natural in C#, and we use them almost as a reflex, they help us to create closures and avoid creating state variables outside the scope of our methods or passing extra state data through event calls.

But one thing that come with events is the fact that writing good applications implies making good use of the resources, meaning we have to dispose those we no longer need. When using events with lambdas and anonymous methods, is possible to forget about that, thus writing code that is not efficient and prone to crashes. Will start this 2-part series talking about the subscribe/unsubscribe behavior.

Subscribe/Unsubscribe lambdas and anonymous methods

Let's begin with a basic scenario using events in a single-thread context for now; just to keep it simple. The code fragment below contains the HelloEventArgs implementation as well as the publisher class MyClassWithEvents.

 
    public class HelloEventArgs:EventArgs
    {
        public string Content { get; private set; }

        public HelloEventArgs(string content)
        {
            this.Content = content;
        }

    }

    public class MyClassWithEvents
    {
        public event EventHandler<HelloEventArgs> SayHelloCompleted;

        public void OnSayHelloCompleted(HelloEventArgs e)
        {
            var handler = SayHelloCompleted;
            if (handler != null) handler(this, e);
        }


        public void SayHello(string s)
        {
            Console.WriteLine("Hello " + s);
            OnSayHelloCompleted(new HelloEventArgs(s));
        }
    }


I know I can make EventArgs generic as well, but that's not the point of this entry. Now... how do we subscribe to - and use - the event? Well the traditional way is just using a method and the "+=" operator.
 
   
   MyClassWithEvents owner = ...; 
   //subscribe
   owner.SayHelloCompleted += OwnerSayHelloCompleted;
   //invoke
   owner.SayHello("mike");
}

static void OwnerSayHelloCompleted(object sender, HelloEventArgs e)
{
    Console.WriteLine("Somebody said hello to " + e.Content);
} 

Of course we can always use an anonymous method or a lambda expression, that we got since C# 3.0, and go like this:
 
 owner.SayHelloCompleted += 
   (sender, e) =>  Console.WriteLine("Somebody said hello to " + e.Content);

Lambdas and anonymous methods help us to code in a cleaner way, especially when it comes to introduce closures, so we don't have to be messing around passing state information. The compiler wraps that up for us. Writing lambdas feels good, it looks good, but it might not always be such a good idea. Why? well, while we can unsubscribe a method from a multicast delegateby solely using he -= operator, we can't do such thing when using anonymous methods and lambdas; even when the compiler will allow you to do something like this:

 
  //notice the -= operator!!, this will compile but not work as expected
  owner.SayHelloCompleted -= 
    (sender, e) =>  Console.WriteLine("Somebody said hello to " + e.Content);

You must know that per C# specification, two anonymous methods or lambdas with the same code might not generate the same code, also in fact, it won't reference the same object in memory. The workaround is simple, if you feel the need to use lambdas (maybe because you need closures and a cleaner-looking code) you must store the reference to the expression or delegate.

 
 EventHandler<HelloEventArgs> myHandler = //store a reference
       (sender, e) => Console.WriteLine("Somebody said hello to " + e.Content);
 //subscribe
 owner.SayHelloCompleted += myHandler;
 owner.SayHello("mike");
 //...then unsubscribe when ready
 owner.SayHelloCompleted -= myHandler;

Now everything comes with a price. This implies you can not write a handler (using anonymous methods or lambdas) that unsubscribes itself after being called (And yes, you might  need to do it). It also moves the problem of the shared state data to a new one: you have to hold a reference to the method and keep it, which is the opposite we want if we are already using this model because of the prettiness of closures. And it becomes painful when multithreading is involved.

Microsoft recommendation in this matter is pretty clear, you should avoid using lambdas and anonymous method on events if you need to unsubscribe at a later time. And the word "need" here is the whole key. Just be careful when using lambdas on events. If you don't unsubscribe from an event and keep references to variables outside the scope, the Garbage Collector won't be able to clean up that after you.

A weird tip is to create a "cleanup" method, that assigns null to the event variable from inside the class that holds the event (since the event wont be directly accessible from the outside) and thus, removing all subscribers (no selective procedure here, is all or nothing). 
 
 public void CleanupSubscribers()
 {
     SayHelloCompleted = null;
 }

Is not the prettiest thing, but it might be of use in many scenarios and will definitely do the cleanup.Of course is up to you to perform the cleaning, so be careful. Another problem with this extreme approach is that in a multithreading environment is almost useless. Care to see why?

Will see more on that on the next entry!






Monday, October 22, 2012

Windows Phone vs iOS Development (with C#): Round One

DISCLAIMER: This is not about iPhone vs WP7 devices; its about development tools. If you think you can enter into a device fight here, or you like to listen to Justin Bieber, you should leave the page now.

I like programming, and that's it. Well...no. I LOVE programming. No matter the platform, OS, framework or  language; I find that programming is a rewarding experience. Of course as with anything in life, you want that experience to be as smooth as possible. And that's why I am so picky with development tools... They are supposed to make my work easier. And this entry is about that, comparing the development tools used to create apps for iOS (iPhone) and Windows Phone.

Recently I had the opportunity to develop the same mobile app for two platforms: Windows Phone and iOS. While I have developed for these platforms before, I rarely have coded the same app (and a complex one) for the two of them. And this is a good chance to perform a comparison, because it gives me a fair point of view, rather than comparing experience by running some code fragments, or reading some biased blogs (I will try not to be...).

The environments


I am a .NET Developer, and I prefer C# over objective-c anytime (we can have a fight about that later). So I decided to use MonoTouch for the iPhone, this also helped me reuse a lot of source code between the two apps. Essentially anything except GUI related code could be reused.



Used configurations


Round One....


1. Integration of tools


Here it gets a bit cumbersome on the iPhone side for a C# developer, not only I need MonoTouch - so I can build with C# to iOS - but I also have to play with a combination of two IDEs: MonoDevelop and Xcode. Fortunately, they work pretty good. Xcode is used for designing and connecting outlets, etc. Some minor drawbacks with resources in the solution, like adding an image from the designer, but nothing that would make your work impossible.

However, the full environment for development in Visual Studio is much more seamless.

Verdict: WP++

2. Performance/Responsiveness 


Both environments perform in a similar way, no long waits or bottlenecks or freezes, even the small MacBook Air, performed great if you consider it was almost half of anything the PC was. I did experience some minor issues (crashes) with Xcode, but after an update, everything was OK.

Verdict: iPhone++

3. Development Costs


Developing for both platforms require a license that cost 99/year. Using MonoTouch is free if you will only use the emulator, but in order to connect to a real device (which is a *must*) you require a paid license. Both MonoDevelop and Xcode are free. But again, you require a Mac computer. And in the case of Visual Studio the WP SDK is free, but of course, you need Visual Studio (and Windows).

Both costs should be considered similar, even considering Apple's hardware is usually more expensive than the regular PC equivalent. 

Verdict: tied

4. Connecting to the device


This is an aspect where iPhone wins, I never had a problem just plugging in the an iPhone to the laptop, and run the Solution in MonoDevelop to deploy it to the device. It is simple. (Although it did required some initial work with certificates, etc. But that's a one-time only thing)

In the WP side every time I plug the device  I have to run Zune or use wpconnect.exe (I wrote about it already here). It became upsetting after you have to run several tests walking around with the device. Also you can't debug when connected through Zune if you are using the camera...

Verdict: iPhone++

5. The IDEs


Here is another tricky comparison, since I am using Xcode as an aid to edit XIB files, and MonoDevelop to edit the C# files, however, we must admit, neither Xcode nor MonoDevelop are mature enough in comparison to Visual Studio. Designing with Xcode is clumsy at best when compared to Visual Studio (and I am not even including Expression Blend here to make it fairer).

Verdict: WP++

6. The emulator


And here is worst part on the iPhone development. The emulator for the iOS is terrible, still better than the ones for Android - have to admit that - but is an awful emulator. Just to mention some problems:
  1. File system case sensitiveness differs from the real device
  2. No Camera 
  3. GPS emulation tricky to use
  4. No Accelerometer 
The Windows Phone emulator is a clear winner here, as it provides all of the above and also performs way better.

Accelerometer with WP Emulator


GPS on WP Emulator

The ability to emulate the accelerometer and GPS sensors on the WP greatly helps development by reducing the amount of time dedicated to test on the device. We can actually do a lot of more work with the emulator itself  before going into the field to test with real live data.

Verdict: WP++

Summing up.


So far, after this first round, the development tools' fight is like this:

iPhone: 2    Windows Phone: 3

Will come again soon, with more on Round Two... debugging, designing, execution performance, benchmarks, networking, error recovery and more.





Sunday, August 26, 2012

New app and updates

Crazy cars, the new game

Recently added a new game to my list of apps for Microsoft Windows Phone, a game, and is called "Crazy cars" can be downloaded here. The game have been download thousands of times and very short time!

Check out the new UI created in Silverlight.




Hidden Pics
The app for hiding photos on you phone also get a new UI, more styled design and several bug fixes. Check out the new look.


New updates are coming for this app, including encrypted photo sharing, fake passwords, bogus tiles and more.

Saturday, June 02, 2012

The Loan Calculator App

Few days ago I added a new App to my inventory on Windows Phone Marketplace. The Loan Calculator app was just something I needed when I was in a hunt for a car (still am). The thing is I wanted to keep it simple. Just input the numbers and see the total, how much, for how long, you know.. just the FINAL number. Which is what car dealers will never give upfront, because they always play that 101 psychology thing on you.

So I built this app using the common formula that you can see around in many websites. The idea is pretty simple, just input the data and get the total final price and the monthly installments. As an extra you can also see how the amortization for the loan plays along time.

Check it out, assume we want to calculate the final price for a car that cost 25k, we will put a  10% down payment, 2.5k, with an APR of 3.0%, and with a loan term of 3 years. Just enter the data and hit "Calculate"

Then we just get the summary result with the final cost, see that in total we are paying $26,055.78 for the car. And I don't know you, but that's what I really care. The monthly installments are of $654.33, you can also see that in total you will pay $1,055.78 of interest on the car.

On the details tab we get the amortization for the monthly payments. So you can see how much goes to interest and how much to the principal.

The formula is this one:

The only catch is that the "rate" is our APR divided by 1200, so here is the c# code to get the monthly installments based on the formula above.
 var rate = interest/1200;
 var monthly = rate > 0 ? ((rate + rate / (Math.Pow(1 + rate, months) - 1)) * principal) : principal / months

Now, we have to pay interest every month, and is based on what we still owe, so applying that to the monthly installments we can get the amortization for every month.The C# code is as follows:
 public void MonthlyDetails(double carPrice, double interest, double downPayment, int months, double monthly)
        {
            var endingBalance = carPrice - downPayment;
            var rate = interest/1200.0;
            var count = 1;
            while (count <= months)
            {
                var interestPaid = endingBalance*rate;
                var principlePaid = monthly - interestPaid;
                endingBalance -= principlePaid;
                CreateRow(count, String.Format("{0:C}", interestPaid), String.Format("{0:C}",
                           principlePaid),String.Format("{0:C}", endingBalance), count++);
            }
        }

Where "CreateRow" is a method that add the data do the grid on the screen.
Hope you like it!

Monday, May 14, 2012

When somebody changes my code...

Well, initially I might get upset, but only if they break something. But here I am not talking a team member changing your code... No... that's OK

This blog entry is about that 'non-deterministic' behavior that sometimes happens to 'us' while developing software and all of the sudden something does not work as it 'should' be. Who does not hate that kind of bugs right? This example is a real case scenario using Telerik components in a web application.

Consider the following piece of ASPX code, I have placed a button and a label, the button 's click event in code-behind event will change the value of the label.

Pretty simple right? Just a button with a javascript confirmation dialog before performing the page's post back. Now lets 'ajaxify' this...

Using the new ajaxified code now have pretty much same effect, except we are not performing a full page post back, but only updating elements inside the UpdatePanel control. But what if I have a page already with lot of telerik stuff? I wont be using the classic asp.net controls, I will use the Telerik stuff.. now lets do it with Telerik !

What a surprise, It will *not* work.... however... it should... why is it failing then? In order to figure out that, let's check the HTML code rendered by the ASP.NET page where we used the Telerik components.

Wow.... my javascript has changed... and it has the "do postback" call after it! But I didn't do that right? That's not a new behavior, postback codes are changed a lot in .NET, but for my experience, whenever ASP.NET or anything change that code, it always works...

Fortunately is easy to fix, just a small change; instead of return confirm('are you sure?'); I just changed that line of code to: if (confirm('are you sure?')) That way it will generate a complete condition that will do the postback after the confirmation.

Don't get me wrong, I like Telerik a lot, and I used their components a lot... but.. you know...



Saturday, March 10, 2012

Two notes on Mixed security warnings

When deploying and testing websites that use secure connections (SSL)  we might get warnings about non secure content on the page. This is usually an easy thing to fix. Just find a tool like "Fiddler" and find out what traffic is going over a regular HTTP (non secure) channel.

Sometimes even a simple FIND over the code will let you find those "unsecured" elements. But that's not enough if you refer some javascript or refer a link over SSL that then does some non-SSL redirection.

 Each browser has a similar way to show you how secure you are on a website. Google Chrome shows website security indicators (icons) that will appear next to your site URL in the toolbar.



The first one (1) is just a regular site with no SSL, and we want number (2) the green one, you should avoid the other ones. Now two notes on that.

Google Ads
Don't use Google Adsense on your website if you use SSL and you care about your site not showing any warning, the ads will be functional, but they cause your site to display the fourth (4) indicator.

And that won't look very professional. It will give the impression that the certificate is not valid or that the user is at risk on your site, even when might be not true, because "you" the developer knows that is just an Ad, the user is not a developer. So avoid this.

Note: even if the ads are only in one page, once the browser hits that page, will show the warning, and even if you navigate away from that one, and go to other pages on the site without ads, it will still show the warning. 

Silverlight "medallion"
There is nothing wrong with Silverlight itself when it comes to security, however, the default code you place on a page when adding a Silverlight element, contains a link to Microsoft that will later redirect a non secure URL. The content on that URL is an image. Is the "Download and Install Silverlight" image.

In this case the warning from the browser is the number three (3), while is not critical, is not good enough. The line causing the problem is this one:

Don't bother changing the source of the image from http to httpS, it won't work. Instead, just download the image and host it yourself with your site.

Now the site won't show any warnings on any browser. Of course the Silverlight medallion will be the one you downloaded and not decided by Microsoft based on the culture. But security goes first...