Monday, May 14, 2018

Create New SharePoint Web coping sibling site content


There are situations when you need to create duplicate the already created web using same site template, language and site structure. This article will cover how to use PowerShell to create new web, export sibling site and restore on new web. This process is dissected in three sections,

Create New Web

The basic PowerShell command to create web is following,

New-SPWeb -url "http://spsite/en-us/ACCOUNTING" -Name "Asset Accounting" 

If you want to use specific template for new web you can write following command,
New-SPWeb -url "http://spsite/en-us/ACCOUNTING" -Name "Asset Accounting" -Template BLANKINTERNET#2

You can find the installed templates from following command,

If you want to use specific template and specific language for new web, you can write following command,
New-SPWeb -url "http://spsite/en-us/ACCOUNTING" -Name "Asset Accounting" -Template BLANKINTERNET#2 -Language 1033
Note: 1033 is for English which is default. If we need to create this for arabic, use 1025.

Export Sibling Site

Following is command for exporting sibling site

Export-SPWeb "http://spsite/en-us/Finance" -Path "c:\firstbackup.bak" 

Import Backup to New Site

Now we have new site and backup of sibling site. We will now restore that backup to newly created web,

Import-SPWeb "http://spsite/en-us/ACCOUNTING" -Path "c:\financeaccount.bak" 

Monday, November 27, 2017

Why and How to implement Dependency Injection Pattern?


By using dependency injection, you solve two main problems,

1- Unit Test
2- Instantiation

Unit Test

You can resolve this by implementing interface of every class that is required to instantiated in any method or implementation. Always pass interface as parameter in constructor rather than making variables and instantiate in the class. For unit test, you can send mocked (the dummy) instantiation of that interface to that class.


        public class Order
            public string ID { get; set; }
            public string Detail { get; set; }

            public void Process()
        public class Cart
            public void ProcessOrder()
                Order order = new Order();

Saturday, October 15, 2016

JavaScript Object References

Recently people asked me how JavaScript keep references while passing through function parameters including angular promise, underscore and normal JS code. I will provide one example from each section to show how references are passed.

Under Score (Lodash) Example

Some of the Underscore library functions return object reference while other returns new object. e.g. _.find method returns reference of the object that was found. in the following example when we change the value of variable "f.a", it affects "chkUnder" variable. While in case of _.where method, if we change the value of "w.a", it never changes the variable "chkUnder".

var chkUnder = [{ a: 1 }, { a: 2 }, { a: 3 }];
var f = _.find(chkUnder, { a: 2 });
f.a = 22;
var w = _.where(chkUnder, { a: 2 });
w.a = 24;

Wednesday, July 6, 2016

How to add Web API to an existing ASP.NET MVC Web Application

The steps I needed to perform were:
  1. Add reference to System.Web.Http.WebHost.
  2. Add App_Start\WebApiConfig.cs (see code snippet below).
  3. Import namespace System.Web.Http in Global.asax.cs.
  4. Call WebApiConfig.Register(GlobalConfiguration.Configuration) in MvcApplication.Application_Start() (in file Global.asax.cs), before registering the default Web Application route as that would otherwise take precedence.
  5. Add a controller deriving from System.Web.Http.ApiController.
I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.
using System.Web.Http;

class WebApiConfig
    public static void Register(HttpConfiguration configuration)
        configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });

// To return objects in Json format (Not XML Format),
var appXmlType = configuration.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");

using System.Web.Http;


protected void Application_Start()


Use TypeScript in SharePoint Hosted App

There is trick involved in making Visual Studio realize to compile TypeScript and generate javascript files, Following procedure will give you complete guidance how to complete the process.

1.      Create a new Sharepoint-hosted app.
a.      Right-click the project name and select Unload Project.
b.      Right-click the project name and select Edit <your project name>.csproj.
c.      Add these lines before the last closing <Project> tag. 

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" />

1.      Right-click the project name and select Reload Project.
2.      Now you will see the TypeScript tab in the project properties.

2.      Now you can add the TypeScript definitions. Right-click the project name and select Manage Nuget Packages. Search online for “sharePoint.Typescript.” Install thesharePoint.Typescript.DefinitelyTyped package.      

3.      Also search for “jquery.typescript” and install the jquery.Typescript.DefinitelyTyped package.

Now you are ready to work with Typescript and can create Typescript files.

Tuesday, May 24, 2016

Extract GAC DLL

Most of the times developers need to extract/copy dlls from GAC. The first step is to see whether these dlls are 32 bit or 64 bit or MSIL. So the first step is to open the command prompt and move to assembly folder. To do this, you need to run following command,

cd c:\Windows\assembly

Now you can see how many types of of assembly folders exists (Windows explorer does not let you select these folders). run following command and you will see the results as below,


Monday, May 9, 2016

Operation is not valid due to current state of the object -- Elevated Privileges


Message=Operation is not valid due to the current state of the object.


I tried to call SPUtility.SendEmail within the RunWithElevatedPrivileges delegate.


If i try to run this method out of Elevated delegate, it works fine. All the other things that are working fine in Elevated Privileges (except send email) are,

  1. SPUtility.GetPrincipalsInGroup
  2. spWeb.EnsureUser

Thursday, February 11, 2016

How to set InfoPath field value on dropdown change event in SharePoint 2010 and 2013


We have a Dropdown in InfoPath which is populated from external data source (SharePoint List. e.g. TimeSheet List having fields ProjectName, %Complete and Type. Dropdown is showing Project Names). We want to populate infopath field (Type) from SharePoint based on selected Project in dropdown.


I suppose you have already Filled Dropdown from Timesheet List and or applied filtering if required, If not, you can follow my post How to Filter Infopath Dropdown.

Select the Project dropdown that we created in previous article and from the "Home" ribbon, select Add Rule->This Field Changes -> Set a Field's Value option as shown in the below image.

How to Populate and Filter InfoPath Dropdown Populating from SharePoint List


We have TimeSheet SharePoint List which has information of all the projects, their status and % Complete. We want to populate dropdown with TimeSheet projects whose status is not closed.


Populating Dropdown

First Create the List as following,

Now in the InfoPath Designer (It does not matter if it is list template or designing new InfoPath document), Add dropdown list from menu bar,

Tuesday, February 2, 2016

Unable to connect to the Synchronization Service error when you try to open Miisclient.exe


When you try to open Miisclient.exe , you get the following error message:
Unable to connect to the Synchronization Service.

Some possible reasons are:

1) The service is not started

2) Your account is not a member of a required security group.

See the Synchronization Service documentation details.

Wednesday, December 30, 2015

Angular timeout ($timeout) service promise

In angular JS, if you want perform some action after some time (or you want to wait for some time) you can use $timeout service. This service returns the promise which we can resolve by "then". In following example, it will take 2 seconds to call the function "toBeCalled".

function Controller($timeout) {

           wait(2).then(function () {


            function wait(seconds) {
                return $timeout(toBeCalled, seconds * 1000);

            function toBeCalled() {
                console.log("called after 2 seconds");

Saturday, December 19, 2015

Entity Framework Code First Approach

Code First approach does not actually Mean that you can not utilize existing database. Instead, it lets you deal with existing database or you can start with code and Entity Framework will create new database. Let us See both approaches,

Existing Database

Open your project in Visual Studio 2013 and click Add New Item -> ADO.NET Entity Model
Click on the Code First from database option. This wizard will lead you to create model classes.

Wednesday, December 16, 2015

ASP.NET Web API 2 Tips and Tricks

Web API Supports RPC(Remote Procedure Call) API and REST API(Representational State Transfer). To simplify this, RPC means action based routing and REST API means Default GET/POST/.... Methods.
REST API offers only method per request type except the Get which comes two times (One for getting Single Record and one for all Records).

Note: You can not use both techniques in One Controller. you can use One only one technique in one controller.


Tuesday, December 15, 2015

How to Know when your angular rendering is complete (Callback function for ngrepeat/ng-repeat)

There are scenarios when you need to know that angular rendering is complete due to ng-repeat directive. Here we need to understand that the success call back method of $http does not mean your rows are rendered. following is the scenario where we can utilize this ng-repeat callback method,
1- You may need to perform particular Jquery Method after rendering of rows is complete.
2- Format generated rows after they are rendered.
3- I needed this to use data tables object ( $('#tbl').DataTable();) after rendering is complete.

To start with, we need to write an attribute level directive which we can call like,

Monday, August 3, 2015

Azure AD Graph API cannot access Microsoft Account

Problem 1:

User.Identity.Name is null for Microsoft users.


in Global.ascx, write following code,
 protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
            ClaimsIdentity id = ((ClaimsIdentity)User.Identity);
            Claim claim = id.FindFirst(ClaimTypes.Email);
            if (claim != null)
                string email = claim.Value;
                id.AddClaim(new Claim(ClaimTypes.Name, email));

Problem 2: ?api-version=2013-04-05 is not returning user profile which the same api works for the local users of AD.

Solution$filter=startswith(userPrincipalName, 'testemail_hotmail')