Implementing Model-View-ViewModel (MVVM) in Windows Phone

Model-View-ViewModel (MVVM) is a solid presentation model and the best benefit of this design is that it lets you decouple UI and logic which makes you unit test your logic easily. You will find a lot of stuff over the internet about MVVM but I am going to quickly introduce you using a diagram:

Source: Implementing MVVM (Microsoft Patterns & Practices)

The View in case of Windows Phone is the UI page (.xaml) and code behind (.cs/.vb). Model is plain data model. ViewModel contains presentation logic which may encapsulates models, have some logic around it, interact with repositories etc. View and ViewModel are connected via Binding or Commands etc. I will cover those as we code it.

In this post, I am going to share a very naive way of implementing MVVM to develop your apps on Windows Phone but more or less we can implement MVVM same way to develop Windows Store apps. In fact in my upcoming post I would love to write about how we can share code between Windows Phone and Windows Store apps by implementing MVVM + Portable Libraries + Dependency Injection.

Microsoft XAML based solutions supports MVVM as most of basic components required to implement MVVM are baked in as part of framework e.g. DataContext and Binding, INotifyPropertyChanged, Commands etc. I will get back to these terms as we go through code.

So here is something we are going to develop. A simple app with contact page allow user to fill in name, email, select a category, add details to it and submit it. We would add some basic validation here as well.

Contact Form Sketch

So let’s jump to code and start learning MVVM by writing code.

We will start by creating model first. I am gonna add a Category class which we would use to create a collection to populate categories.

Now there are couple of things here that needs explanation. INotifyPropertyChanged and OnPropertyChanged being called in setters. INotifyPropertyChanged is an interface that ships with framework and the class implements it is able to notify their view/clients that a property value has changed. So once we bind our view with ViewModel/Model then we need a mechanism to inform View/UI that a value has been updated. What happens is that when we change value of a property in model it send raises property change event, which is why we are calling “OnPropertyChanged” method, to let view know that a property value has change and therefore please update your UI. And that’s the major purpose of INotifyPropertyChanged interface and we need to implement it in all Models or ViewModels which we intend to bind.

Now let’s create a view model. ViewModels are usually one per view, page in this case. So we are going to create ContactPageViewModel

We have an ObservableCollection<Category> which we would use to populate category list. The ObservableCollection is part of framework and it automatically notifies UI when an item has been added, deleted etc. We also have another property “SelectedCategory” which we would use to populate the selected property by the user. We have Name/Email for user data, Inquiry string for details and IsValid property that we would use for required validation.

Let’s talk about view now. Now here is a part that is kind of easier on Windows Platform such as Windows Store and Windows Phone in contrast to Android and iOS.

So binding a property of control is simple we use special XAML syntax “{Binding PropertyName, Mode = OneWay/TwoWay/OneTime}”. The mode here specify that whether binding would be one way i.e. from Model -> UI or TwoWay i.e. UI -> Model and vice versa. The other important thing to notice is Command. Commands are way to connect view events with ViewModel. In this case, we have registered submit button with SubmitCommand on ViewModel which would eventually call OnSubmit action.

BUT the potential of MVVM can be observed with how validation is handled. What I have done is that submit button will only be enable when IsValid property is true. And who is updating IsValid property? RequiredFieldValidator.
That’s why we have registered TextChanged event in UI which triggers source to update on every key stroke which update the ViewModel property which internally raises PropertyChanged event and that event is being handled by validator which sets IsValid to true all required fields are being populated.

And you just made a simple implementation of MVVM on Windows Phone. Please note that the above code is not production optimized. Also there are different ways to implement MVVM and this is just one way to do it. Also MVVM may not fit to very simple 1-2 pages app however the more complex the app the more likely it is that MVVM is the right fit for your app.

Sample code can be forked or downloaded from Github: https://github.com/adilmughal/DemoMvvm.WP

Year 2013

Yesterday marks the end of year 2013, wasn’t it very fast? As the year ends, its time to post a short note on how the year has been.

Overall I see 2013 as change in professional life. After 4+ years of serving, I left my job and thank Telenor for the good time, then I relocated to Australia to join Nintex Mobile team. So as of now in my daily work life, I am enjoying developing mobile application across all major platforms. And we really do one user story on say Windows RT or Phone and other on iOS, which initially feels like crazy and some big time learning stuff.

Apart from professional life, I was awarded “Most Valuable Professional (MVP)” for the fifth consecutive time by Microsoft. Delivered few talks on web development, participated in Imagine Cup evaluation, traveled to US to attend MVP Summit 2013. Plus I finally manage to migrate my blog from blogger to WordPress hosted on virtual machine on Windows Azure.

Personally, we as family are exploring another city Melbourne, Australia and trying to settle here for a while. We definitely miss our friends and family back in home town but Melbourne is a good place to live in and we have an opportunity to make new friends here.

Last but not least the year end with shocking and sad news as one ex-colleague of mine “Anwer Baig” died suddenly. We used to work together at Telenor. He was really a lively person and used to enjoy outdoor activities like hiking, football etc. Whatever your faith is, please take out few moments to pray for his soul. May he rest in peace and blessed with place in heaven (ameen).

So this was my 2013 and I thank God for his blessings. How was yours?

I wish you, dear reader, a very happy, healthy, prosperous and peaceful 2014.

A new focus on mobile development

Since last 5 years of my career, I have been mainly working on web application development in particularly using .NET technology stack and also mainly blogging on ASP.NET, client side libraries, C# and developing a small open source projects on GitHub as well.

I do really enjoy working web because of web working model and it’s fast paced in terms of improvement plus web development tools have improved over the time, one way to realize fast paced web is by considering that Firefox has released more than 15 version in last few years… just joking. So yeah this leads to me categorizing myself as server side programmer.

Source Flickr!

In 2012, I got the opportunity to work on mobile app development on Android and I really like going through app development paradigm along with the challenges associated with it. In fact I so liked it that I switched my employer in another country to work full time in mobile product development team as developer working across major platforms iOS, Windows etc.

So what attracts me to mobile apps development?

First, mobile development is one of the “trending” thing in software industry. It’s booming, evolving and I strongly believe that smartphones in enterprises and in many other areas of life are yet to be leverage to their full potential.

Second, mobile development has got interesting challenges. If you have been working on server-side you take many things for granted so things like computing capacity, memory, batteries/power, network connectivity failures, metered networks are some of things to be taken care of in any good mobile app.

Third, availability of your app on different platform. For example in web, the challenge is to have a cross browser complaint responsive design of your website however on mobile to cover a good market you need to have your presence on more than one platform and they might be totally different technically. So for someone who love learning new technologies, this is promising.

So here I am heads down learning with a new focus on mobile apps development.

Source Flickr

Moving WordPress Blog to Custom VM hosted on Windows Azure

Some months ago I migrated my blog from blogger to self hosted WordPress on Windows Azure. My initial experience was good, having a website hosted on azure standard instance with MySQL database somewhere in cloud. All good, I started doing some WordPress optimization.

One day I got an alert from “ClearDB” that my database storage is about to reach limit and then I realized that MySQL database for my blog was actually hosted by ClearDB which by default gives you only 20 MB free space plus with the option to get 1 GB for $9.99 per month. So they expect me to pay for both website hosted on Azure and then MySQL database as well. Yes as MSDN subscriber I do get $150 credit for Azure but I don’t want to waste them plus pay an additional amount to ClearDB. This does not make sense to me as I can get complete WordPress hosting on $9-$13 per month, why would I pay 9 dollars just for database 😐

I also cleaned up DB to reduce its size by removing revisions, spasms etc. but I kept getting the annoying alerts from ClearDB. Therefore I decided to get rid of this model and create my custom VM to host WordPress website with MySQL database.

I end up creating a Ubuntu virtual machine on Windows Azure (yes we are fortunate to see this day) and thereby creating a complete LAMP environment. I followed an article “How to setup rock solid VM on Windows Azure for your WordPress blog” and it worked smoothly. So I mapped the domain to this new VM and satisfied so far.

Another benefit I see of having custom VM is that you can save the snapshot as backup or later host it somewhere else as well.

How is your experience of hosting blog, dear reader?

Tips to Optimize WordPress on Azure

Few months ago, I moved my blog to WordPress on Azure. I am not a WordPress expert, not even near to it but as hosting is charged or free for limited configuration, it is better to optimize and leverage the current resources first before scaling out on cloud.

So I would like to share few tips based on my experience. Just a bit background, I mostly blog for technical stuff so I used a lot of images and code snippets to transfer my message.

1. Utilize free online storage for Images

Content like images can take relatively large percentage of your space and bandwidth. Instead of adding media to WordPress, try utilizing online service like Flickr, DropBox, SkyDrive etc. They provide sufficient free storage to start with and reduce your site storage space and bandwidth as well. Simply add images by linking URL in your blog posts. The only issue is that it might be a bit tedious to upload elsewhere and then embedding the URL but I believe you can come up with smart way to do this like using a client application to upload content online.

2. ClearDB database size near quota limit

So when you host WordPress on Azure, the MySql database is hosted to a Azure partner i.e. ClearDB. It’s a bit weird and I was surprised to see a sudden email from ClearDB that my database size is near quota limit. First of all I never knew that my blog database was hosted their and then I didn’t know about the limit earlier and ClearDB apparently offer 9.99/month for just 1 GB and 49.99/month for just 5 GB. Makes me thing are we living in 2013 or 2003, well I don’t blame them but giants like Google, Microsoft, Yahoo, DropBox has raised the bar high for me in terms of storage.

Anyways, my 2 cents here are that before upgrading to any paid package, try installing WordPress Database optimization plugins. I tried a plugin ‘Optimize Database‘. It basically remove revisions, spams etc. Worked really well, saved more than 50% storage for my poor 20 MB free database storage.

3. Use GitHub Gist to share code

Code snippets for any programming language requires a little more attention then just text. You may have to format it well like code are formatted in development environments and you may need to update it over time. I have started using Github Gist.

Gist is a simple way to share snippets and pastes with others. All gists are Git repositories, so they are automatically versioned, forkable and usable from Git.

4. Leverage Caching

Caching can prove to be really handy for performance and saving bandwidth, provided it is properly configured. On WordPress, I have installed a plugin “W3 Total Cache“, have started using it yet I am still exploring its configuration. It looks promising though. Comes with features like page caching, HTML/JS/CSS minify, database caching, browser caching etc. Highly recommended.

Well those were some tips from my end for optimize hosting, what are yours?

My Experience of Migrating blog from Blogger to WordPress on Azure

You may have noticed the new look of my blog with a bit difference in URLs, as I have migrated from Blogger to WordPress that is hosted on IIS deployed on Microsoft Windows Azure.

Objectives:

  • Migrate all posts from Blogger to WordPress
  • Don’t end up with broken links for blog posts
  • New home page, simple and improved responsive layout
  • Update DNS settings to set adilmughal.com to new site

Migrating Earlier Blog Posts

After creating a new WordPress site from Websites gallery in Windows Azure Portal, migrating earlier posts was very easy and straight forward, a tool comes out of box with WordPress, just utilize the tools to import blogger post and comments on WordPress

There is a great tutorial on how to create a WordPress website on Azure in few clicks

Dealing with Broken Links

First, I wanted to move all my blog post with URL like {domain}/blog/{year}/{month}/{title} which is not really default in WordPress, however you can set it under Settings -> Permalinks. The thing I was worried about is that earlier my URL were of scheme {domain}/{year}/{month}/{title}.html and I don’t want to break any URL previously linked blog post. So for this I need to create a custom structure under Permalinks.

However, after setting custom structure, you would end up in URL like:

http://www.adilmughal.com/index.php/blog/2013/02/asp-net-mvc-4-redirects-incorrect-login-url-login-aspx/

To kick out index.php, you need to do some URL rewriting in your web.config, if hosted on IIS. This is pretty much explained in an article “Enabling Pretty Permalinks in WordPress“. Also refer to gist, code snippet, below containing “Main Rule”.

Second, blogger has convention of url scheme ending with .html. I want to get rid of .html but at the same time if I don’t want to break any previous linked blog post. For instance, a blog post link

www.adilmughal.com/2013/02/restoring-nuget-packages-for-external-dependencies.html

should take me to new URL

http://www.adilmughal.com/blog/2013/02/restoring-nuget-packages-for-external-dependencies/

Therefore I have to add another rewrite rule. “Remove html” rule demonstrates the same in gist below:

It took a little time to figure this out but I believe that was the most important thing. Another thing I want to preserve was social media interaction like Facebook Likes, Tweeted etc. But that is something I was not able to achieve that as such they don’t work on redirection… however what matter most was done.

Home Page and Improved Layout

Previously my home page was merely list of posts, I wanted to add a new home page with a good snapshot of everything like recent blog post, recent talks etc… and that was one of the reason I went for a separate /blog link setting. WordPress and a custom theme gives me flexibility of adding a static page with as home page. I would like to dive deep into the PHP thing to make most of it, but that’s a thing to do later.

DNS Settings

Well that was a bit tricky for me. For DNS settings, first you need to set A (Host) and CNAME (Alias) with Host @ pointing to your IP of server on Azure.

You can find the IP of your server in “Manage Domain” under “Configure” section of your Web site on Windows Azure Management Portal

Second, you need to add CNAME entries to awverify.{website_name}.azurewebsites.net as screenshot depicts below:

Then all you have to do is to add your domain name in “Manage Domain” section

and that’s it. I am done! Enjoy reading my new blog and feel free to provide any feedback. If you are already hosting your blog/site somewhere else, try hosting it on Azure, it has it’s own benefits.

New Employer, New Country, Another Change

Though 2012 proved to be a year of change for me, I am ready to take another leap of relocating to new country to avail the opportunity to be part of Nintex product development team.

For those of you working on SharePoint server probably know about Nintex, their Nintex workflow is famous third party tool utilized in SharePoint to develop custom workflows easily.

Nintex Banner

Nintex is the world’s leading SharePoint workflow company, with over 5000 customers in 90 countries serviced by a global network of high quality partners and service providers. Nintex delivers innovative software and cloud services that empower organizations to automate business processes, quickly and easily. Read more about Nintex here.

I will be joining their Nintex Mobile team in Melbourne, Australia office.

I believe this would be an interesting move yet challenging since it involves relocation as well. Switching employer and relocating together is really shaking up your life, both personally and professionally. However Nintex is a kind of company I was looking to switch after Telenor, it’s a computer-software product based company, following agile practices, and in touch with latest tools/technology.

I truly hope to have a great time and get good exposure, learning and growth at Nintex, starting soon!

P.S. I have posted about leaving my previous employment in recent post “Thanks for the good time Telenor“.

Thanks for the good time Telenor

This post is a short note to say THANK YOU to my colleagues, now ex-colleagues, for the good time we had in last 4 years at Telenor Pakistan, as you might already know, dear reader, that I have just left Telenor Pakistan.
Overall I enjoyed working in Telenor and if I look back I see some good legacy of my contributions in Human Resource Management System, Payroll, Telcom Value Added Services, Mobile Apps etc. I learned a lot about software engineering in particularly web development and challenges of large enterprise.
Beside work, I am leaving with remarkable memories of fun time we had.
And I got plenty of opportunity to present in front of co-workers, at times forcefully 😉
I wish Telenor Pakistan a bright and successful time ahead.
So thank you to every single one of you who have worked with me and helped me throughout my time at Telenor Pakistan and special thanks to leaders around me who believed in my potential and have invested time/resources for providing me significant exposure, education and experience.
Please stay in touch, follow your dreams, do what you are passionate for, go for continuous improvement and above all enjoy your life!

P.S. I will talk about my next employer in upcoming post.

 

Awarded Microsoft Most Valuable Professional 2013

Super excited to share that I have been recognized as Most Valuable Professional (MVP) by Microsoft for the consecutive fifth year. This time I have been awarded in ASP.NET/IIS space with technical interest in Client App Dev, Windows Azure and C#.

Special thanks to our MVP Lead Hande, DPE Lead Tahir Masood, my wife and above all my parents for their outstanding support.

Glad to be part of The Official Microsoft MVP Community. You can see my profile on MVP site .

Where is Windows 8 Store App Suspend Resume Shutdown Option in Visual Studio 2012 Ultimate?

If you have been developing Windows 8 apps using Visual Studio 2012 Express and recently started working on Visual Studio 2012 Ultimate, it might take you few minutes to figure out where is “Suspend”, “Resume”, and “Suspend and Shutdown” option during debugging. 

Because you may know that Visual Studio is a huge product and each express version is tailored as per its usage. So default toolbar of VS ultimate does not include this option enabled.
So all you have to do is to select “Debug Location” under View -> Toolbar -> Debug Location. 

That’s it. Now you can see the “Suspend” etc. option in toolbar. 

Just thought to share this small thing as it took my couple of minutes to figure this out.