MVC Ajax File Upload in Sitecore Programmatically using API calls

here I’m going to explain about uploading the file directly into Sitecore media library programmatically. below is the list of steps will be following to Upload the file to Sitecore

  • Coding cshtml & Ajax API calls
  • Coding to Create the Month & Year Wise Folders to store the uploading images
  • code to publish the created folders.

Code cshtml & Ajax API calls

Create a cshtml and add the following list of Code

<input type=”file” id=”FileUpload1″ />
<input type=”button” id=”btnUpload” value=”Upload Files” />

and then create a separate javascript file and add the following ajax API call functionality, it will help to pass the attached file to the form and it can also send the other input data

$(document).ready(function () {
$(‘#btnUpload’).click(function () {

// Checking whether FormData is available in browser
if (window.FormData !== undefined) {

var fileUpload = $(“#FileUpload1”).get(0);
var files = fileUpload.files;

// Create FormData object
var fileData = new FormData();

// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);

// Adding one more key to FormData object
fileData.append(‘username’, ‘Manas’);

url: ‘/Home/UploadImage’,
type: “POST”,
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
error: function (err) {
} else {
alert(“FormData is not supported.”);

Create the Action Result and add the below code to Upload an Image,


Code to create Sitecore Folder programmatically


Code to attach the File to Sitecore Media Library



Code to Publish the newly Inserted media items 


Final View of the uploaded Images 



TDS Auto Code Generation Issues

As part of my development activity, I have created one WFFM form under the Global Section under the home node.

I need to access the WFFM fields to access the data entered into the text box field. So synced the tds items but the respective code is not generated. Tried more than 10 times but the automatic code is not generated.

Then checked with my colleague, he gave the clue.

Solution: During the initial configuration, by default Other than templates all the other items code generation is disabled, In my case its Global item, to generate the Code follow the below steps

  1. Right-click on the Sitecore Item and select properties
  2. Select the Code generation template drop-down and select the respective template
  3. In my case it’s, After selecting, TDS code is generated automatically.

Glass Mapper – Initial Setup issues

After installing glass mapper, If your getting warnings on RenderImage, IsEditable ,RenderLink or any other glassmapper objects.


The Type ‘Expression<>’ is defined in an assembly that is not referenced. You must add a reference to assembly “System.Core, Version=, Culturalneutral,PublicKeyToken”

Then make sure to add the below line Under <System.WebServer> <assemblies>

<add assembly=”System.Core, Version=, Culture=neutral, PublicKeyToken=B77A5C561934E089″/>

After that close and re-open the solution, it will resolve the warnings now. Make sure to use the appropriate assembly version for system.core

Bundling with Sitecore 6.5 to 8.2 + versions of Sitecore MVC4 bundling and minification it helps to avoid the repeated request to Servers and enables caching the data into server Memory.

I have got a chance to implement bundling in two Sitecore Versions

  • Sitecore 6.5 (Web Forms)
  • Sitecore 8.1 (MVC)

Let’s See how to implement bundling in Sitecore 6.5

Bundling in Sitecore 6.5 to  8.1 version

1)Open NuGet packet manager and execute the below command

2)Create a Class and add the .css file and .js file path as like below

3)Open Global.asax.cs file and open Application Start Event and add your bundling class

4)add the Script bundle and style bundle into the IgnoreUrlPrefixes as like below

5) Now remove the actual reference of your css &js files inside the code and add the below code to refer the files

Below is the reference in case of Web forms

 Bundling in Sitecore 8.2 and greater version

Sitecore removed the functionality of Global.asax.cs Application_Start event from Sitecore 8.2 onwards because its Inheriting Sitecore.Web.Application.  So we need to use the sitecore pipeline approach as per the blog post as below.

I already implemented bundling using Sitecore Pipeline as per the below blog post , its working absolutely fine


Azure bacpac restoring Issues & resolutions

There are two issues faced by me during restoring the bacpac file.

ERROR 1: Create User with Password

Could not import package Error:SQL72045 script execution error. CREATE USER [usersample] WITH PASSWORD = sasaas%$##$#$#$#$#$

To resolve the above issue, this property is missing in bacpac azure DB export.

1.Rename your .bacpac file to .zip

2.Export the zip content to a new folder

3.Modify the model.xml and add <Property Name=”Containment” Value=”1″ />

4.its the time to change the check sum

  1. download dacchksum.exe from this url
  2. 6. Copy dacchksum.exe in the same directory as .bacpac resides

7.Open Command Prompt and then navigate to the old directory, then execute the following command to generate the new check sum

Command: dacchksum.exe /i:Azurebackup.bacpac

Copy the checksum values from Calculated:[]

  1. open origin.xml then add the new Checksum then save the file.
  2. Compress the folder as zip then rename the .zip to .bacpac
  3. its done. You can start importing in Sql Server 2016 successfully


This is second error faced in restoring the bacpac file.

Could not import package.
Error SQL72014: .Net SqlClient Data Provider: Msg 15578, Level 16, State 1, Line 1 There is already a master key in the database. Please drop it before performing this statement.
Error SQL72045: Script execution error. The executed script:


to resolve this issue Follow Option 2 from


MongoDb Installation

  1. Navigate to MongoDB Download and download community edition.
  2. Make sure to install Mongo Compass, its a separate tool and its similar to RoboMongo, and it has lot of functionalities
  3. Usually do the custom Installation inside c:\mongodb
  4. after the installation Create three folders, as below
    1. c:\mongodb\data

    2. c:\mondodb\data\db

    3. c:\mongodb\logs

  5. Open Command prompt in admin mode and enter the below command
    1. cd c:\monogodb\bin

  6. Install Mongo db as service,Execute the below command
    1. mongod.exe –dbpath=”c:\mongodb\data\db” –logpath=”c:\mongodb\logs\mongo.log” –install

  7. Open Services.Msc and find MongoDB click Start to start the service
  8. To verify MongoDb is running properly, Navigate to  c:\mongodb\logs and check any errors.

Migrating the Sitecore Website from Old URL to New URL

Recently we have received the request from client that they are are going for brand conversion, i.e they want to move from their current website to the new website

They want all the request to be redirected from old website to the new website with the entire URL  for eg: they wanted to take care of the below conversion
If the user is Visiting it should be automatically redirected to the new website

IIS Changes
it can be easily achieved by leveraging the Existing IIS functionality – URL-Rewrite module.

by default, IIS doesn’t have this functionality. You have to install this extension from this URL

After installing this module, You can verify this installation in IIS , make Sure URL Rewrite Module is appearing.

  • add the below code inside the web.config  , Inside the <System.WebServer> tag<rewrite>
                    <rule name=”TestRedirect” stopProcessing=”true”>
                        <conditions logicalGrouping=”MatchAny” trackAllCaptures=”false”>
                            <add input=”{HTTP_HOST}” pattern=”www\.oldwebsite\.com” />
                            <add input=”{HTTP_HOST}” pattern=”oldwebsite\.com” />
                        <action type=”Redirect” url=”{R:1}” redirectType=”Permanent” />
            </rewrite>this above rule will take care of automatic redirection  your website request from to newwebsite.comSitecore Changes
  • App_Config/Include/UrlResolver.config  – CM & CD
  • App_Config\Include\SitemapXML.config – CM
  • Sitemap.xml – Regenerate SiteMap
  • Robot.txt
  • URLResolver.config – CM & CD

inside the App_Config/Include/UrlResolver.config add your as like below

<setting name=”SitecoreModule.UrlResolver.ExcludedRedirects” value=”localhost,,” />
<setting name=”SitecoreModule.UrlResolver.ForceWWW” value=”,” />

the above changes are applicable to both CM and CD.

SitemapXML.Config – CM(Content Management)
Inside App_Config\Include\SitemapXML.config
<site name=”website” filename=”sitemap.xml” serverUrl=”” />

Your current sitemap is generated with the all your links, you have to regenerate the sitemap.xml to generate all the links with the

Update robots.txt to use the , So that Search Engine will start crawling the new website links


Sitecore Content & Design Changes
Before doing all the above changes, Take the copy of production DB and restore into staging environment, Do all the content changes and during the production roll restore the Staging Database into production and replace the necessary Styles and images changes _CSS and _Images folder