28 December 2015

Learn AngularJS in one day

Found a nice website/link to learn Angular JS in one day.

https://toddmotto.com/ultimate-guide-to-learning-angular-js-in-one-day/

Useful for refreshing basic Angular JS concepts in quick time.


21 December 2015

SharePoint 2013 - Problem in debugging and deploying SharePoint web-part

Recently we were developing a web-part for our SharePoint 2013 site. When we tried to connect to SharePoint 2013 site from Visual Studio 2013, we got following error -

Error occurred in deployment step ‘Recycle IIS Application Pool’: Cannot connect to the SharePoint site: http://<your sharepoint site>/. Make sure that this is a valid URL the SharePoint site is running on the local computer. If you moved this project to a new computer or if the URL of the SharePoint site has changed since you created the project, update the Site URL property of the project

Due to this error, we were not able to deploy web-part to SharePoint site directly from Visual Studio itself. We were also not able to debug the web-part.

Finally we found the solution for this problem. Visual studio 2013 runs as process vssphost5.exe. This process runs under an account. This account can be identified by going to Task Manager and looking at details of the process. This account needs to be given dbowner permissions on following SharePoint databases -

  • SharePoint site content database
  • SharePoint central admin content database
  • SharePoint configuration database
To find names of these databases, you can go to Central Admin --> Backup & Restore -->Perform Backup.

Once these permissions were given, we were able to deploy the web-part and debug it right from Visual Studio.

18 December 2015

Visual studio Dev Essentials Program - 6 months of pluralsight and other benefits

Sign up for Visual Studio Dev Essentials program and get access to exclusive benefits including free training, Azure credits and more.

https://www.visualstudio.com/en-us/products/visual-studio-dev-essentials-vs.aspx 

Pluralsight offer is for limited time only. Be sure to sign up before 31st Dec 2015.

Enjoy...




16 December 2015

SharePoint Online - How to remove a service principal name from service principal

Today I was configuring server to server authentication between SharePoint 2013 Azure and SharePoint Online. I was following the steps from this MSDN URL -

https://technet.microsoft.com/en-us/library/dn197169.aspx

Everything went on fine until I executed following commands -

$msp = Get-MsolServicePrincipal -AppPrincipalId $spoappid
$spns = $msp.ServicePrincipalNames
$spns.Add("$spoappid/$spcn")
Set-MsolServicePrincipal -AppPrincipalId $spoappid -ServicePrincipalNames $spns

I got following error in the last command -

Set-MsolServicePrincipal : Uniqueness violation. Property: ServicePrincipalNames.
At line:1 char:1
+ Set-MsolServicePrincipal -AppPrincipalId $spoappid -ServicePrincipalNames $spns
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [Set-MsolServicePrincipal], MicrosoftOnlineException
    + FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.UniquenessValidationException,Microsoft.Onlin
   e.Administration.Automation.SetServicePrincipal


I checked the values of existing Msol Service Principal with the help of following commands - 

$msp = Get-MsolServicePrincipal -AppPrincipalId $spoappid
$spns = $msp.ServicePrincipalNames
$spns

The output was in this format - 

00000003-0000-0ff1-ce00-000000000000/*.mydomain.com
00000003-0000-0ff1-ce00-000000000000/*.sharepoint.com
00000003-0000-0ff1-ce00-000000000000

I immediately found the problem. I was trying to add "*.mydomain.com" again to the service principal and it was already existing. I realized that I had added it earlier on a different server using a different certificate. But since that certificate was no longer valid, I have to re-register it with a new certificate but with same domain name. 

Searched a lot on internet but was not able to find how to remove a service principal name from a service principal.

Finally I found the solution in my original commands.

$msp = Get-MsolServicePrincipal -AppPrincipalId $spoappid
$spns = $msp.ServicePrincipalNames
$spns.Add("$spoappid/$spcn")
Set-MsolServicePrincipal -AppPrincipalId $spoappid -ServicePrincipalNames $spns

If you see these commands, I am adding my service principal name in service principal using

$spns.Add("$spoappid/$spcn")

Since this is a generic list, all I have to do is remove the same service principal name from generic list and again update the service principal.

$msp = Get-MsolServicePrincipal -AppPrincipalId $spoappid
$spns = $msp.ServicePrincipalNames
$spns.Remove("$spoappid/$spcn")
Set-MsolServicePrincipal -AppPrincipalId $spoappid -ServicePrincipalNames $spns

That's it. Simple and elegant solution. But spent quite some time figuring it out.


15 December 2015

SharePoint 2013 - GetUserEffectivePermissions returning incorrect results

Recently I was trying to get effective permission of a SharePoint user using client context (client side object model). I was trying to achieve this in SharePoint 2013 Provider Hosted App.

The method was executing sucessfully but when I was iterating through the effective permissions, I was getting false for all the permissions. Here is the sample code that I was using -

var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

using (var clientContext = spContext.CreateUserClientContextForSPHost())
{

    string userName = @"domain\username";

    var userPermissions = clientContext.Web.GetUserEffectivePermissions(userName);
    clientContext.ExecuteQuery();

    foreach (var permission in Enum.GetValues(typeof(PermissionKind)).Cast<PermissionKind>())
    {
        var permissionName = Enum.GetName(typeof(PermissionKind), permission);
        var hasPermission = userPermissions.Value.Has(permission);
        Response.Write(String.Format("<br>Permission: {0}, HasPermission: {1}", permissionName, hasPermission));
    }


}

Finally I realized that my SharePoint application is claims enabled. So I have to pass user-name in claims format.

string userName = @"i:0#.w|domain\username";

The code worked like a charm after that.

Hope this helps someone as I spent quite some time in figuring out this small thing. Its not mentioned anywhere in MSDN forums. I have tried to answer this on few posts in stack-exchange and stack-overflow forums.


12 December 2015

SharePoint - Error when configuring Federated Search (Open Search 1.0/1.1)

Recently I was trying to configure Federated Search on my SharePoint environment. I was configuring "Bing Search" as a Federated Result source.
(http://www.bing.com/search?q={?searchterms}&format=rss&Market=en-US).

After configuring it, when I tested the result source, I got following exception logged in SharePoint ULS logs -

SearchServiceApplication::Execute--Exception: System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: key is null or empty 

When I searched over internet, I came across Microsoft forum which mentions that this happens if your SharePoint installation has Sep 2014 update. This issue was fixed in Nov 2014 update.

I checked my SharePoint version and found that indeed I had Sep 2014 update only. It was not updated to Nov 2014 cumulative update. After performing the update, the issue got fixed.



09 December 2015

Introduction to Continuous Integration and Team City

Continuous Integration

Continuous Integration is a development practice that requires developers to integrate code into a shared repository on a regular basis (at least daily). Each integration process is verified by an automated build. Automated build may also include automated unit testing, code analysis etc. Automated build may be followed by automated deployment as well.

Advantages of Continuous Integration 

  • Takes code from central repository for build
  • Helps in detecting integration errors early & easily.
  • Leads to faster and more frequent integration.
  • Improves project management confidence.
  • Prevents last minute integration problems.


Disadvantages of Continuous Integration 
  • Extra cost requirement
  • Extra time/effort requirement

TeamCity:

TeamCity is Continuous Integration (CI) server from JetBrains. It provides all the features of Continuous Integration. It is available for Windows, Mac OS & Linux. 

Features of TeamCity:

  • Language & Platform support - It supports various language platform projects. E.g. – Java, .NET, Ruby, Xcode, C++, Python, PHP etc.
  • Integration with Source control systems - It supports various source control repositories.  E.g. – TFS, VSS, ClearCase, Subversion, Perforce, CVS etc.
  • Integration with build systems - It supports various build systems. E.g. – Java (Ant, Maven, Gradle), .NET (MSBuild, PowerShell, Nant), Ruby (Rake with RVM, Bundler, Ruby SDK).
  • Central Administration web console - Team city provides web based central administration console. It can be used for various activities like - administration, configuration & maintenance, managing projects & build configurations, Managing user accounts, groups & permissions, managing build agents, viewing various reports related to server etc.
  • Multiple build agents - Team city supports multiple build agents. Each build agent can run a build script. Hence TeamCity can run multiple parallel builds. Build jobs can be queued on build agents. The jobs will be executed once build agent is free. 
  • On the fly build progress reporting - TeamCity reports build progress (errors, warning, informational messages) as build progresses. Build progress is available on both web administration console and in IDEs. TeamCity alerts about failed tests immediately. 
  • Automated Unit Testing - TeamCity automatically runs unit test during build. The build fails if any test fails. Failed tests are highlighted in build results. Notifications can be sent for failed tests. Failed tests can also be assigned to specific developers leading to easier test management. Unit testing history and statistics is stored and available for analysis.
  • Code quality tracking – TeamCity provides various features for code quality tracking. E.g. – Duplicate code analysis, Static code analysis, Code coverage, Code quality reports etc.
  • Plugins – TeamCity supports plugins for extensibility. Over 100 ready to use plugins are freely available on TeamCity site. These plugins help in achieving functionalities which are not available out of the box. Users can develop their own plugins for any custom needs.

References and Suggested Readings:


05 December 2015

Useful websites for HTML5 and CSS3 browser compatibility check

I recently came across three useful websites for checking and verifying browser compatibility of various HTML5 and CSS3 features.

http://caniuse.com/ - This site lists various features of HTML5 and CSS3. When you click on any of the feature, it provides a list of browsers which supports these features along with their version number.

http://html5test.com/ - This site checks your browser for HTML5 feature compatibility and rate it on a pre-defined point scale. Then it provides a list of all features of HTML5 and their compatibility with your current browser. It also provides compatibility of various HTML5 features for other browsers.

http://css3test.com/ - This site checks your browser for CSS3 features compatibility and rate it on a percentage basis. It also provides a list of all features of CSS3 and their compatibility with your current browser.

Found these websites very useful during development and helps in deciding to use or not use a particular feature of HTML5 or CSS3.

30 November 2015

Parsing XML to objects in .NET

Introduction

There is a general requirement in many projects to parse XML to an object and vice versa. Instead of using inefficient and error prone method of manual XML parsing, .NET object serialization/deserialization functionality can be used to achieve similar result in a more efficient and elegant manner. This approach is very generic and will work with all types of XML.

Approach

System.Runtime.Serialization provides methods for serializing and de-serializing XMLs.
DataContractSerializer method of System.Runtime.Serialization namespace can be used to achieve functionality of -

  • XML to object conversion (XML Parsing [De-Serialization])
  • Object to XML conversion (Object Serialization)
  • Apart from this, Generics feature of C# has been utilized to make the methods generic and independent of object types. It also enhances type-safety of the code. Actual type needs to be specified only when method is called.
  • The method for ‘Serialization’ accepts type of data to serialize as a parameter ‘T’. This makes the method generic in a sense that it can accept object of any type for serialization and we don’t have to define that at time of method declaration.
  • The method for ‘De-Serialization’ returns de-serialized data. The return type has been specified as generic ‘T’. This makes the method generic in a sense that it can de-serialize and return object of any type.
Implementation

1.    Class declaration
1.1. Create a static class named ‘XmlParserDeparser’.
1.2. Reason for making this class static is that this class acts as a utility class and there will be no need to create instance of this class to access its helper methods.
1.3. Add following namespace in the class file –
1.3.1.   using System;
1.3.2.   using System.Collections.Generic;
1.3.3.   using System.IO;
1.3.4.   using System.Runtime.Serialization;
1.3.5.   using System.Text;

2.    XML to object conversion (XML parsing/de-serialization)
2.1. To achieve this conversion, DataContractSerializer method of System.Runtime.Serialization will be used.
2.2. Declare a static method with name XmlToObject<T>.
2.3. Here ‘T’ will be type of the data object to create after parsing XML using de-serialization techniques.
2.4. This method will return object created from XML.
2.5. It will take two input parameters -
·         XML as string
·         Known types to include in the serializer (can be null too)
2.6. Complete code for the method is presented below –
/// <summary>
/// Deserializes the specified XML string.
/// </summary>
/// <typeparam name="T">The type of the data to deserialise to.</typeparam>
/// <param name="xml">The XML string representing the data to deserialise.</param>
/// <param name="knownTypes">The known types to include in the serializer.</param>
/// <returns>The deserialised data in object form.</returns>
public static T XmlToObject<T>(string xml, IEnumerable<Type> knownTypes)
{
    using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(xml)))
    {
        var serializer = new DataContractSerializer(typeof(T), knownTypes);
        T theObject = (T)serializer.ReadObject(stream);
        return theObject;
    }
}

2.7. Here a memory stream is created using XML as input.
2.8. An instance of System.Runtime.Serialization.DataContractSerializer is created specifying type ‘T’ and enumeration of knownTypes as input. Latter is optional though (can be null).
2.9. Now the object of DataContractSerializer reads the XML and creates a generic object.
2.10. This object is cast to type ‘T’ and then returned.
2.11. We can also create over-load of this method with only one parameter i.e. ‘XML as string’.
2.12. This method will internally call the above method with ‘knownTypes’ passed as null.
2.13. The signature for this method will be as follows –
        /// <summary>
        /// Deserializes the specified XML string.
        /// </summary>
        /// <typeparam name="T">The type of the data to deserialise to</typeparam>
        /// <param name="xml">The XML string representing the data to deserialise</param>
        /// <returns>The deserialised data in object form</returns>
        public static T XmlToObject<T>(string xml)
        {
            return XmlToObject<T>(xml, null);
        }


3.    Object to XML conversion (Object serialization)
3.1. To achieve this conversion, DataContractSerializer method of System.Runtime.Serialization will be used.
3.2. Declare a static method with name ObjectlToXml<T>.
3.3. Here ‘T’ will be type of the data object to convert to XML using serialization techniques.
3.4. This method will return XML as string.
3.5. It will take two input parameters -
·         Type of object to convert to XML
·         Known types to include in the serializer (can be null too)
3.6. Complete code for the method is presented below –

/// <summary>
/// Serializes the specified input data, of type T, to XML string.
/// </summary>
/// <typeparam name="T">The type of the data to serialise.</typeparam>
/// <param name="data">The data to serialise.</param>
/// <param name="knownTypes">The known types to include in the serializer.</param>
/// <returns>The data as an XML string.</returns>
public static string ObjectToXml<T>(T data, IEnumerable<Type> knownTypes)
{
    using (var memoryStream = new MemoryStream())
    {
        var serializer = new DataContractSerializer(typeof(T), knownTypes);
        serializer.WriteObject(memoryStream, data);
        memoryStream.Seek(0, SeekOrigin.Begin);

        var reader = new StreamReader(memoryStream);
        string content = reader.ReadToEnd();
        return content;
    }
}

3.7. Here a memory stream is created first.
3.8. An instance of System.Runtime.Serialization.DataContractSerializer is created specifying type ‘T’ and enumeration of knownTypes as input. Latter is optional though (can be null).
3.9. Now the object of DataContractSerializer reads the object data and writes the output (XML) into memory stream.
3.10. This memory stream is then read by a StreamReader object till end and converted to string which is returned by method.
3.11. We can also create over-load of this method with only one parameter i.e. ‘Type of object to convert to XML’.
3.12. This method will internally call the above method with ‘knownTypes’ passed as null.
3.13. The signature for this method will be as follows –
  /// <summary>
        /// Serializes the specified input data, of type T, to XML string.
        /// </summary>
        /// <typeparam name="T">The type of the data to serialise.</typeparam>
        /// <param name="data">The data to serialise.</param>
        /// <returns>The data as an XML string.</returns>
        public static string ObjectToXml<T>(T data)
        {
            return ObjectToXml(data, null);
        }


Advantages
  • The advantage of using this approach is that you are able to perform XML parsing very easily without writing custom parsing code.
  • Similarly you are able to easily convert an object to XML without need of any custom code.
  • This code is generic and will work for all types of XML and objects. We just need to ensure to specify proper XML and object type (T).

25 November 2015

Introduction to AngularJS

AngularJS is an open source JavaScript framework developed by Google. It helps in extending capabilities of HTML, CSS & JavaScript. It enhances browser based applications with MVC (Model-View-Controller) capabilities which help in making development and testing easier. AngularJS combines both Declarative Programming (used for building UIs and wiring software components) and Imperative Programming (used for building business logic). It provides two-way data binding features (similar to Silverlight/WPF XAML) which helps in automatic synchronization of models & views. It decouples DOM manipulation from application logic thus improving testability of the code.

Features of AngularJS -

Two way data binding – AngularJS provides two way data binding between Model & View. The data between model & view is automatically synchronized on change. This is most important and useful feature of AngularJS. This feature takes care of DOM manipulation and listening to DOM events. Thus application developers can focus on application logic instead of writing boiler plate code for handling DOM manipulation.

Model-View-Controller (MVC) – AngularJS is based on the basic principles of MVC design pattern.

  • In AngularJS, any JavaScript object can act as a Model. 
  • View is the declarative HTML used for UI design. It is based on DOM objects.
  • Controller is responsible for construction of the model and connects it to View. It contains business logic. They can be nested and can handle inheritance. 

Services – They perform small common tasks for your web application. We can use in-built services or create our own using various methods viz. Service API, Factory API or $provide API. In-built AngularJS services starts with “$” symbol.

Dependency Injection – AngularJS has in-built Dependency Injection. AngularJS services can be passed as parameters whenever required. AngularJS identifies the dependencies and automatically creates their instance.

Directives – Directives enables programmers to extend the HTML vocabulary in a declarative way. They help in transforming DOM or creating new behavior.  AngularJS has some in-built directives. It also allows programmers to create their own directives.

Templates – AngularJS enables programmers to create static declarative templates containing HTML, CSS & AngularJS elements. These templates get combined with model and controller at run-time to render the final view.

Filters – Filters helps in performing data transformation and data formatting. They can also be used to filter results.

Validation – AngularJS has many in-built validations for various HTML5 input variables, controls and directives. E.g. – Validations for textbox, number, URL, email, radio, checkbox, required validator, pattern validation, minlength, maxlength, min, max etc. It also enables programmers to create their own validations which can be re-used.

Testability – Applications created using AngularJS are highly testable due to use of MVC pattern and Dependency injection. Unit tests can be created and run against JavaScript code making enterprise application level testing possible.

References and Suggested Readings

http://angularjs.org/

20 November 2015

KendoUI controls not working in all browser versions

Recently we faced a strange problem with KendoUI controls. While most of the controls were working fine, KendoUI tab control was not working in all versions of Internet Explorer. It was loading fine on first page load but when we tried to click any other tab, nothing was happening. After quite a bit of research, we found a simple solution to the problem.

Add following tag in your HTML file -

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

This will ensure that your HTML code works fine in all browsers as required. Especially the latest browser that you are using.

Apart from this solution, we also recommend to use latest version of Kendo UI controls as far as possible. We were using one year old version of Kendo UI (2014 Q2) while the latest version was 2015 Q3 SP1. Kendo is very good in fixing minor bugs like these in their progressive releases. So its always a better idea to use the latest version.

02 November 2015

FabricJs - Top features

FabricJs is a simple and powerful JavaScript library for HTML5 which helps in working with HTML5 canvas objects. It is an open source library. HTML5’s native APIs to work with canvas are low level and provide limited functionalities. FabricJs helps in manipulating and animating objects in HTML5 canvas in a much powerful manner without losing the canvas state. It creates an interactive layer above HTML5 canvas which enables easier manipulation of canvas objects. It renders canvas in a much faster manner as compared to HTML5 due to use of SVG.

Features of FabricJs:

Interactivity – FabricJs enable users to interact with objects on HTML5 canvas using mouse. Interaction can be dragging object, rotating object, scaling object etc.

Paths – In FabricJs, paths represent an outline of a shape that can be stroked, filled or modified in other ways. It consists of a series of commands (move, line, curve, arc etc.) which can help in producing complex shapes.

Groups – In FabricJs, we can group multiple objects together using ‘Groups’. These objects can then be manipulated together as a single unit.

Animation – FabricJs provides powerful animation capabilities like rotate, move, shrink, grow, fade-in, fade-out etc.

Image Filters – FabricJs provides methods to apply filters to images. It provides some inbuilt filters. E.g. – Brightness, Tint, Sepia, Convulate, Grayscale, Invert, Pixelate, Noise etc. It also gives option to apply custom filter. It also give option to remove a filter from image or apply multiple filters to images.

Gradient – FabricJs provides methods to apply gradients to objects. Gradient can be applied using multiple colors as well.

Text – FabricJs supports text abstraction and enables to work with text in object oriented model. It also supports rich text which enables to change various text properties like font style, font shadow, alignment, height, background, height, multiline support etc.

Events – FabricJs is based on event driven architecture. It supports lots of events from low level hardware (mouse, keyboard) events to high level object events.

Sub-classing – FabricJs supports inheriting from existing classes. We can also create our own classes and even extend existing classes.

Free drawing – FabricJs has excellent support for free hand drawing on the canvas.

Canvas Serialization –FabricJs supports serializing canvas into object/string which can be easily transmitted or stored.  FabricJs supports 3 types of serialization –

  • To JSON – This converts canvas object into JSON string.
  • To Object – This converts canvas object into an array of point objects.
  • To SVG – This converts canvas object into SVG (Scalable Vector Graphics) text format using SVG parser.


Canvas Deserialization – FabricJs supports two ways to render canvas from string –

  • From JSON – This recreates the canvas from a JSON string
  • From SVG – This recreates the canvas from SVG string.


References and Suggested Readings:


01 November 2015

Dynamically generate header in SilverLight Telerik RAD Grid using MVVM approach

In this post, we will discuss how to dynamically change the grid headers in SilverLight Telerik RAD Grid using MVVM approach.

Create simple Silverlight project ‘DynamicGridHeader’. Create two folders name it as “View” and “View Model”. Add Silverlight user control to the View folder name it as “MyView”. MyView page will have all my user controls to show the data.

Create simple Telerik grid in the page and add one button to change the headers.  Grid should have Four columns showing data for country Names, Country ID, Population for current year and last year population.















Create a class in view model to add data to the grid.  And implement INotifyPropertyChanged
Interface to get notification when property changes.














Populate dummy data in the constructor.


























Till now the grid will show the data for current year and previous year. With column headers as 2012 and 2011.














Now when user want to check data for 2011 and 2010 the column header will not change. It is always show 2012 and 1011. To change the column dynamicaly create two properties one showing selected year and other showing previous year. Bind these properties to textblock and then to the grid headers.









Now when user select previous year the headers will changed dynamically.





















That's it. Simple and elegant solution !