Monday, November 27, 2017

Why and How to implement Dependency Injection Pattern?

Benefits

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.

Before

        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();
                order.Process();
            }
        }

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.
App_Start\WebApiConfig.cs:
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");
            configuration.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

    }
}
Global.asax.cs:
using System.Web.Http;

...

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

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. 

    <TypeScriptSourceMap>true</TypeScriptSourceMap>
  </PropertyGroup>
<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,

dir


Monday, May 9, 2016

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


Exception

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

Cause: 

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

Comments

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

Problem

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.

Solution

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

Problem

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.

Solution

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


Problem

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.

Configuration


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.

Solution

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: 

https://graph.windows.net/tenantid/users/testemail@hotmail.com ?api-version=2013-04-05 is not returning user profile which the same api works for the local users of AD.

Solution

https://graph.windows.net/contoso.com/users?api-version=2013-11-08&$filter=startswith(userPrincipalName, 'testemail_hotmail')

Wednesday, July 8, 2015

Adding Application Constants by removing Magic Strings in Angular applications

Defining App


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

Adding Constants


These constants are used to remove magic string from the application and user application level constants,

myApp.constant('AppConstants', (function () {
    var constants = {};
 
    constants.App = {};
    constants.App.Name = "My Application Name";
 
    constants.LocalStorage = {};
    constants.LocalStorage.profileKey = "profile";
    constants.LocalStorage.clientsKey = "clients";
 
 
    constants.clsProfile = {};
    constants.clsProfile.Email = "Email";
 
    return constants;
 
}())
 
);

How to add toaster in Angular JS

Index page:

 Open Home main (Container page) page  and add following references.
Remember, If you will add following lines in any of angular view, it will not work.

Reference:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/0.4.9/toaster.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/0.4.9/toaster.min.css" rel="stylesheet" />
<script src="https://code.angularjs.org/1.2.0/angular-animate.min.js"></script>


Add Toaster Tag

<toaster-container></toaster-container>

Tuesday, July 7, 2015

Angular JS $state.go redirects to home page

Topic


$urlRouterProvider.otherwise() called before $state.go()

Explaination

i faced above problem in one of my application. I needed to change the state on click event of anchor tag. User was being navigated to Otherwise route rather than redirecting to the route that was called on click event. following was my code,



<a ng-click="SetClient(Name)" href="#">{{Name}}</a>

function SetClient(stateName)
{
$state.go(stateName);
}

The following configuration is used for redirection if any other url is provided.
$urlRouterProvider.otherwise("/home");

The Problem

When ever i clicked on the hyperlink, it redirected to home state rather than the state name that was passed to SetClient.

Solution

I found out that "#" hash sign is creating problem. i removed hash sign and it worked fine.
<a ng-click="SetClient(Name)" href>{{Name}}</a>
Hash sign was calling "$urlRouterProvider.otherwise".

Sunday, May 17, 2015

Could not load file or assembly ‘$SharePoint.Project.AssemblyFullName$’ or one of its dependencies. The system cannot find the file specified.

There are lot of scenarios where you can face this issue. I will explain scenario which i faced.

Scenario

I have all the solution deployed and running already on the production server. My task was to just change an html link in the .ascx control. I changed the control and rather than deploying whole solution, i copied .ascx control and put it in the 14 hive control templates. I restarted IIS and refreshed page, i found following exception,

Could not load file or assembly ‘$SharePoint.Project.AssemblyFullName$’ or one of its dependencies. The system cannot find the file specified.


Solution

Luckily error was pointing towards the new custom control that i deployed. I opened file and searched for "$SharePoint.Project.AssemblyFullName$". Replace this string with the actual assembly name, version and culture (If you deploy with visual studio, it changes it automatically but as it was manual deployment, i needed to copy control's assembly and replace with the "$SharePoint.Project.AssemblyFullName$"). Restart IIS and problem was solved.

Wednesday, November 19, 2014

Step by Step guide to create First PDF report with ADOBE Pro and iTextSharp -- .NET

Recently I had to work on a reporting module for Mobile application. I used iTextSharp to write wrapper class which was responsible for creating PDF files on the fly. The plan was to create PDF forms from Adbobe Acrobat Pro and generate PDF reports using the iTextSharp and my wraper class. My wrapper class takes PDF Template path, Simple Modal object (Just having values to print on PDF) and the output PDF path as input and generate PDF report. Let us see in more detail.

First Install NuGet Package, iTextSharp

Create PDF form 

First create a mock up of a report in the word document,


Reflection: Dynamically reading Object Properties and Calling Methods -- .NET


Introduction

In the .NET Framework, every program is compiled into an assembly containing metadata which has information of assembly behavior and structure. Reflection in .NET is used to observe and change the behavior of any object which means you can read read metadata of an object through reflection.

Current sample is going to describe following features of Reflection,
  1. Object properties and their datatypes.
  2. Call object methods dynamically. 
The first thing to use reflection in your project is, include the reflection namespace,

using System.Reflection;

Sunday, September 28, 2014

Opening InfoPath Form in Modal Dialog

Question 


How to open InfoPath New and Edit forms in the Modal dialog?


Answer


Let us start with new fresh InfoPath Library. Create an InfoPath Library and call it "AccordionForms". The path of library would be like,


Let us examine new and edit form URLs.


New InfoPath Form:


If you click on the new item link, it would redirect to URL,


Wednesday, September 24, 2014

Create Info Path Accordion (Show Hide Section)

Previously i worked on the project which used InfoPath form. The Form had many sections and each section had scrolling and lot of data. I needed to introduce accordion in the form. I needed to add buttons to show hide any section of the form so that user can focus on what is required. InfoPath is different than the normal JQuery accordion where you can hide or show any thing based on script or just CSS. In InfoPath you need to add behavior and Rules for each button and section which we want to hide or we want to use as changing behavior or variable. Following is the how i achieved it,
1- First thing first, add two picture buttons (Having up and down pictures).  

2- Add Boolean variable ESShow and set its default value as 0 if you want to hide section when InfoPath form loads otherwise set its default value 1.


Content Editor Web Part Example (Writing Custom Web Part

The Content Editor Web Part (CEWP) allows you to add text, html, JQuery or styles to a SharePoint page. It is great to use this if you,

  1. Are good in JQuery or Javascript.
  2. Want to use Web Services, REST API (Introduced in SharePoint 2013) or ECMA script.
  3. Need One or two pages of customization and do not want to touch Visual Studio and going through process of uploading solutions.
  4. Do not have deployment permissions on Central Administration.

Add a Web Part to a page


1. From a page, in the ribbon, click the Page tab, and then click the Edit command.

Image: Edit command of the Edit tab

Display Parent web InfoPath form in child web InfoPath Form Web part

Problem

Yesterday i faced an issue while displaying Info Path form in the web part. My task was to show the Info Path form in the child web but actual Info Path library was on the parent web. The problem was when i tried to edit the Info Path web part, i could not see the list of Info Path library (from parent web) because it was showing only current site Info Path libraries.

Solution

I added new page in Page/Site Pages library of parent website. I added Info Path web part in the page and copied the Page from parent web to child web. Every thing worked fine in the child web Info Path web part page.

Copy Page to Child Site

Tuesday, September 23, 2014

Copying Web Part Page to same / other list of same web or child web

Problem


There are situations when you want to copy the web part page to same/other list in same web/child web. If you copy the page through SharePoint Designer, it will copy the page but the web parts will be removed.


Solution


Use site Content and Structure.

Procedure

Monday, May 5, 2014

The assembly 'DevExpress ...' is not registered for COM Interop. Please register it with regasm.exe /tlb.

Last week i was stuck in to a problem for registering the DevExpress library. I received following error while compiling the project,

"The assembly 'DevExpress.Utils.v13.2, Version=13.2.6.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a' is not registered for COM Interop. 
Please register it with regasm.exe /tlb."

Solution:
1- Open command prompt with administrator privileges and navigate to folder,
C:\Program Files (x86)\DevExpress 13.2\Components\Bin\Framework

2- Run following command,
RegAsm.exe "C:\Program Files (x86)\DevExpress 13.2\Components\Bin\Framework\DevExpress.Utils.v13.2.dll"


Friday, February 21, 2014

Adding Recursive Folders to TFS using C#


Add reference to two dlls

Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.VersionControl.Client.dll

Include following assemblies,

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;


Authenticating TFS

// Providing URL, UserName and Password
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(tfsURL), new                          System.Net.NetworkCredential(userName,password));

// Checking Authentication
tpc.EnsureAuthenticated();

// Getting Version Control instance
VersionControlServer versionControl = tpc.GetService<VersionControlServer>();

Create Simple Accordion with JQuery (Not JQuery UI)

Why not use JQuery UI accordion?

JQuery UI is more professional accordion and has too many options. But in my last project, I had to create accordion having different color coding on each heading background and other rendering options so i just created very very simple accordion.

I have created two Headings and for each heading i have provided class name "question" and for each detail, class name is "answer".When the page is opened first time, you can hide all the details by,   $('.answer').hide();this line can also be written in document.ready method.