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 = ...; 
   owner.SayHelloCompleted += OwnerSayHelloCompleted;

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);
 owner.SayHelloCompleted += myHandler;
 //...then unsubscribe when ready
 owner.SayHelloCompleted -= myHandler;

Now everything comes with a price. Writing a event handler that unsubscribes itself is different now.
 EventHandler<HelloEventArgs> myHandler = null; //make it null first
 myhandler =  (sender, e) =>  //assign it later (to allow capturing the variable)
 Console.WriteLine("Somebody said hello to " + e.Content);
//...then unsubscribe when ready from inside the handler
 owner.SayHelloCompleted -= myHandler;
 owner.SayHelloCompleted += myHandler;

 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, or do it like the code above, 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. 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 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... don't touch my code.

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...

Tuesday, March 06, 2012

Using WPConnect instead of Zune for Windows Phone development

Sometimes you get so used to do something everyday that you don't appreciate how much time it saves you. So in this entry I want to go back to the basics and comment on something I had been asked many times. I remember the times where we used Active Sync to connect Windows Mobile devices, is was not that hard but it could get tricky some times, depending if the device was connected via USB or Wi-Fi, emulators via  DMA and more. And to be honest, it was not that long ago. Fortunately the new Microsoft Windows Phone 7 series does this in a pretty easy way.

Besides being used to download apps, musics, podcasts or to sync content between the computer and the device. The Zune software is what we can easily use to "hook up" your device with your Visual Studio and deploy apps to your phone.

If you are a registered developer at Microsoft Marketplace just connect your unlocked/activated phone. Run Zune if not setup to auto-start. Then on the Visual Studio just  select to run on the device rather than on the emulator.

And that's it!

The catch...
While you are using Zune you will not be able to debug code related to the MediaLibrary,  that means anything related to open photos from phone albums or photo chooser task, music files, etc. The reason seems obvious since Zune is a synchronization software so it will be using those components. Although that could work better. The solution is to use the WPConnect.exe tool that comes with your Windows Phone SDK.

This executable file is located on your SDK folder. Go to C:\Program Files(x86)\ Microsoft SDKs\Windows Phone\v7.1\Tools\WPConnect\ and there is the program. Select the x64 or x86 folder depending if your are running 32 or 64 bit OS. Then run the WPConnect.exe from that folder. My phone is named "hobbit" see the screenshot below:

Now as a side note, Zune must be closed before running WPConnect.exe but you have to run it first when you plug in your device. So the steps are:
  1. Plug in your device.
  2. Run Zune if is not setup to auto-start.
  3. Unlock your device if it has a PIN number.
  4. Close Zune
  5. Run WPConnect.exe
Think of the steps 1-3 as a "handshake" because you won't need to do it again, and that's what you do every day when using Zune to sync to your phone. If the connection drops and Visual Studio fails to deploy the app, you can just re-run WPConnect.exe and you are good to go.

When connected using WPConnect you can debug your apps even if you make use of the media library on your phone. The only downside so far is that the WP7 is still missing the wireless support for development, which is something that we did have one Active Sync, and we need mainly when  developing apps that use the accelerometer or gyroscope and need to fight with moving/tilting the phone around attached to a 6 foot USB cord.

Thursday, February 23, 2012

Nice panning and zooming in Windows Phone 7

A bit of time ago I published an app called Hidden Pics on the Microsoft Marketplace, on that entry I covered some basics on the Isolated Storage and the PhotoChooserTask for Windows Phone 7. On this entry I want to cover the zooming and panning. As part of that app, the user has the option to open a photo full size on the device screen and then pinch to zoom the photo.  They can also pan by dragging on the screen with the fingers.

Now this is supposed to be very basic, but there is a catch, which is making the zoom stable. By stable I mean that if you use two fingers to zoom in the photo, once you finish the two fingers should have the same pixels behind them, which indicates that you zoomed proportionally and panned correctly. After googling around a bit I put together the code to do both zooming and panning properly.

So here is the XAML for the control, I am using an Image control inside a Canvas with a CompositeTransform:

The photo will start fully fitted on the Image control, and in this case my app starts in portrait. Now the event is hooked for flicks (I use them to switch from one photo to the next one) and the PinchDelta and PinchStarted events are the ones we will use here. Now check the code and see how it is done.

Now notice the OrientationChanged event of the Silverlight page is here, the reason is that I want the user to be able to use the zoom and panning either in portrait or landscape mode, but for that, I do really need Width and Height of the Image control to be set. Also I check if the scale is 1 or less, then in that case the ApplicationBar is shown and the image is fit to the screen. So if the photo is not zoomed, a flick will move to the next or previous photo, but then the photo is zoomed, no menu and and flicking will just pan around the photo. See the code for the flick event:

Hope you can make use of this.

Saturday, February 18, 2012

Hidden Pics: My first App on Windows Phone marketplace

Just days ago I finished and published my first app to Microsoft Windows Phone Marketplace. As part of the "#30tolaunch" program, I must admit that waiting for  the app to be certified was a little scaring, but the app was approved without any trouble and is already up, you can grab it here.

Now the idea of the app is simple, it uses the Isolated Storage to hide pictures you want to keep out of curious people looking at your phone. And it involves two common elements that might be useful for you in future apps.

1) Isolated Storage
2) Photo Chooser Task

Isolated Storage.
The Isolated Storage is a virtualized file system so your app can't really access the device storage like it used to be. If you are a Windows Mobile developer, you might remember those times where you could write/read files all across the filesystem of a windows device. Thankfully that's not like that anymore. And you get a isolated space just for you application. Reading bytes from a file on that storage looks like this:

In a nutshell is pretty much what you do using the regular File, Directory and Stream classes in System.IO Namespace. Just that now you are reduced to work over a private space for you application and not the whole storage device.

Photo Chooser Task
Letting the user select a photo from either the media library or the camera is a very straight forward action. Paraphrasing  Chris Koenig this is an "anti-climatic" kind of stuff, because is so easy, that you have nothing to ask, and hence, you might get bored. If you remember battling with a camera in Windows Mobile 5.0 you will love this.

Just opening the photo chooser task will let the user select a picture from the media library or take one from the camera. No work with the camera is involved at all, not even with the Media Library. All you get is a file at the end of the process, no  matter if the file is new from the camera or it was selected from a user's photo album.

The overall experience
Being a developer from the times of eVB and eVC, then .NET Compact Framework with C# (which did rock, but wasn't enough) I must say the experience is great. I do miss some low-level power control with p/invoke (which is forbidden in the marketplace). Also miss control on how I could connect external devices to the phone and develop for that using COM ports. But with more sensors everyday on the phones that might not be missed.

The UI being developed with Silverlight instead of Windows Forms is a huge step forward especially on screens that auto-rotate and re-layout. This could not get easier to develop using Visual Studio. And finally the process of submitting an app to the marketplace is easy and simple.

So... just submit your app.