Thursday, October 30, 2014

Session : Introduction to Universal Apps at National Institute of Business Management (NIBM) - Sri Lanka

Today Microsoft Sri Lanka has organized a full day Universal App Camp at National Institute of Business Management (NIBM), Sri Lanka. I was lucky enough to deliver a 3 hour session there about Introduction to Universal Apps. I talked about how Windows Store Apps and Windows Phone Store Apps are evolved over time and how Windows Phone 8.1 is converged with Windows 8.1. Then I gave an in depth to application states, life cycle and navigation.



I am also uploading the slide deck to OneDrive as well.



Happy Coding.

Regards,
Jaliya

Tuesday, October 21, 2014

Windows Phone Silverlight App Vs. Windows Phone App : Hardware Back Button

I am sure, most of you have heard with the release of Windows Phone 8.1, Windows Phone platform has converged with the Windows Runtime as never than before. If you take Windows Phone 8 and Windows 8, the similarities between both these platforms were around 30%. But Windows Phone 8.1 has around 90% convergence with the Windows Runtime. So basically what that means is 90% of things that you do with Windows Store Apps, you can do with Windows Phone 8.1 as well.

Windows Phone 8 has been using the Silverlight stack while new Windows Phone 8.1 will be using Windows Runtimes’ XAML stack. But if you want to continue with Silverlight, it’s still possible with Windows Phone Silverlight version of templates in Visual Studio.

image
Windows Phone Silverlight
Here in this post, what I am going to show you is, how Windows Phone is handling the Windows Phones’ hardware back button key press. It’s entirely different than in Window Phone Silverlight.

Let’s go by the example. Here I have 2 Windows Phone applications, one developed using Windows Phone Silverlight and the other developed using Windows Phone 8.1. In both applications, I have a button in the Main Page and when I click on the button, it will navigate to another page. And now what I need to test is clicking on hardware back button from the second screen from both these applications. Expected behavior is navigating back to the Main Page.

SNAGHTML5c859a48
Windows Phone App
When I run both applications, Windows Phone Silverlight application, works as expected. But Windows Phone 8.1 application is getting terminated when you click on the hardware back button from the second page. That’s because in Windows Phone Silverlight applications, hardware back button is defaultly handled by the operating system. But in Windows Phone 8.1, it’s not like that (If you take a tablet there is no hardware back button key, so there is no need to handle that in Windows Runtime. Even in future Windows Phones, it's said to be included no hardware back button, instead there will be software back button.). So unfortunately, in this case you will need to write the code for hardware back button key press.

One way is, you can handle it for application level by implementing the Windows.Phone.UI.Input.HardwareButtons.BackPressed event in the App.xaml.

In App.xaml.cs
public App()
{
    this.InitializeComponent();
    this.Suspending += this.OnSuspending;
    Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
 
void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
    Frame frame = Window.Current.Content as Frame;
    if (frame.CanGoBack)
    {
        e.Handled = true;
        frame.GoBack();
    }
}
If you want to handle it only for a specific page, you can do the following in the page level as well.

Second Page
public SecondPage()
{
    this.InitializeComponent();
}
 
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
 
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
}
 
void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
    if (Frame.CanGoBack)
    {
        e.Handled = true;
        Frame.GoBack();
    }
}
Now if you are thinking because of we have to manually handle hardware back button in Windows Phone 8.1 and since Windows Phone Silverlight handles back button automatically, Windows Phone Silverlight is good, well I don’t think so. It’s true that there are some features still which are only available in Windows Phone Silverlight and not available in Windows Phone, but Microsoft is in the process of making them available under Windows Runtime. By then it will be available for future Windows Phones. Because of this Windows Phone 8.1s’ convergence with Windows Runtime, you can develop apps for Windows Store as well as for Windows Phone having the same code base. Isn’t it just great.

I am uploading the sample code my OneDrive.


Happy Coding.

Regards,
Jaliya

Friday, October 17, 2014

Visual C# Technical Guru - September 2014

Became second in Visual C# Technical Guru Awards for the month of September, 2014.

The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
http://blogs.technet.com/b/wikininjas/archive/2014/10/16/the-microsoft-technet-guru-awards-september-2014.aspx

image
Visual C# Technical Guru – September 2014
Happy Coding.

Regards,
Jaliya

Monday, October 13, 2014

NServiceBus with ASP.NET SignalR

In this post let’s see how we can NServiceBus with ASP.NET SignalR. In detail here what I am going to do is periodically publish a event using NServiceBus. I will have a ASP.NET MVC application as my front end and there I will have a another NServiceBus client which is responsible for capturing event broadcasted by the NServiceBus publisher. Then using ASP.NET SignalR, I will be updating the UI with those captured events content.

I am not going go detail here in with the NServiceBus, as I have wrote following posts. I would  really suggest you to read these posts first, so you will have a good understanding about what I am going to do today.
As in both above posts, I have created a NServiceBus Scheduled Task in which I am going to publish a event periodically.

I will start off for today by adding a new ASP.NET MVC application to the solution.

image
New ASP.NET MVC Application
Now I am running NServiceBus.Host and Microsoft ASP.NET SignalR nuget packages on ASP.NET MVC project using Package Manager Console. NServiceBus.Host will add the EndpointConfig.cs to the project and I am keeping as it is. Now I am creating a folder named “SignalR” inside my project and I am going to add a new class there named “EventMessageHandler”.
public class EventMessageHandler : IHandleMessages<MyMessage>
{
    public void Handle(MyMessage message)
    {
 
    }
}
When NServiceBus has published an event of type “MyMessage”, “Handle” method in “EventMessageHandler” class will handle it. For now, lets keep the “Handle” method empty and let’s add a OWIN Startup class to the project by right clicking on the App_Start folder and selecting a OWIN Startup class template.

image
OWIN Startup class
Now I am modifying the created OWIN Startup class as follows.
using Owin;
using Microsoft.Owin;
using NServiceBus; 

[assembly: OwinStartup(typeof(NServiceBusSignalRSample.Startup))]
namespace NServiceBusSignalRSample
{
    public class Startup
    {
        public static IBus Bus { get; private set; }
 
        public static void Configuration(IAppBuilder app)
        {
            Bus = Configure
                    .With()
                    .DefaultBuilder()
                    .DefiningEventsAs(t => t.Namespace != null && t.Namespace.StartsWith("NServiceBusSignalRSample.Messages"))
                    .PurgeOnStartup(false)
                    .UnicastBus()
                    .LoadMessageHandlers()
                    .CreateBus()
                    .Start();
 
            app.MapSignalR();
        }
    }
}
Here I have configured my NServiceBus host and I am mapping SignalR hubs to the app builder pipeline. Next step is to create a SignalR hub. For that I am adding the following class to the previously created “SignalR” folder.
public class MyHub : Hub
{
}
Now here I am deriving “MyHub” class from “Hub” and that's it. 

Before starting off with the client side code, let’s modify the “Handle” method in “EventMessageHandler” class now to call my client sides' "addNewMessageToPage" which is not yet implemented..
public class EventMessageHandler : IHandleMessages<MyMessage>
{
    public void Handle(MyMessage message)
    {
        IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
        hubContext.Clients.All.addNewMessageToPage(message.Message, "Jaliya");
    }
}
Now I am all set with the back end code. Final thing to be done is to create a view in client side, initiate the hub connection and create a method named “addNewMessageToPage”. For that first I am modifying the “HomeController” and adding a new Action there named “SignalR”.
public ActionResult SignalR()
{
    return View();
}
Now I am right clicking on the Action and creating a new view with the same name “SignalR”. I am modifying the “SignalR” view as follows.
@{
    ViewBag.Title = "SignalR";
}
<h2>SignalR</h2>
 
<div class="container">
    <ul id="output"></ul>
</div>
 
@section scripts {
    <script src="~/Scripts/jquery.signalR-2.1.1.min.js"></script>
    <script src="~/signalr/hubs"></script>
 
    <script>
        $(function () {
            $.connection.hub.logging = true;
            $.connection.hub.start();
            var chat = $.connection.myHub;
 
            chat.client.addNewMessageToPage = function (message, name) {
                $('#output').append('<li>' + message + ' ' + name + '</li>');
            };
        });
    </script>
}
Now I am all set. One last thing to be done is to set multiple startup projects.

image
Multiple Startup Projects
Once that’s done, I am running the application.

image
Result
So that’s it. Appreciate your feedback.

I am uploading the full sample to my OneDrive.


Happy Coding.

Regards,
Jaliya

Friday, October 10, 2014

Session : Windows Runtime Apps at Information and Communication Technology Agency of Sri Lanka (ICTA)

Today delivered a session titled “Windows Runtime Apps” for Information and Communication Technology Agency of Sri Lanka (ICTA). The ICTA has organized the event for group of startup companies in Sri Lanka and Microsoft Sri Lanka was invited to carry out two sessions. I was lucky enough to deliver one session.


I have uploaded the Slide deck and the sample application to my OneDrive.



Happy Coding.

Regards,
Jaliya

Saturday, October 4, 2014

Scheduled Tasks in NServiceBus

One of the nicest things that can be done using NServiceBus is we can schedule a task or an action/lambda, to be executed repeatedly. In this post let’s see it in action in which I am going to periodically send messages from one NServiceBus to another NServiceBus host.

I will start  off with the application by creating a blank solution named “NServiceBusScheduledTaskSample”.

image
Blank Solution
For this solution, I am adding three class library projects named “NServiceBusScheduledTaskSample.Server”, “NServiceBusScheduledTaskSample.Client” and “NServiceBusScheduledTaskSample.Messages”. “NServiceBusScheduledTaskSample.Server” project is responsible for sending messages to “NServiceBusScheduledTaskSample.Client”. I am deleting default Class1.cs from all the three projects. Now I am running NServiceBus.Host nuget package on “NServiceBusScheduledTaskSample.Server” and “NServiceBusScheduledTaskSample.Client” projects using Package Manager Console.

Install on Server

image
Install on Server
Install on Client

image
Install on Client
Once Package Manager Console completed installing all the required files, you can see in both “NServiceBusScheduledTaskSample.Server” and “NServiceBusScheduledTaskSample.Client” projects, there is a new class added named “EndpointConfig”.

Now let’s move into Server Project. I am keeping the “EndpointConfig” class as it is. If you are running scheduled tasks, inherting “EndpointConfig” from AsA_Server or AsA_Publisher is a must. Because if your “EndpointConfig” inherits from AsA_Client, then the TimeoutManager is disabled and we need that to run scheduled tasks. So after keeping “EndpointConfig” as it is, I am adding a new class to the project and I am naming it as “MyTask”. I am implementing an interface named “IWantToRunWhenBusStartsAndStops” on “MyTask”.
public class MyTask : IWantToRunWhenBusStartsAndStops
{
    public IBus Bus { get; set; }

    public void Start()
    {
 
    }
 
    public void Stop()
    {
 
    }
}
Now here in “Start()”, I am planning on sending messages to my Client project. For that between the Server and Client, I need to share messages. Those messages, I am going to put in Messages Project. I am adding a new class named “MyMessage” inside Messages project. “MyMessage” is implementing “ICommand”.

There I have a single property named “Message” of type string.
using NServiceBus;

namespace NServiceBusScheduledTaskSample.Messages
{
    public class MyMessage : ICommand
    {
        public string Message { get; set; }
    }
}
After doing that, I am going to add references from both Server and Client to Messages project.

Again moving back to Server project, I am modifying the “Start()” method in “MyTask” as follows.
public void Start()
{
    Schedule.Every(TimeSpan.FromSeconds(5)).Action(() =>
    {
        Bus.Send("NServiceBusScheduledTaskSample.Client", new MyMessage()
        {
            Message = "Hello World!"
        });
        Console.WriteLine("Sent a message.");
    });
}
Schedule is a static class that can be accessed anywhere (in Version 4.x). So I am Scheduling a action in which I am doing a Bus.Send for every 5 seconds and as it’s parameters, I am passing my destination and my message to be sent.

Now inside my Client project, I am modifying the “EndpointConfig” as  follows.
public class EndpointConfig : IConfigureThisEndpoint, AsA_Client
{
}
Instead of AsA_Server, I have changed it to AsA_Client. I can keep it as AsA_Server, it will still work here.

Now I am adding a new class named “MessageReceiver”. I am implementing an interface named “IHandleMessages<T>” on “MessageReceiver”. In this case it’s “IHandleMessages<MyMessage>”.
public class MessageReceiver : IHandleMessages<MyMessage>
{
    public void Handle(MyMessage message)
    {
        Console.WriteLine(message.Message);
    }
}
Now I am all set. Now since I need to run multiple projects, I am selecting multiple startup projects.

image_thumb19
Setting Startup Projects
Now when I run the project, I am getting the following.
image
Result
I am uploading the full sample to my OneDrive.


Happy Coding.

Regards,
Jaliya