Tuesday, March 6, 2018

Sitecore MVC Routing using sitecore pipelines approach

Case Study:

It is very important to separate CMS and CD level MVC routing . When we deploy CD content delivery for any web then it should have very specific routing for the web and most of the cms specific routing should be entrusted to cms solution. It is simple you move all the cms level custom route to custom library and later reference and allow to run at runtime using config patch specific to environment. Like SiteSetting.CMS.Config vs SiteSetting.CD.Config this is will part of continous deployment where it will be picked up during depployment to specific cms and CD environment. By doing this we are separating the responsibility and it help maitain consistent approach specific to cms and cd. This also good for performance of application and it will not conlict with web solution specific to its functionality.

CD with specific to web page
Say http://abc.com/homepage which internally call api via ajax -xhr request say http://abc.com/abc/api/home/Get

CMS with specific to admin or shell page
http://abc.cms/sitecore/admin/api/user this is very specific to cms

Now when you are employing this solution in MVC ensure it is separated for each of this environment. The cms web server will have routing logic loaded at runtime specific to its env without adding extra overload to web CD environment.

Implementation Logic

Monday, March 5, 2018

Keyvault access :Certificate give permission to Protected item


If you are working with keyvault, ensure you import client certificate with proper permission for it to work properly in your development or local machine. This is most common error and you won't be able to figure out the issues unless you create standalone console app to troubleshoot. The keyvault will always fail at this method and it goes in infinite loop.
public async Task<string> GetAccessToken(string authority, string resource, string scope)
           var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
           var result = await context.AcquireTokenAsync(resource, _clientAssertionCert);
           return result.AccessToken;



Important Note:

Web application may not prompt you with above security pop-up unlike console application.


Run ->type  MMC
Go to your user personal certificate and delete existing certificate that is application specific and import again with below checkbox status in place.

Thursday, March 1, 2018

Calculate distance between two Geo location using Google Map API


In order to run this proof of concept , we need google api  key,API_Key This can be obtain as per your personal google account credential. create project in developer console in google and generate api_key for you to create proof of concept to consume google api.

Try Out Proof of concepts: Hosted in JSFiddler

Google Developer Console Login

Create Project in Google API Console

Google Distance Matrix API

Google Autocomplete Location API

Production Implication

Create account for BUPA or contact IS support for the same.

Key Implementation things to note

  • Use new google.maps.DistanceMatrixService(); for recommended route.
  • The below example can be useful to find distance for multiple source and destination location
  • You can limit auto complete or restrict to specific countries.   destinationautocomplete.setComponentRestrictions({
  •     'country': ['aus']
  • Use new google.maps.DirectionsService() to calculate alternative routes with legs and steps directions
  • Property setting optimizeWaypoints: true gives accurate distance remove complexity such as turns and other criteria
  • Property setting provideRouteAlternatives: true, helps you find all route path options
  • It used traveling salesman algorithm for optimal map routing with google maps.->optimizeWaypoints

Code Base Implementation

Tuesday, February 6, 2018

MVC File Upload using Client side and Server Side

Purpose :-

We can achieve file upload either using any of the below options

  • File Upload using html input file field with Jquery Ajax to call server side web api
  • File Upload using MVC Razor Html.BeginForm to call asp.net mvc acction controller or web api
Below code base cover above implementation.

Key technical specifications :-

  1. Enctype =multipart/form-data
  2. List if using out of box asp.net
  3. Request.Form pass through Ajax Jquery or some sort of js library to read file in asp.net
  4. MultiPartFormBoundary 
  5. ContentType MediaTypeHeaderValue("application/octet-stream")


Tuesday, January 23, 2018

Dynamically load partial view using mvc action controller

As we all know we can have partial views to do many thing. Here is one of the scenario. Say we have different workflow based on operation selection. Either we have static partial views with full pledge workflow embedded in it or you load workflow as partial view dynamically.


With Dynamic Approach

  1. We can inject partial view at runtime
  2. The mark up will be lean and light as it will be on-demand load.

For proof of concept I choose existing Asp.net MVC razor from vs.




@model WebApplication3.Models.FullAndPartialViewModel
    ViewBag.Title = 
"My Master Page";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function () {
"p").click(function () {
var categoryId = $("#ddlCategory").val();

"#dvCategoryResults").load("/home/InitiateWorkflow", { categoryId: categoryId });
"#ddlCategory").change(function () {
var categoryId = $("#ddlCategory").val();

            // $("#dvCategoryResults").load('@(Url.Action("GetCategoryProducts","Home",null, Request.Url.Scheme))?categoryId=' + categoryId);
//  $("#dvCategoryResults").load("/home/InitiateWorkflow", { categoryId: categoryId});
<div id="container">
<label for="ddlCategory"><strong>Select a category</strong></label>
@Html.DropDownListFor(m => m.CategoryId,
new SelectList(Model.CategoryList, "CategoryId""CategoryName", Model.CategoryId), new { id = "ddlCategory", @class = "test" })
<br /><br />
<div id="dvShowSubmissionCriteria" hidden="hidden">
<p>This is submission criteria. Please accept before you proceed</p>
<p><strong>Click here to start Workflow -->.</strong></p>
<div id="dvCategoryResults">



using System.Collections.Generic;
namespace WebApplication3.Models
public class FullAndPartialViewModel
public int CategoryId { getset; }
public List<CategoryListItem> CategoryList { getset; }
public class  CategoryListItem
public int CategoryId { getset; }
public string CategoryName { getset; }


using System.Web.Mvc;
using WebApplication3.Models;
namespace WebApplication3.Controllers
public class HomeController : Controller
public ActionResult Index()
return View();
public ActionResult About()
            ViewBag.Message = 
"Your application description page.";
FullAndPartialViewModel viewModel = new FullAndPartialViewModel();
            viewModel.CategoryList = 
new System.Collections.Generic.List<CategoryListItem>();
new CategoryListItem() { CategoryId = 1, CategoryName = "Service Operation 1" });
new CategoryListItem() { CategoryId = 2, CategoryName = "Service Operation 2" });
return View(viewModel);
public PartialViewResult InitiateWorkflow(int categoryId)
var service = new Service();
if (categoryId == 1)
                service.Name = 
"Workflow 1";
                service.Value = 
"I got 5 Steps!";
return PartialView("~/Views/Home/_WF1.cshtml", service);
                service.Name = 
"Workflow 2";
                service.Value = 
"I got 100 Steps!";
return PartialView("~/Views/Home/_WF2.cshtml", service);



namespace WebApplication3.Models
public class Service
public string Name { getset; }
public string Value { getset; }

Partial View Workflow 1: _WF1.cshtml


@using WebApplication3.Models
@model Service

Partial View Workflow 2: _WF2.cshtml


@using WebApplication3.Models
@model Service



Machine generated alternative text:
Application name Home About 
Select a category Service Operation 2 
This is submission criteria. Please accept before you proceed 
Click here to start Workflow 
Workflow 2 
I got 100 Steps! 
C 2018 MY ASRNET Application

Monday, December 18, 2017

Powershell Read XML config


  1. Read XML file
  2. Global variable

You can download code from gist.

Tuesday, December 12, 2017

Powershell Set IIS apppool custom identity credential

import-module webadministration

function Set-WebsiteAppPoolCustomIdentity([String] $appPoolName, [String] $userId, [String] $pwd)

    Write-Host $appPoolName;
    $webAppPool = get-item IIS:\AppPools\$appPoolName     
    $webAppPool.processModel.userName = $userId;
    $webAppPool.processModel.password = $pwd;
    $webAppPool.processModel.identityType = 3;
    $webAppPool | Set-Item
    Write-Host "IIS Recycled";
    $webAppPool = get-item iis:\apppools\$appPoolName;
    write-host "New Pool User: " $webAppPool.processModel.userName;
    write-host "New Pool PWd: " $webAppPool.processModel.password;

Set-WebsiteAppPoolCustomIdentity  -appPoolName "abc" -userId "hello" -pwd "world"