Session: A lap around Visual Studio 2015

Lap around VS 2015 SessionIn October, I had an opportunity to talk about Visual Studio 2015 at Microsoft Innovation Center (Karachi, PK). I talked mostly about debugging enhancements, C# 6 language enhancements, the new ASP.NET 5 ecosystem including CoreCLR, .NET execution environment (DNX) etc.

Slide deck:

If you are interested in reading about C# 6 stuff, I have written a seperate blog post around that. Playing with C# 6 features

Setting up .NET development environment on OSX

Yes we have lived to day where, this week at BUILD 2015 conference, Microsoft made few interesting announcements related to cross platform where they released a preview distribution of “.NET Core” runtime on Linux/Mac and a cross platform code editor “Visual Studio Code”. How cool is that!

In this post, I am going to setup .NET development environment on Mac. Note that I am after plain .NET core and not ASP.NET.

So let’s get started.

Prerequisite
You would need HomeBrew package manager to install .NET version manager, so if you don’t have it already installed, you can paste following script on terminal to install. Further details at

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Ref screenshot

.NET Version Manager (DNVM)
To get started, we need to setup DNVM using HomeBrew. All you need to do is to install following commands in sequence.

brew tap aspnet/dnx
brew update
brew install dnvm

Ref screenshot

Like suggested, register the command

source dnvm.sh

.NET Core DNX SDK

At this time not all tools are using .NET Core, some of them are still using Mono. Therefore we need to acquire both DNX, Mono and CoreClr. As its mentioned in documentation, mono is the default DNX, so we can acquire it by calling

dnvm upgrade -u 

Next, get the .NET Core DNX

dnvm install latest -r coreclr -u

Ref screenshot

If we now call dnvm list command, we can see the installed DNX.

Visual Studio Code
We will leverage the latest code editor announced by Microsoft. You can use any other editor you like but I am going to use VSCode for this post.

  • Install the Visual Studio Code for OSX.
  • Create a new folder in Finder at your preferred location say “HelloWorldApp”.
  • Run VSCode and open that folder inside editor

project.json

Create a new file project.json to specify dependencies/frameworks.

{
    "version": "1.0.0-*",
    "dependencies": {
    },
    "frameworks" : {
        "dnx451" : { },
        "dnxcore50" : {
            "dependencies": {
                "System.Console": "4.0.0-beta-*"
            }
        }
    }
}

Now it’s time to write code. Create a new .cs file say Main.cs and start writing C# code, you would notice you are getting intellisense, auto completion for even things like snippets but I will keep VSCode features for another blog post.

dnenv_mac_vscode_intellisense_1

dnenv_mac_vscode_intellisense_2

Run it
When you are done writing code, go back to terminal and download packages based on project.json. However one thing to highlight here is that restoring packages tool works on mono and has not moved to .net core. So in order to download packages you need to specify that you want to use mono dnx and then run the restore command.

Mac:HelloWorldApp adilmughal$ dnvm use 1.0.0-beta5-11682 -r mono
Mac:HelloWorldApp adilmughal$ dnu restore

Once you have restored the packages, run the app by switching dnx to coreclr and using run command

Mac:HelloWorldApp adilmughal$ dnvm use 1.0.0-beta5-11682 -r coreclr
Mac:HelloWorldApp adilmughal$ dnx . run
Hello .NET on Mac
For Adil's weblog

Congratulations, you just run C# code compiled by Roslyn compiler, executed by .NET Core CLR on OSX.

UPDATE: coreclr version 1.0.0-beta5-11682 has a bug where when you try to run the code, roslyn throws exception. This issue has been reported on github, as a workaround you can download and use version 1.0.0-beta5-11657 which works fine!

dnvm install 1.0.0-beta5-11657 -r coreclr -u
dnx . run

Hope this helps!

Playing with C# 6 features

C# 6 has got nothing major coming like LINQ or async/await in past instead it has got several small enhancements which actually helps you clean up your code and get ride of boilerplate code. In this post, I am going to share some of the code snippets I wrote to explore new features in C# 6.

This post is written using VS 2015 CTP6, so the actual specs may vary by the time of final release. If you want to quickly get hands on Visual Studio 2015 CTPs without setting up environment, you can create virtual machine from gallery in Azure

String interpolation:
Methods like string.Format in C# provides great functionality to construct strings using placeholders. However that approach is a bit confusing and error-prone. C# 6 introduces a new way to use variable placeholders directly in string instead of number based placeholders by placing ‘$’ symbol before the string. This makes code a lot more readable.

public static void StringInterpolationEnhancements()
{
  string name = "Adil";
  DateTime date = new DateTime(2015, 03, 13, 10, 15, 0);
  int versionYear = 2015;
            
  // Previously in C# 5
  WriteLine(string.Format("This code was written by {0} on {1} using Visual Studio {2}", name, date, versionYear));

  // In C# 6
  WriteLine(string.Format($"This code was written by {name} on {date} using Visual Studio {versionYear}"));
          
  // In fact you don't need to call string.format 
  WriteLine($"This code was written by {name} on {date} using Visual Studio {versionYear}");

  // This is especially handy when you add more parameters in string format over the time and the order get confusing
  string content = "blog";
  WriteLine(string.Format("This {3} was written by {0} on {1} using Visual Studio {2}", name, date, versionYear, content));

  WriteLine($"This {content} was written by {name} on {date} using Visual Studio {versionYear}");
}

Using static members:
A lot of time you have a class with bunch of static methods and you have to call them via class. e.g.

using static System.Console;
 
//Previously in C# 5
Console.WriteLine("This is how to use static classes");
 
// In C# 6 by adding namespace using static System.Console;
WriteLine("Just call the static method directly"); 

This was one of the feature I liked in Java and its now added in C# as well although Java don’t have many other goodies from C#.

Null propagation:
This one is interesting. Often we have methods with more statements to do null checks then actually intent of method. C# 6 introduces a new null propagation operator (?.) This would automatically check if the left hand side is not null then it uses property of that object.

public void DisplayStudent(Student student)
{
  // Previously in C# 5
  if (student != null)
  {
    WriteLine(student.Name);
  }
}

public void DisplayStudentInCSharp6(Student student)
{
  //In C# 6
  WriteLine(student?.Name);
}

If you want to work with primitive type because C# already has nullable primitives, you can write something like

int? age = student?.Age;

This is especially handy in firing events because you don’t have to do a thread safe null check

event EventHandler OnNetworkChange;
void RaiseNetworkChange()
{
    OnNetworkChange?.Invoke(this, new EventArgs());
}

However I was looking for cases when we have to add null checks before iterating on a collection but I don’t think it works in foreach statement but may be it’s good idea to check language specs or ask this question to language team. Do you know about it, reader?

// can I say something like student?.Courses?.GetEnumberable()
foreach (var course in student.Courses)
{
  WriteLine(course.Id);
}

Expression bodied members:
For method having single return statement or properties with a getter having single return statement, C#6 lets you implement a method with single expression, like we use to do define lamba expressions.

//Instead of 
public override string ToString()
{
  return string.Format("Value : {0}, value};
}

// We can define expression in C# 6
public override string ToString() => $"Value : {value}";

Dictionary Initializers:
C# 3.0 introduces concept of object intializers where you can initialize properties of object like

Student student = new Student { Name = "Adil" };

However if you want to initialize index or dictionary you have to initialize say dictionary first and set value at index in separate statement but not any more

Dictionary<string, int> dictionary = new Dictionary<string, int> {["Year"] = 2015,["Month"] = 03,["Day"] = 15 };

Other enhancements:
There are few other enhancements in the language as well.
– Getter only auto properties
– Constructor assignment for getter only properties
– Auto properties initializers
– Catching exception with filters
– await in catch/finally block
– nameof operator

public class OtherEnhancements
{
    // A getter only property with readyonly backing field
    public int DemoInt { get; }

    // An auto property intialized with default value
    public string DemoString { get; set; } = "Demo";

    public OtherEnhancements()
    {
        // Assignment in constructor for getter only field behaves like readonly field
        this.DemoInt = 100;
    }

    public void DemoMethod()
    {
        try
        {
            // Some code to capable to raise FileNotFoundException
        }
        // catch exception with filter to handle only for particular file 
        catch (System.IO.FileNotFoundException exception) when (exception.FileName == "abc.txt")
        {
            // In previous version of C#, you have to check it inside
            // and then re throw which would result in losing exception data
        }
    }
}

That’s all for this post. The complete sample for above code snippets is available at Github Gist.

Have you tried new features yet? any interesting scenario you would like to share in comments?

How we do cross platform mobile app development at Nintex

Maintaining your business presence or mobile apps on different platforms is challenging. A lot of companies hire platform specific developers, form one team for each platform which work in their own silos, each responsible to maintain their respective platform, having different implementation, different code paths and different kind of design. Each team may or may not have face similar functional/UI issues.

At Nintex, we build and ship native mobile apps across iOS, Android and Windows platforms to support access to workflows and forms securely from wherever you are on your mobile devices. Here we have followed a slightly different approach where we design and implement any feature once and then we port the implementation to other platforms. Therefore we have feature based mobile developers which design and implement each feature across Android, iOS and Windows platform.

This has work really good for us, breaking the silos and help us achieve design and code path consistency across multiple platforms.

This often lead us concluding that if we have functional bug in one platform, chances are we have that bug in other platforms as well.

The crux of the idea is that we follow Model-View-ViewModel (MVVM) pattern across all platforms. So we have similar classes for model, view and view-model, contracts, repositories, helpers etc. across Windows, iOS and Android. By similar classes I mean, similar name, code path and structure yet they are written in their own platform specific languages. So if we have a view model with a method on one platform, we will have it across all.

MVVM
MVVM

As an example, consider following sample snippet of a view model from Android and iOS and you will see the point here.

ViewModel in Android (Java)
ViewModel in Android
ViewModel in iOS (Obj-C)

However view, which comprises of UI and code, can be platform specific. e.g.
In Android, View = XML Layout + Activity
In iOS, View = Storyboard + ViewController
In Windows, View = XAML + Code behind

Each view has reference to its view model (initialized through IoC or passed by its parent) where all user interactions are done through events or binding or listeners etc. depending on platform. For instance, in iOS we leverage KVO to observe value change in ViewModel to reflect update to View/UI and stuff like button click is simply routed back to ViewModel method either via simple method call or some mechanism. So our views are just there to render UI widgets/components/layout.

The advantage of this approach is, first, it gives us shared design and code consistency, second, it gives opportunity to open a cross platform conversation and knowledge across team, third, it improve code testability by decoupling UI logic from View (ViewControllers/Activity/CodeBehind) to ViewModel, fourth, it makes relatively easy for us to follow SOLID principles.

However, we have came across challenges with platform specific components like showing alerts/notification, http clients, retrieving geolocation etc. The way we handle it is by injecting contract (interface/protocol) to ViewModel class which has platform specific implementation however code structure remains same in ViewModel across all platforms.

If you are interested to see some sample yet naive MVVM implementation:
MVVM implementation in Android
MVVM implementation in Windows Store and Windows Phone

How do you develop cross platform native apps? It would be interesting to know… is it C++ shared/wrapped code? Do you use Xamarin? You prefer each platform specific team working in their own silos?

PS: This post is revised version of my original blog post at Nintex Labs

Code and Slide Deck from YOW Connected 2014

This week I attended YOW Connected 2014, a mobile and IoT development conference in Melbourne, and also delivered a session. It was good to meet mobile developers in local community.

I delivered a talk “Write cleaner, maintainable and testable code in Android with MVVM”. I think it captured attention of some percentage of audience.

For those interested, code and slides are linked below:

and code has been pushed to GitHub

If you have any query related to talk, please feel free to contact me.

Microsoft Most Valuable Professional (MVP) Award 2014

I am pleased to share that I have been re-awarded Most Valuable Professional (MVP) by Microsoft.

Each year Microsoft recognized around 4000 individuals for their contribution in technical community such as offline events, online forums, authors, open source contributors etc. [See what it takes to become MVP]

I am truly grateful to people around me, without them I couldn’t achieve anything significant.

Key Tips to Students and Young Achievers

Few months ago, I shared some of my key tips with students at UoK to be successful in their academic and professional life. Now just to be clear I am not truly a professional coach or mentor but I am glad to share essential tips which I have learned with my experience in personal development and career.

#1 – Determination to TRY and ACHIEVE

A lot of individuals fail in the beginning. They are just not determined enough to try and achieve their goal. Your goal would be hard or at least it seems to be hard but trust me it’s doable with the courage to try.

I mentioned this point in the context of learning computer programming for students of computer science who are really afraid to accept that they can do programming and this fear stops bunch of them to try few times.

If you’re not brave enough to take the first step, then you’ll never know how far you can go.*

I would like to share my experience here, I was once an awful programmer at that time I was in high school and even when I took an optional IT course in college. I couldn’t just get it, even though I feel like I have interest in computers and machines overall. Then after I got admission in undergraduate program at University of Karachi, for first several weeks of semester I was trying to grasp what programming was all about however couldn’t really do well in writing programs and logic on my own. Until one day I picked up one of the reference book and just sit down in lab to TRY with strong feeling that I would be able do it and after spending some time I achieved the output. I still remember the output of the program

1234554321

1234    4321

123        321

12            21

1                1

Yeah it’s peanuts today but at that time it was real challenge for me! On that day the confidence that I got gave me the boost to aspire to become a software craftsman.

# 2 – Learn to LEARN

This is truly the key to success. You must get the ability to learn about anything in life. It’s not just about technology, it’s about any field. The world has changed, your learning is not going to stop once you graduate… it would just start in a new way!

In your career, especially in technology, every decade brings a drastic change in the field, at least so far. I have seen a lot of students discussing silly topics like which technology/platform to learn or one is better than other. That’s old school. You need to learn to learn any tool, technology or platform you need to achieve your what you want to do, get the in-depth understanding of how things work, learn the science or practice the art and above all be a craftsman and aspire to achieve mastery.

So invest in learning and development, make it a habit, identify the learning methodology that suits you. Eventually you will gain the confidence that you can do anything by learning about it.

#3 – EXPLORE yourself and DO what you ENJOY!

At times take some out to try out different things, explore what you like doing and settle yourself doing what you enjoy! It can be just side hobby or area with in your field, you decide!

You must not end up spending a big chunk of your day doing what you don’t enjoy!

=========

*Couldn’t find author name of quote

Java in Android is a variant of Java

Android app development uses Java platform and you can consume JDK (java development toolkit) in Android.

This above statement is partially true however the fact is that some part of Java SDK is being pulled out and packaged it in Android SDK. Second fact is that we can use Java language to consume Android SDK. However today, it is recommended to use Java 6 for Android projects. (I will come to answer that why)

Notice If you expand the android.jar you can view that it is composed of several different packages of open source libraries. So Android SDK is actually a collection of snapshot of several open source libraries at a particular time such as Java SDK/OpenJDK, Apache HttpClient, json.org, w3c dom etc. and of course the android core APIs and some of them are even uniquely modified for Android.

This all leads to an interesting question in the community I read some days ago on Reddit

Can we leverage Java 8 features in Android?

The answer is not yet.

Why? (you ask!)

Because remember we read that Android run on its own Dalvrik VM instead of Java standard VM (JVM) to convert byte code to executable.Therefore if any feature has been added in Java 8, its written to produce certain byte code by Java compiler which is then worked out by updated JVM. However that features needs to be supported in Dalvrik VM as well. Plus authors of Android needs to pull latest version of Java packages into the android.jar.

Hope this clears out confusion for some android developers!

Further readings:

  1. Java vs. Android APIs
  2. Will Android get Java 7 or 8 in a forseeable future?

Session: Code Sharing between Windows Phone/Store Apps

Today, I got opportunity to interact with developers at Microsoft Innovation Center Karachi to demonstrate code sharing between Windows Phone and Windows Store apps.

Slide deck can also be download from OneDrive

Code has been published to github code repository

Sharing Code between Windows Store/Phone Apps using MVVM and PCL

I recently published an article on CodeProject.com about how developers can share their code base across Windows Phone and Windows Store apps using Model-View-ViewModel (MVVM) pattern and Portable Class Libraries (PCL).

If you are windows developer with experience of implementing MVVM or want to implement MVVM, I would request you to read the article and I would be happy to listen to your feedback.

Sharing Code Between Windows Phone and Windows Store Apps using MVVM and PCL

Excerpt from article:

As the business wants to expand its reach to different form factors and devices, a large number of developers build native apps across different platforms. One particular scenario is when developers wants to target Windows Phone and Windows Store platform. Unlike Android, developers have to create different projects inside Visual Studio for Windows Store and Windows Phone apps.

This article explains how developers can utilize the Model-View-ViewModel (MVVM) and .NET portable class libraries to create a common shared business logic across both platforms. We would not be able to cover MVVM introduction in this article, so I expect readers would already know about it, if you don’t know what MVVM is, I would recommend to read some intro articles first on MVVM before continuing further.

The App

For the sake of simplicity and learning, we are going to create a simple contact form app on both phone and tablet, which would look something like sketch below:

The Design

The design goal here is to move all the core business model, view-models, helpers and repositories in a separate portable class library which can be referenced by UI/View projects. The connection of view with view-models would be through data binding and commands etc.

One point worth mentioning here is that helpers and repositories from PCL would further communicate with external portable libraries like e.g. Http Client to perform network operation across both platform using same PCL dll. Now in real world you may not be able to achieve this 100% but it would work in many scenarios.

Implementation

So let’s start coding! we would create a simple yet naive approach of achieving the design above. Continue reading…