Here is a little utility class I wrote a in order to convert any C# class to a string and back again. The serialzied string can be saved to disk, or sent over the network to be deserialized some where else. The usage is quite straight forward.

To serialize an object to a string do this:

string serializedData = XMLDataSerializer.SerializeToString(objectToSerialize);

and to deserialize an object to a specific type use: 

string object = DataSerializer.DeSerializeFromString<ObjectType>(serializedData ); 

Here is a unit test demonstrating:

[TestMethod]
    public void SerializeToStringTest()
    {
        var testClass = new TestClass()
        {
            testint = 12345,
            teststring = "SyntaxWarriors XML Serializer"
        };
        var dataString = DataSerializer.SerializeToString(testClass);
        var testClassDeserialized = DataSerializer.DeSerializeFromString<TestClass>(dataString);

        Assert.IsTrue(testClass.testint == testClassDeserialized.testint);
        Assert.IsTrue(testClass.teststring == testClassDeserialized.teststring);
}

This is the value of dataString in the unit test.

<TestClass>
    <testint>12345</testint>
    <teststring>SyntaxWarriors XML Serializer</teststring>
</TestClass>

And here is the class itself:

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
 
namespace SyntaxWarriors.Serializers
{
    internal static class XMLDataSerializer
    {
        public static string SerializeToString(object obj)
        {
            return SerializeToXml(obj);
        }
 
        public static T DeSerializeFromString<T>(string input)
        {
            T obj = DeserializeFromXml<T>(input);
            return obj;
        }

        private static string SerializeToXml<T>(T obj)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;
            settings.NewLineChars = Environment.NewLine;
            settings.NewLineHandling = NewLineHandling.None;
            settings.Encoding = Encoding.UTF8;
            using (var stringWriter = new StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(stringWriter, settings))
                {
                    var namespaces = new XmlSerializerNamespaces();
                    namespaces.Add(string.Empty, string.Empty);

                    var serializer = new XmlSerializer(obj.GetType());
                    serializer.Serialize(xmlWriter, obj, namespaces);
 
                    var xmlStr = stringWriter.ToString();
                    return xmlStr;
                }
            }
        }
 
        private static T DeserializeFromXml<T>(string xml)
        {
            T result;
            var ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
            using (var tr = new System.IO.StringReader(xml))
            {
                result = (T)ser.Deserialize(tr);
            }
            return result;
        }
    }
}


The live feedback is often forgotten when working with form validation. Therefore, I have made a simple web application that will present live validation feedback as the user input email & password in order to create a new account. The technologies used for this example is Bootstrap in order to create a nice looking view, and AngularJS in order to present live data & for some validation help.

The end result will look something like this:

BigImage

 

First we need to create a HTML page containing the input form needed.

The HTML page will contain the AngularJS bindings in order to present live updates but also to check validation variables in order to present the correct color.

In this example we are making use of AngularJS to do some of the validations for us:

loginForm.email.$error.required

Which will make sure that the field 'email' contains a value

 

loginForm.email.$error.email

Which is used to validate the field as an email address.

 

loginForm.email.$dirty

Which will make sure that the data has changed (meaning no initial values).

 

loginForm.email.$invalid / loginForm.email.$valid

Which determines whether the control is in a valid state.

 

What also should be noted is that ng-disabled is used in order to only activate the submit button when all of the fields are valid.

<!DOCTYPE html>
<html ng-app="validationApp">
<head>
     <title></title>
     <meta charset="utf-8" />
     <link href="Content/bootstrap.css" rel="stylesheet" />
     <link href="site.css" rel="stylesheet" />
</head>
<body>
     <form ng-controller="validationCtrl" name="loginForm">
          <div ng-cloak class="container">
               <div class="row col-xs-12">
                    <h1>Form validation with Bootstrap & AngularJS</h1>
                    <h4>Create a new account below</h4>
               </div>
               <!--Setup validation control for email-->
               <div class="row form-group" ng-class="{'has-error' : loginForm.email.$dirty && loginForm.email.$invalid, 'has-success' : loginForm.email.$dirty && !loginForm.email.$invalid}">
                    <div class="col-sm-6">
                         <input class="form-control" type="email" name="email" ng-model="email" placeholder="Email" required />
                    </div>
                    <div class="col-sm-6">
                         <span style="color:red;" ng-show="loginForm.email.$dirty && loginForm.email.$invalid">
                              <span ng-show="loginForm.email.$error.required">Email is required.</span>
                              <span ng-show="loginForm.email.$error.email">Invalid email address.</span>
                         </span>
                         <span style="color:green;" ng-show="loginForm.email.$dirty && !loginForm.email.$invalid">
                              OK
                         </span>
                    </div>
               </div>

               <!--Setup validation control for the password field-->
               <div class="row" style="margin-top:10px;">
                    <div class="form-group"
                         ng-class="{
                         'has-error' : loginForm.password.$dirty && (loginForm.password.$invalid || passwordStrength == 'too weak'),
                         'has-success' : loginForm.password.$dirty && !loginForm.password.$invalid && passwordStrength == 'good',
                         'has-warning' : loginForm.password.$dirty && !loginForm.password.$invalid && passwordStrength != 'good' && passwordStrength != 'too weak'}">
                    <div class="col-sm-6">
                         <input class="form-control" name="password" type="password" ng-model="password" placeholder="Password" required />
                    </div>
               <div class="col-sm-6">
                    <span style="color:red;" ng-show="loginForm.password.$dirty">
                         <span ng-show="loginForm.password.$error.required">Password is required.</span>
                         <span ng-show="loginForm.password.$error.required == null && passwordStrength == 'too weak'">Your password is too weak</span>
                    </span>
                    <span style="color:orange;" ng-show="loginForm.password.$dirty && !loginForm.password.$invalid && passwordStrength != 'good' && passwordStrength != 'too weak'">
                         Password is {{passwordStrength}}
                    </span>
                    <span style="color:green;" ng-show="loginForm.password.$dirty && !loginForm.password.$invalid && passwordStrength == 'good'">
                         Password is {{passwordStrength}}
                    </span>
               </div>
          </div>
     </div>

     <!--Setup validation control for the second password field-->
     <div class="row" style="margin-top:10px;">
          <div class="form-group"
               ng-class="{
               'has-error' : loginForm.passwordRepeat.$dirty && loginForm.passwordRepeat.$invalid,
               'has-success' : loginForm.passwordRepeat.$dirty && !loginForm.passwordRepeat.$invalid && passwordRepeatResult == true}">
               <div class="col-sm-6">
                    <input class="form-control" name="passwordRepeat" type="password" ng-model="passwordRepeat" placeholder="Retype password" required />
               </div>
               <div class="col-sm-6">
                    <span style="color:red;" ng-show="loginForm.passwordRepeat.$dirty">
                         <span ng-show="passwordRepeatResult == false">
                              Passwords do not match
                         </span>
                    </span>
                    <span style="color:green;" ng-show="loginForm.passwordRepeat.$dirty">
                         <span ng-show="passwordRepeatResult == true">
                              Passwords match
                         </span>
                    </span>
               </div>
          </div>
     </div>

     <!--Submit-->
     <div class="row col-xs-12" style="margin-top:10px;">
     <!--Disable submit button if input is not valid-->
          <input type="submit" value="Create account" class="btn btn-primary btn-sm"
          ng-disabled="loginForm.password.$invalid || loginForm.email.$invalid || !passwordRepeatResult || passwordStrength != 'weak'" />
     </div>
</div>
</form>
<footer>
     <script src="Scripts/jquery-1.9.1.js"></script>
     <script src="Scripts/bootstrap.js"></script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
     <script src="site.js"></script>
</footer>
</body>
</html>

 

As for the JavaScript file we have a few custom validations in order to display different results depending on the password strength.

In order for this to work efficiently, Angular watches has been created that will be notified when the model has changed.

var validationApp = angular.module('validationApp', []);

validationApp.controller('validationCtrl', ['$scope', function ($scope) {
//Validating password strength
$scope.checkPassword = function (password) {
     if (password == null) {
          return 'too weak';
     }
     if (password.length > 14 && password.match(/\d+/g) != null) {
          return 'good';
     }
     else if (password.length > 9 && password.match(/\d+/g) != null) {
          return 'pretty good';
     }
     else if (password.length > 5 && password.match(/\d+/g) != null) { //Password is 6 characters or longer
          return 'weak';
     }
     else {
          return 'too weak';
     }
}

//Check if the two passwords match
$scope.matchPassword = function (password, passwordRetype) {
     if (password != null && passwordRetype != null) {
          if (password.length > 0 && passwordRetype.length > 0 && password == passwordRetype) {
               return true;
          }
          else {
               return false;
          }
     }
     else {
          return false;
     }
}

//Setup watch on the passsword variable
$scope.$watch('password', function (newValue, oldValue) {
     $scope.passwordStrength = $scope.checkPassword(newValue);
     $scope.passwordRepeatResult = $scope.matchPassword(newValue, $scope.passwordRepeat);
});

//Setup watch on the second password variable
$scope.$watch('passwordRepeat', function (newValue, oldValue) {
     $scope.passwordRepeatResult = $scope.matchPassword($scope.password, newValue);
})
}]);

The example project can be found here:

Form validation - Source


Visual Studio 2015 Update 3 released a neat feature that enables you to fix reference errors of packages available through NuGet.

Since this feature isn't enabled by default I will walk you through the process of enabling this:

1. If you haven't already, update to Visual Studio 2015 Update 3 or later.

2. Open Visual Studio and navigate to this section:

Tools -> Options -> Text Editor -> C# -> Advanced.

Beneath the header "Using Directives" you will find "Suggest usings for types in NuGet packages" which you want to check.

SmallImage

When enabled, you will receive the following message when pressing (CTRL+.) to quick fix a reference issue:

SmallImage

I have an Angular project in which I need to interact with a CRM 2016 instance, that is, I need to create a record and open/navigate to it from within Angular.

I dont want to use the javascript SDK files because well they just seem klunky and non angular -ish.. So instead I wanted to do it with just a regular service.. Turns out it was quite easy. The hardest part was figuring out where Microsoft stored the GUID of the created record (spoiler: they stuck it in the header, more details on that here).

First off you need to add a service (or copy paste the CreateRecord method from this service to your own).

myApp.service('dataService', function ($http, $rootScope, $timeout, $q) {
    var pub = {};

    var crmAPIURL = Xrm.Page.context.getClientUrl() + "/api/data/v8.1/";

    pub.CreateRecord = function (entityName, record) {
        var url = crmAPIURL + entityName;
        return $http
        (
            {
                method: "POST",
                url: url,
                data: record,
                dataType: 'json',
                timeout: 15000
        }).then(function (data) { return data; });
    }

    return pub;
});

Now with that service method defined we can call it like this from one of our controllers:

$scope.CreateCompany = function ()
{
    // define the entity record with all the fields you want to set.
    var account = {
        name: "My Test Company",
        address1_line1: "SyntaxWarriors road 1337"
    };

    // call the service defined previously with the data and the name of the entity according to the web api
    // the entity names are listed here: https://your_organization_name.crm4.dynamics.com/api/data/v8.1/
    // in my case I wanted to create an account record which is called "accounts" (yes, the service tries to pluralize all things).
    $dataService.CreateRecord("accounts", account).then(function (data)
    {
        // this will return something like: "https://your_organization_name.crm4.dynamics.com/api/data/v8.1/accounts(59e11f14-4489-e611-80de-c4346bacbdc4)"
        // the service returns the GUID of the created record in the header.. for some unexplained annoying reason I dont know. 
        var entityUrl = data.headers("OData-EntityId");

        // do some regex to get the data in between parentheses.
        var getDataBetweenParenthesesRegex = /\(([^)]+)\)/;
        var matches = getDataBetweenParenthesesRegex.exec(entityUrl);

        // uncomment these if you want to see what you're actually getting back.
        // console.log(data)
        // console.log(matches); the guid matches

        // the second match (1) is the guid without the (). Lets open a new window to that.
        if (matches.length >= 1) {
            Xrm.Utility.openEntityForm("account", matches[1]);
        }
    });
}


BigImage

This article will briefly introduce you to SignalR, explain its advantages and get you started with a simple application.

What is SignalR?

ASP.NET SignalR adds real-time functionality to your ASP.NET applications by intelligently identifying the best underlying technique supported on the client as well as the server side on doing so. This means that by using SignalR you won’t have to learn the latest techniques on message passing real-time data as new technology come around. SignalR will simply add functionality for these new techniques meanwhile the API calls will remain the same.

On top of this, SignalR is also OpenSource and hosted on GitHub here: https://github.com/SignalR/SignalR.

Side note:

If you like the methodology of SignalR but aren’t into ASP.NET because you are more of a MEAN-stack developer or just enjoy working with Node.JS. Then you should definitely check out Socket.IO. A comparison between these libraries will be published later on.

The primary supported underlying techniques used by SignalR are the following:

HTML 5 transports

WebSocket

WebSocket is the newest and most optimal solution for sending real-time data as it supports all modern browsers and uses a full duplex solution for message passing.

Server Sent Events

A HTML 5 alternative to WebSocket. Unfortunately, Internet Explorer never adapted this technology.

Comet transports

Forever frame

Can only be used with Internet Explorer.

Ajax long polling

Ajax long polling was the natural choice before WebSocket came around. However, Ajax long polling doesn't provide near as good performance compared to WebSockets.

A more detailed view of these underlying techniques will be discussed in a later post.

Usage

While SignalR is broadly used on chat applications it has the functionality and performance for making a collaborative document writing sessions and even games http://shootr.signalr.net/.

Getting started

To get started with SignalR Microsoft has created a sample application which can be installed by following the instructions below. However, I think that this application is quite advanced to begin with and therefore I will create a simple chat application using SignalR. I would however, suggest you to install the sample application provided by Microsoft later on.

Microsoft SignalR sample

Microsoft has created a SignalR sample project that can be downloaded and installed through nuget. The project contains a fake stock market application which returns dummy data. You can download and play around with this project by creating a blank ASP.NET MVC application and then run the command:

Install-package Microsoft.AspNet.SignalR.Sample

Then follow the instructions in the 3-step process inside the readme to get the application started.

Simple chat application using bootstrap & AngularJs

The final application:

BigImage

Create a new application ASP.NET Web Application:

BigImage

Create a new empty project:

BigImage

Install SignalR using nuget:

Install-Package Microsoft.AspNet.SignalR

Create a Owin startup project and rename it to "Startup.cs":

BigImage

Open the "Startup.cs" file and insert the following which is also provided in the readme.txt:

app.MapSignalR();

This is done to enable SignalR in your application.

Then, create a new folder and name it "Hubs", then create a hub "ChatHub.cs" inside of the folder:

BigImage

Hubs are used for communicating in real-time between the server and the clients. And as described above, it is SignalR's job to provide the best underlying technology in doing so.

Here is the code for the hub:

//Class for handling all user connections
public static class UserConnections
{
//Hashset for keeping track on all unique connections
public static HashSet<string> ConnectionIds = new HashSet<string>();
}

[HubName("chatHub")]
public class ChatHub : Hub
{
//Method for broadcasting message to all connected clients
public void SendMessage(string name, string message)
{
//This will call the method on the client side containing the parameters name and message
Clients.All.broadcastMessage(name, message);
}

//Override onConnected event to keep track connected clients
public override Task OnConnected()
{
UserConnections.ConnectionIds.Add(Context.ConnectionId);
Clients.All.onClientConnected(UserConnections.ConnectionIds.Count);
return base.OnConnected();
}

//Override onDisconnected event to keep track connected clients
public override Task OnDisconnected(bool stopCalled)
{
UserConnections.ConnectionIds.Remove(Context.ConnectionId);
Clients.All.onClientDisconnected(UserConnections.ConnectionIds);
return base.OnDisconnected(stopCalled);
}
}

A few things to note:

Inside of the file, I have two classes: UserConnections and ChatHub.

UserConnections is a static class and will represent our database in this case since it is a small project.

ChatHub is our hub that will take care of all the communications between the server and clients. As you can see, this inherits from the class "Hub" to take advantage of the hub capabilities. Note that there is nothing stopping us from creating multiple hubs for one project, but seeing that this is a small project, one is good enough.

Inside of the hub I have created method called "SendMessage" which takes two parameters; name and message which represent the user who sent the message and the actual message.

What’s quite different from SignalR than most libraries are that dynamic calls are being used to call methods on the client side from the hub.

This means that "broadcastMessage" in the following line of code has to be setup on the client side:

Clients.All.broadcastMessage(name, message);

Which also means that you won’t get any intellisense on these method calls since they only exist on the client side.

Before the dynamic function call however, we specify which client should receive this message. In this case we will broadcast the message to all connected clients.

Inside of the hub we also want to keep track on the connected clients using our fake database represented as a static hash list.

This is done by overriding the OnConnected as well as the OnDisconnected method and by sending the count value to all connected clients when these events are triggered.

Moving on to the client side:

 

Install bootstrap using nuget:

Install-Package bootstrap

Create a new folder named "Views" and add a HTML-file named "Index.html":

BigImage

Provided that you have bootstrap.css in a folder named "Content" and signalR, jquery and boostrap.js in a folder named "Scripts":

Insert the following code to the file:

<!DOCTYPE html>
<html ng-app="signalrApp">
<head>
<title></title>
<meta charset="utf-8" />
<link href="../Content/bootstrap.css" rel="stylesheet" />
</head>
<body ng-controller="MainCtrl">
<div class="container">
<div class="row">
<div class="col-xs-12">
<span>Connections: {{clientCount}}</span>
</div>
</div>
<div class="row">
<div class="col-sm-2">
Name:
<input type="text" id="nameInput" ng-model="name" class="form-control" />
</div>
<div class="col-sm-8">
Message:
<input type="text" id="textInput" ng-model="text" class="form-control" />
</div>
<div class="col-sm-2">
<button style="margin-top:20px;" class="btn btn-sm" ng-click="sendMessage()">Send Message</button>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<br />
<div ng-repeat="message in messages">
<div class="col-sm-2"><b>{{message.name}}</b>:</div>
<div class="col-sm-10">{{message.text}}</div>
</div>
</div>
</div>
</div>
<footer>
<script src="../Scripts/jquery-1.9.1.min.js"></script>
<script src="../Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="/signalr/hubs"></script> <!--Will be generated by SignalR-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<script src="../Scripts/script.js"></script>
</footer>
</body>
</html>

What you should note here is the reference to the auto-generated hubs directory at the bottom. This is where SignalR will tell the client how to communicate with the hubs setup on the server. Without this reference, we wouldn't be able to do any calls to the created hub.

Now create a file named "script.js" inside of the Scripts folder:

BigImage

Insert the following:

var signalrApp = angular.module('signalrApp', []);

signalrApp.controller('MainCtrl', ['$scope', function ($scope) {
//Initialize variables
$scope.clientCount = 0;
$scope.name = '';
$scope.text = '';

//Focus name input
$('#nameInput').val('').focus();

//Array that will hold messages
$scope.messages = [];

//Declare proxy to the chat hub
$scope.chat = $.connection.chatHub;

//Create a function that will be called from the hub
$scope.chat.client.broadcastMessage = function (name, text) {
//Validate message
if (name && text) {
//push the message to the array
$scope.messages.push({ 'name': name, 'text': text });
//Update the angular scope
$scope.$apply();
}
}
//Create function that will be called from the hub when client connects
$scope.chat.client.onClientConnected = function (count) {
//Set the client count to
$scope.clientCount = count;
//Update the angular scope
$scope.$apply();
}

//Start connection
$.connection.hub.start().done(function () {
//Setup method that will be called from the UI
$scope.sendMessage = function () {
//Call the sendMessage method on the hub containing the name and text.
$scope.chat.server.sendMessage($scope.name, $scope.text);
//Reset text
$scope.text = '';
//Focus text input
$('#textInput').val('').focus();
//Update the angular scope
$scope.$apply();
}
})
}])

 

The code is quite well documented. But make sure that you understand that this method will call with the chatHub:

$scope.chat.server.sendMessage($scope.name, $scope.text);

Which will then be received and then call the client method:

$scope.chat.client.broadcastMessage = function (name, text) {

The same goes for the online count

As you have seen Angular is used to update the user interface, but since SignalR is outside of the Angular scope we will need to call the $apply() method on the scope to update the UI.

Now you should be able to create your very own ASP.NET SignalR Web Application :)

...And here is the source code:

SignalRChatApp.zip

Good luck!