Saturday, 6 October 2018

Developing and Consuming WEB API


Below steps to Develop Web API in Visual Studio
1.Create Blank Asp.Net Web Application.
2. Select empty project with Web API.
3.Add a new Class in model as EmployeeDetail and properties as below and paste below code for the same

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApiDemo.Models
{
    public class EmployeeDetail
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }

    }
}

 4. Add New Item in Controller as Empty Web API Controller and paste below code for the same.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiDemo.Models;
namespace WebApiDemo.Controllers
{
    public class EmployeeController : ApiController
    {
        List<EmployeeDetail> emp = new List<EmployeeDetail>()
        {
              new EmployeeDetail {Id="1",Name="Mohd Rizwan", City="Saharanpur" },
              new EmployeeDetail {Id="2",Name="Mohd Jabir", City="Delhi" },
              new EmployeeDetail {Id="3",Name="Mohd Waseem", City="Mumbai" }
        };
        [HttpGet]
        public IEnumerable<EmployeeDetail> GetAllEmplyees()
        {
            return emp;
        }
        [HttpGet]
        public IEnumerable<EmployeeDetail> GetEmployeeById([FromUri]string empid)
        {
            var empList = emp.Where(w => w.Id == empid).ToList();
            return empList;
        }
      
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [HttpPost]
        public HttpResponseMessage AddNewEmployee(EmployeeDetail empd)
        {

            EmployeeDetail s = new EmployeeDetail();
            s.Id = empd.Id;
            s.Name = empd.Name;
            s.City = empd.City;
            emp.Add(s);
            return Request.CreateResponse(HttpStatusCode.OK, emp);
        }
        [System.Web.Http.AcceptVerbs("GET", "PUT")]
        [HttpPut]
        public HttpResponseMessage UpdateEmployee(EmployeeDetail empd, [FromUri]string empid)
        {
            var emps = emp.Where(w => w.Id != empid).ToList();
            EmployeeDetail s = new EmployeeDetail();
            s.Id = empd.Id;
            s.Name = empd.Name;
            s.City = empd.City;
            emps.Add(s);
            return Request.CreateResponse(HttpStatusCode.OK, emps);
        }
        [System.Web.Http.AcceptVerbs("GET", "DELETE")]
        [HttpDelete]
        public HttpResponseMessage DeleteEmployee([FromUri]string empid)
        {
            var emps = emp.Where(w => w.Id != empid).ToList();
            EmployeeDetail s = new EmployeeDetail();
            return Request.CreateResponse(HttpStatusCode.OK, emps);

        }
    }
}

5.Change WebApiConfig under App_Start folder to default response in JSON format and add action after controller in webapiconfig paste below code for the same.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;

namespace WebApiDemo
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());
            

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
    
How to Consume Web API in jQuery

1.      Create HTML page.
2.      Add below code on HTML page.
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
$(document).ready(function()
{
    GetAllEmployees()//Load All Details by default
    $('#btnAdd').click(function () {
        AddNewEmployee();
    });
    $('#btnUpdate').click(function () {
        UPdateEmployeeDetails();
    });
    $('#btnDelete').click(function () {
        DeleteEmployyeById();
    });
    $('#btnGetAll').click(function () {
        GetAllEmployees();
    });
    $('#btnGetById').click(function () {
        GetEmployeeById();
    });

});


    function GetAllEmployees()
    {
        var resturl = "http://localhost:44739/api/Employee/";
        resturl += "GetAllEmplyees";
        $.ajax({
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose'
            },
            async: false,
            success: function (data)
            {
                GenerateHTMLTable(data);
                console.log(data)
            }, eror: function (data)
            {
                alert('error');
            }
        });
    }
      function GetEmployeeById()
    {
      
          var resturl = "http://localhost:44739/api/Employee/";
          resturl += "GetEmployeeById?empid=" + $('#txtId').val();
        $.ajax({
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose'
            },
            async: false,
            success: function (data)
            {
                GenerateHTMLTable(data);
                console.log(data)
            }, eror: function (data)
            {
                alert('error');
            }
        });
    }
      function AddNewEmployee()
    {
        var stringData= JSON.stringify({
            'Id': '5',
            'Name':'Salim',
            'City':'MZN'
        })
        var resturl = "http://localhost:44739/api/Employee/";
        resturl += "AddNewEmployee";
        $.ajax({
                      type:'POST',
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose'
            },
            data: stringData,
            async: false,
            success: function (data)
            {
                GenerateHTMLTable(data);
                console.log(data)
            }, eror: function (data) {

                alert('error');
            }
        });
    }
      function UPdateEmployeeDetails()
    {
          var stringData = JSON.stringify({
            'Id': '5',
            'Name':'Salim',
            'City':'MZN'
        })
          var resturl = "http://localhost:44739/api/Employee/";
          resturl += "UpdateEmployee?empid=" + $('#txtId').val();
        $.ajax({
            type: 'PUT',
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose'
            },
            data:stringData,
            async: false,
            success: function (data)
            {
                GenerateHTMLTable(data);
                console.log(data)
            }, eror: function (data) {

                alert('error');
            }
        });
    }
      function DeleteEmployyeById()
    {
          var resturl = "http://localhost:44739/api/Employee/";
          resturl += "DeleteEmployee?empid=" + $('#txtId').val();
        $.ajax({
                      type:'DELETE',
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose'
            },
            async: false,
            success: function (data)
            {
                GenerateHTMLTable(data);
                console.log(data)
            }, eror: function (data) {

                alert('error');
            }
        });
    }
      function GenerateHTMLTable(data)
      {
          $('.itemCollection').html('');
          if (data.length > 0)
          {
              for (var i = 0; i <data.length; i++)
              {
                  $('.itemCollection').append("<tr><td>" + data[i].Id + "</td><td>" + data[i].Name + "</td><td>" + data[i].City + "</td></tr>");
              }
          }
      }
    </script>
</head>
<body>
    <div>
        <div><input type="text" id="txtId" /></div>
        <div><input type="button" id="btnAdd" value="Add New" /></div>
        <div><input type="button" id="btnUpdate" value="update" /></div>
        <div><input type="button" id="btnDelete" value="Delete" /></div>
        <div><input type="button" id="btnGetAll" value="GetAll" /></div>
        <div><input type="button" id="btnGetById" value="Get By ID" /></div>
        <div></div>
    </div>
  <table width='500px' style='border-collapse: collapse;border: 1px solid #1e7fb8' border='1'>
      <thead><tr style='background-color: #1e7fb8;color:white;'><td>Id</td><td>Name</td><td>City</td></tr></thead>
      <tbody class="itemCollection"></tbody>
  </table>
</body>
</html>

Note:- if you face any challenge in consuming API

Paste below code in web.config file inside <system.webServer>

<httpProtocol>
   <customHeaders>
      <clear />
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
   </customHeaders>
</httpProtocol>





Friday, 31 August 2018

Server-side activities have been updated.

Server-side activities have been updated. You need to restart SharePoint Designer to use the updated version of activities.



Copy following files manually to the locations mentioned below.

Microsoft.SharePoint.WorkflowServices.Activities.Proxy.dll
Microsoft.Web.Design.Client.dll


Download below DLL

for SharePoint Online, you have to copy these files at below location.

%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache\<SiteName>\<VersionNumber>






for SharePoint On-premise, you have to copy these files at below location.



%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache\<SiteName>\<VersionNumber>

Thursday, 9 August 2018

Add New Column in sharePoint Using Powershell


Add New Column in SharePoint Online List using Powershell

1. Create a CSV file add Column in below Format
   
ListName
Name
Type
Required
ChoiceOption
DefaultValue

Below are the supported type

Text
MultiText
Choice     
DateTime
User
UserMulti
Boolean   
Number


Default Value
 for Boolean is 0 or 1 mean No/Yes

and Choice Value will be in comma separated value like Approved,Pending,Rejected

Default Value for Choice is like Rejected


2. Copy below script and paste in .ps1 file 

3. change the site url
4. changes the schema file path

5. Right click on script and Run with powershell



$contentFile ='E:\SharepointOnline\ListLibrarySchema.csv'
$CSVitems = Import-Csv $contentFile
$clientDll =[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
$runtimeDll = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
$url = "https://tenantName.sharepoint.com/sites/SiteName/"
$cred = get-credential
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($cred.username, $cred.password)
$clientContext.Credentials = $credentials
Write-Host "Connected to SharePoint site: '$Url'" -ForegroundColor Green

#Load List
$ListTitle ="CustomListName"
$List = $clientContext.Web.Lists.GetByTitle($ListTitle)

#Load List's exsiting Columns
$Fields = $List.Fields
$clientContext.Load($List)
$clientContext.Load($Fields)
$clientContext.ExecuteQuery()

FOREACH ($CSVitem in $CSVitems)
{
     #Schema Parameter
     $NewColumnName=$CSVitem.Name
     $FieldType=$CSVitem.Type
     $Required=$CSVitem.Required
     $DefaultValue=$CSVitem.DefaultValue
     $ChoiceOption=$CSVitem.ChoiceOption.Split("{,}")

     #Check if the given field name
     $Field = $Fields | where{$_.Title -eq $NewColumnName}

    if(!$Field)
    {
       Write-Host "Column Adding...: '$NewColumnName'" -ForegroundColor yellow
       if($FieldType -eq "Text")
       {
            # Single Line
            $a=$List.Fields.AddFieldAsXml("<Field Type='Text' NumLines='6' Required='$Required' Name='$NewColumnName' DisplayName='$NewColumnName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $List.Update()
            $clientContext.ExecuteQuery()
            Write-Host "Column Added: '$NewColumnName'" -ForegroundColor Green
       }
       if($FieldType -eq "MultiText")
       {
            # MultiLine
            $a = $List.Fields.AddFieldAsXml("<Field Type='Note' Name='$NewColumnName' RichText='FALSE' DisplayName='$NewColumnName' Required='$Required' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $List.Update()
            $clientContext.ExecuteQuery()
            Write-Host "Column Added: '$NewColumnName'" -ForegroundColor Green
        }
         if($FieldType -eq "Choice")
       {
            $OptionCollection=""
            foreach($option in $ChoiceOption)
            {
              $OptionCollection+="<CHOICE>$option</CHOICE>"
            }
            #Choice field
            $a = $List.Fields.AddFieldAsXml("<Field Type='Choice' Required='$Required' Name='$NewColumnName' DisplayName='$NewColumnName' >
                                        <CHOICES>
                                            $OptionCollection
                                        </CHOICES><Default>$DefaultValue</Default></Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $List.Update()
            $clientContext.ExecuteQuery()
            Write-Host "Column Added: '$NewColumnName'" -ForegroundColor Green
        }
         if($FieldType -eq "DateTime")
       {
            # DateTime
            $a = $List.Fields.AddFieldAsXml("<Field Type='DateTime' Name='$NewColumnName' DisplayName='$NewColumnName' Required='$Required' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $List.Update()
            $clientContext.ExecuteQuery()
            Write-Host "Column Added: '$NewColumnName'" -ForegroundColor Green
        }
         if($FieldType -eq "User")
       {
            # SingleUser/People
            $a = $List.Fields.AddFieldAsXml("<Field Type='User' List='UserInfo' Name='$NewColumnName' UserSelectionMode='PeopleOnly' Required='$Required' DisplayName='$NewColumnName'></Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $List.Update()
            $clientContext.ExecuteQuery()
            Write-Host "Column Added: '$NewColumnName'" -ForegroundColor Green
        }
         if($FieldType -eq "MultiUser")
       {
            # MultiUser/People
            $a = $List.Fields.AddFieldAsXml("<Field Type='UserMulti' ShowField='ImnName' DisplayName='$NewColumnName' Name='$NewColumnName' Required='$Required' List='UserInfo' UserSelectionMode='PeopleOnly' Mult='TRUE' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $List.Update()
            $clientContext.ExecuteQuery()
            Write-Host "Column Added: '$NewColumnName'" -ForegroundColor Green
        }
         if($FieldType -eq "Boolean")
        {
            # Yes/No #0 for No and 1 for Yes
            $a = $List.Fields.AddFieldAsXml("<Field Type='Boolean' DisplayName='$NewColumnName' Required='$Required' Name='$NewColumnName'><Default>$DefaultValue</Default></Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $List.Update()
            $clientContext.ExecuteQuery()
            Write-Host "Column Added: '$NewColumnName'" -ForegroundColor Green
        }
        if($FieldType -eq "Number")
        {
            # Yes/No #0 for No and 1 for Yes
            $a = $List.Fields.AddFieldAsXml("<Field Type='Number' DisplayName='$NewColumnName' Required='$Required' MaxLength='255' Name='$NewColumnName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $List.Update()
            $clientContext.ExecuteQuery()
            Write-Host "Column Added: '$NewColumnName'" -ForegroundColor Green
        }
    }
    else
    {
        write-host "Field Exists already!" -ForegroundColor red
    }

}



#Exit Window
Write-Host "Please enter to exit..."
Write-Output
Write-Host "End............"

Monday, 23 July 2018

Graph Access token without login in sharepoint online




function GraphAccessToken()
{
    var deferred = new jQuery.Deferred();
    var requestHeaders = {
        'X-RequestDigest': $("#__REQUESTDIGEST").val(),
        "accept": "application/json;odata=nometadata",
        "content-type": "application/json;odata=nometadata"
    };
    var resourceData = {
        "resource": "https://graph.microsoft.com",
    };
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.OAuth.Token/Acquire",
        headers: requestHeaders,
        type: "POST",
        data: JSON.stringify(resourceData),
        success: function (data) {
            var msGraphToken = data.access_token;
            GetSharedWithMeDocument(msGraphToken);
            deferred.resolve(msGraphToken);
        },
        error: function (jqxr, errorCode, errorThrown) {
            console.log(jqxr.responseText);
            deferred.reject(jqxr.responseText);
        }
    });
    return deferred.promise();
}


function GetSharedWithMeDocument(token)
{
        var odurl = "https://graph.microsoft.com/v1.0/me/drive/sharedWithMe"
       // var thumbnailSize = "large"
      //  var odquery = "?expand=thumbnails,children(expand=thumbnails(select=" + thumbnailSize + "))";
        $.ajax({
            url: odurl,
            dataType: 'json',
            headers: { "Authorization": "Bearer " + token },
            accept: "application/json;odata.metadata=none",
            success: function (data)
            {
                var trCollection = "";
                if (data)
                {
                    for(var itemIndex=0;itemIndex<data.value.length;itemIndex++)
                    {                   
                        trCollection += "<tr><td>" + iconlink + "</td><td>" + data.value[itemIndex].remoteItem.shared.sharedDateTime + "</td><td>" + data.value[itemIndex].lastModifiedBy.user.displayName + "</td></tr>";
                    }
                }
                $("#oneDriveSharedWithTableBody").html('');
                $("#oneDriveSharedWithTableBody").append(trCollection);
            }           
        });
}

Monday, 16 July 2018

Print using Jquery

Print using Jquery





<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var htmlContentPrint="";
$(document).ready(function(){
       $("#btnPrint").click(function () {
        var divPrint = document.getElementById('modelBox');
        var tableElements = $(divPrint).find('.ui.table');
        $(tableElements).each(function (i) {
            $($(tableElements)[i]).attr('style', 'width:100%');
            $($(tableElements)[i]).attr('border', '1');
        });
        var newWindow = window.open('', 'Print-Window');
        newWindow.document.open();
        htmlContentPrint = '<html><head>'+
            '<link type="text/css" media="print,screen" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.min.css"></link></head><body onload="window.print()">' + divPrint.innerHTML + '</body></html>';
        newWindow.document.write(htmlContentPrint);
        newWindow.document.close();
        setTimeout(function () { newWindow.close(); }, 10);
    });
});
</script>

<input id="btnPrint" type="button" value="Print" />
<div id="modelBox">
<table class="ui table">
    <thead>
<tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
</thead>
    <tbody>
<tr>
        <td>John</td>
        <td>Doe</td>
        <td>john@example.com</td>
      </tr>
<tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>mary@example.com</td>
      </tr>
<tr>
        <td>July</td>
        <td>Dooley</td>
        <td>july@example.com</td>
      </tr>
</tbody>
  </table>
</div>

Wednesday, 18 April 2018

Room Availability validation in list


Below method will return true or false

false means room is already booked

true means room is available

var validationflag=CheckAvailabbleRooms("4/30/2018 1:10 AM", "4/30/2018 2:10 AM", "room1");


function CheckAvailabbleRooms(startdatea, endates, roomss)
{

    var val_flag = true;
    var companySiteUrlLink = titanForWork.getQueryStringParameter("CompanySiteUrl");
    var startdateaes = new Date(startdatea);
    var tStart = startdateaes.toISOString();
    var endatestv = new Date(endates);
    var vEnd = endatestv.toISOString();//EndDate
    var filterData = "&$filter=EndDate ge datetime'" + tStart + "' and Rooms eq '" + roomss + "'";
    var listName = 'ListName';
    var siteURL = companySiteUrlLink + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=ID,Title,Rooms,Location,EventDate,EndDate" + filterData;
    console.log(siteURL);
    $.ajax({
        url: siteURL,
        headers: { Accept: "application/json;odata=verbose" },
        async: false,
        success: function (data) {
            var items = data.d.results;
            // alert(items.length);
            for (var index = 0; index < items.length ; index++) {
                if (items[index].EventDate <= vEnd) {
                    val_flag = false;
                    var uuu = new Date(items[index].EventDate);
                    console.log(items[index].ID + "-------" + uuu);
                }
            }
        }, eror: function (data) {
            console.log($('#txtSomethingWentWrong').val());
        }
    });
    return val_flag;
}

Sunday, 8 April 2018

Onedrive Documents using rest api





Get all shared documents with me on onedrive  end point url


https://office365domainname-my.sharepoint.com/_api/v2.0/drive/oneDrive.sharedWithMe








Get all my ondrive documents



https://office365domain-my.sharepoint.com/personal/username_YourO365DomainHere_onmicrosoft_com/_api/Web/GetFolderByServerRelativeUrl('/personal/username_YourO365DomainHere_onmicrosoft_com/Documents')?$select=Files/Name&$expand=Files

Friday, 16 March 2018

Drag Drop in Sharepoint using Jquery


1. Add the Bootstap refrence and Jquery refence



2. Add below html to your file where you want to drag drop files





                                                                           

                                                                               

                                                                                 
                                                                               
                                                                           
                                                                       
                                                                       



3. Call below function on page load or  call after all dependency of other function



function CallDragDropEventFunction()
{
    var targeturl = "http://SiteCollection/web";
    $(".dropzone2").dropzone({
        url: targeturl,
        margin: 20,
        allowedFileTypes: 'image.*, pdf,doc,docx,xlsx,rar,zip,ppt,pptx,dotx,rtf,log,msg,txt,csv,dat,pps,xml,aif,iff,m3u,m4a,mid,mp3,wav,wma,3gp,xls,xlr,zipx',
        params: {
            'action': 'save'
        },
        uploadOnDrop: true,
        uploadOnPreview: false,
        success: function (res, index)
        {
            console.log(res, index);       
        }
    });
}


4. Add below all code in your js file and refrence that js file on HTML  and change the library name and site url in below rest api in javascript function



var callBackTimerArrayList = new Array();
(function ($, window, document, undefined) {
 


    // Create the defaults once
    var pluginName = 'dropzone',
        defaults = {
            width: '100%',                            //width of the div
            height: 42,                            //height of the div
            progressBarWidth: '100%',                            //width of the progress bars
            url: '',                             //url for the ajax to post
            filesName: 'files',                        //name for the form submit
            margin: 0,                              //margin added if needed
            border: '1px dashed #ccc',              //border property
            background: '',
            zIndex: 100,                            //Z index of element
            textColor: '#ccc',                         //text color
            textAlign: 'center',                       //css style for text-align
            text: 'Drop files here to upload',    //text inside the div
            uploadMode: 'single',                       //upload all files at once or upload single files, options: all or single
            progressContainer: '',                             //progress selector if null one will be created
            src: '',                             //if preview true we can define the image src

            dropzoneWraper: 'nniicc-dropzoneParent',        //wrap the dropzone div with custom class
            files: [],                             //Access to the files that are droped
            maxFileSize: '5MB',                         //max file size ['bytes', 'KB', 'MB', 'GB', 'TB']
            allowedFileTypes: '*',                            //allowed files to be uploaded seperated by ',' jpg,png,gif
            clickToUpload: true,                           //click on dropzone to select files old way
            showTimer: false,                           //show time that has elapsed from the start of the upload,
            removeComplete: true,                           //delete complete progress bars when adding new files
            preview: false,                          //if enabled it will load the pictured directly to the html
            uploadOnPreview: false,                          //Upload file even if the preview is enabled
            uploadOnDrop: true,                           //Upload file right after drop
            params: {},                             //object of additional params

            //functions
            load: null,                           //callback when the div is loaded
            progress: null,                           //callback for the files procent
            uploadDone: null,                           //callback for the file upload finished
            success: null,                           //callback for a file uploaded
            error: null,                           //callback for any error
            previewDone: null,                           //callback for the preview is rendered
            mouseOver: null,                           //callback for mouseover event
            mouseOut: null,                           //callback for mouseout event
        };

    // The actual plugin constructor
    function Plugin(element, options) {
        this.element = element;

        // jQuery has an extend method that merges the
        // contents of two or more objects, storing the
        // result in the first object. The first object
        // is generally empty because we don't want to alter
        // the default options for future instances of the plugin
        this.options = $.extend({}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    var xhrDone = {};
    var timers = {};
    var timerStartDate = {};
    var uploadIndex = 0;


    Plugin.prototype.init = function () {
        // Place initialization logic here
        // You already have access to the DOM element and
        // the options via the instance, e.g. this.element
        // and this.options

        $(this.element).css({
            width: this.options.width,
            height: this.options.height,
            border: this.options.border,
            background: this.options.background,
            color: this.options.textColor,
            'text-align': this.options.textAlign,
            'box-align': 'center',
            'box-pack': 'center',
            'z-index': this.options.zIndex
        });

        $(this.element).hover(function () {
            $(this).css("cursor", "pointer");
        }, function () {
            $(this).css("cursor", "default");
        });

        $(this.element).html(this.options.text);

        $(this.element).wrap('
');
        $("." + this.options.dropzoneWraper).css('margin', this.options.margin);
        if (this.options.progressContainer === '') {
            this.options.progressContainer = "." + this.options.dropzoneWraper;
        }

        if (this.options.src) $(this.element).attr('src', this.options.src);

        if (typeof $(this.element).attr('src') !== 'undefined') {
            var src = $(this.element).attr('src');
            $(this.element).attr('src', '');
            var clone = $(this.element).clone();
            $(this.element).css({
                'z-index': this.options.zIndex,
                position: 'absolute'
            }).html('').parent().css('position', 'relative');
            clone.appendTo($(this.element).parent());
            clone.replaceWith('');

            $(this.element).parent().find(".previewImg").css({
                width: this.options.width,
                height: this.options.height,
                border: this.options.border,
                background: this.options.background,
                color: this.options.textColor,
                'text-align': this.options.textAlign,
                'box-align': 'center',
                'box-pack': 'center'
            });
        }

        if (this.options.clickToUpload) {
            $(this.element).parent().append('
');
            var onlyOne = this.options.preview;
            var multile = "";
            if (!onlyOne) multile = "multiple";
            $(this.element).parent().find('form')
            .append('').hide().
            bind('change', function (event) {
                $(this).trigger('submit');
            }).on('submit', function (event) {
                event.preventDefault();
                upload(this, event.target[0].files);
                var input = $(this.element).parent().find('input');

                //input.wrap('
').closest('form').get(0).reset();

                input.unwrap().hide();
            }.bind(this));
        }

        $(this.element).bind({
            dragover: function (e) {
                e.preventDefault();
                e.stopPropagation();
                $(this.element).css({
                    color: '#000',
                    'border-color': '#000'
                });
            }.bind(this),
            dragleave: function (e) {
                e.preventDefault();
                e.stopPropagation();
                dragLeave(this);
            }.bind(this),
            drop: function (e) {
                e.preventDefault();
                dragLeave(this);
                if (!this.options.preview) {
                    upload(this, e.originalEvent.dataTransfer.files);
                } else {
                    upload(this, e.originalEvent.dataTransfer.files);
                }
            }.bind(this),
            click: function (e) {
                if (this.options.clickToUpload) {
                    var el;
                    var form;
                    el = $(this.element).parent().find('input');

                    if (el.parent().prop('tagName') !== 'FORM') {

                        form = $("
");

                        form.bind('change', function () {
                            $(this).trigger('submit');
                        }).on('submit', function (event) {
                            event.preventDefault();

                            upload(this, event.target[0].files);
                            var input = $(this.element).parent().find('input');

                            input.unwrap().hide();
                        }.bind(this));
                        el.wrap(form);
                    }
                    el.trigger('click');
                }
            }.bind(this),
            mouseover: function (e) {
                if (typeof this.options.mouseOver == "function") this.options.mouseOver(this);
            }.bind(this),
            mouseout: function (e) {
                if (typeof this.options.mouseOut == "function") this.options.mouseOut(this);
            }.bind(this)
        });


        if (typeof this.options.load == "function") this.options.load(this);
    };

    function dragLeave(that) {
        var borderColor = that.options.textColor;
        var borderCheck = that.options.border.split(" ");
        if (borderCheck.length == 3) borderColor = borderCheck[2];
        $(that.element).css({
            color: that.options.textColor,
            'border-color': borderColor
        });
    }

    function upload(that, files)
    {
   
        if (that.options.preview) {
            if (!checkFileType(that, files[0])) {
                if (typeof that.options.error == "function") {
                    that.options.error($(that.element), "fileNotAllowed", "File is not allowerd to upload! You can only upload the following files (" + that.options.allowedFileTypes + ")");
                } else
                    alert("File is not allowed to upload! You can only upload the following files (" + that.options.allowedFileTypes + ")");
                return;
            }
            if (!checkFileSize(that, files[0])) {
                if (typeof that.options.error == "function") {
                    that.options.error($(that.element), "fileToBig", 'File to big (' + humanFileSize(files[0].size) + ')! Max file size is (' + that.options.maxFileSize + ')');
                } else
                    alert('File to big (' + humanFileSize(files[0].size) + ')! Max file size is (' + that.options.maxFileSize + ')');
                return;
            }
            var reader = new FileReader();
            $(that.element).parent().find('img').remove();
            $(that.element).css({
                'z-index': that.options.zIndex,
                position: 'absolute'
            }).html('').parent().css('position', 'relative');
            var clone = $(that.element).clone();
            clone.appendTo($(that.element).parent());
            clone.replaceWith('');
            $(that.element).parent().find(".previewImg").css({
                width: that.options.width,
                height: that.options.height,
                border: that.options.border,
                background: that.options.background,
                color: that.options.textColor,
                'text-align': that.options.textAlign,
                'box-align': 'center',
                'box-pack': 'center'
            });
            reader.onload = function (e) {
                $(this.element).parent().find('img').attr('src', e.target.result).show();
                //Image not showing on preview fix
                $(this.element).parent().find('img').height('0%').height('100%');
                if (typeof this.options.previewDone == "function") this.options.previewDone($(this.element));
            }.bind(that);
            reader.readAsDataURL(files[0]);
        }
        var key;
        if (files) {
            that.options.files = files;
            if (that.options.removeComplete) {
                var $removeEls = $(".progress-bar:not(.active)").parents('.extra-progress-wrapper');
                $removeEls.each(function (index, el) {
                    el.remove();
                });
            }
            var i, formData, xhr;
           
            if (that.options.uploadMode == 'single')
            {
                //Reset uploading Count
                callBackTimerArrayList = [];
                // Reset Progress bar
                $('#uploadingDocumentsStatus').hide();
                $('#divprogressBarControl').css("width", "1%");
                $('#divprogressBarControl').text("1%");
                ///////////////Loop on all documents
                for (i = 0; i < files.length; i++)
                {
                    timerStartDate[uploadIndex] = $.now();

                    formData = new FormData();
                    xhr = new XMLHttpRequest();

                    if (!checkFileType(that, files[i]))
                    {
                        callBackTimerArrayList.push('1');
                        addWrongFileField(that, i, uploadIndex);
                        uploadIndex++;
                        reamoveErrorProgressBar();
                        continue;
                    }
                    if (!checkFileSize(that, files[i]))
                    {
                        callBackTimerArrayList.push('1');
                        addFileToBigField(that, i, uploadIndex);
                        uploadIndex++;
                        reamoveErrorProgressBar()
                        continue;
                    }
                    formData.append(that.options.filesName + '[]', files[i]);
                    if (Object.keys(that.options.params).length > 0)
                    {
                        for (key in that.options.params)
                        {
                            formData.append(key, that.options.params[key]);
                        }
                    }
                    if ((!that.options.preview && that.options.uploadOnDrop) || (that.options.preview && that.options.uploadOnPreview))
                    {
                        $('#uploadingDocumentsStatus').show();
                        addProgressBar(that, i, uploadIndex);
                        bindXHR(that, xhr, i, uploadIndex);
                        var targetFolderName = readCurrentTargetUrlCookie("UploadedDocumentTargetFolderURl");
                        $.when(uploadDropedDocuments(targetFolderName, files[i], that.options.url, i, files.length)).done(function (responsecurrentItemId)
                        {

                        });
                        $(".progress").hide();
                        uploadIndex++;
                    }
                }
            }
        }
    }

    function startTimer(i) {
        timers[i] = window.setInterval(function () {
            var $el = $(".upload-timer-" + i);

            var diff = $.now() - timerStartDate[i];

            var sec = diff / 1000;
            var min = 0;
            if (sec >= 60) {
                min = Math.round(sec / 60);
                sec = sec % 60;
            }

            $el.text(min + ":" + pad(sec.toFixed(2), 5));

        }, 10);
    }

    function pad(str, max) {
        str = str.toString();
        return str.length < max ? pad("0" + str, max) : str;
    }

    function bindXHR(that, xhr, i, index) {
        $(xhr.upload).bind({
            progress: function (e) {
                if (e.originalEvent.lengthComputable) {
                    var percent = e.originalEvent.loaded / e.originalEvent.total * 100;
                    if (typeof that.options.progress == "function") that.options.progress(percent, index);
                    else {
                        $(".progress-" + index).children().css("width", percent + "%").html(percent.toFixed(0) + "%");
                    }
                }
            },
            loadstart: function (e, a, b, c) {
                startTimer(index);
            }
        });

        xhrDone[index] = false;

        $(xhr).bind({
            readystatechange: function () {
                if (this.readyState == 4 && this.status == 200) {
                    changeXhrDoneStatus(index);
                    $(".progress.progress-" + index).children().removeClass('active');
                    if (typeof that.options.success == "function") that.options.success(this, index);
                }
            }
        });

        var interval = setInterval(function () {
            if (Object.keys(xhrDone).length > 0) {
                var allOk = {};

                for (var indexT in xhrDone) {
                    if (xhrDone[indexT] === true) allOk[indexT] = true;
                }

                if (Object.keys(xhrDone).length == Object.keys(allOk).length) {
                    clearInterval(interval);
                    xhrDone = {};
                    if (typeof that.options.uploadDone == "function") that.options.uploadDone($(that.element));
                }
            }
        }, 500);
    }

    function changeXhrDoneStatus(i) {
        xhrDone[i] = true;
        clearInterval(timers[i]);
    }

    function addProgressBar(that, i, index) {
        $(that.element).parent()
            .append('
')
            .css({ 'margin': that.options.margin });
        $(".progress-" + index).css({
            width: that.options.progressBarWidth,
            margin: '20px 0 0 0',
        }).append('
').hide();
        $(".progress-" + index).wrap('
');
        //$(".progress-" + index).parent().append(''+that.options.files[i].name.trunc(20)+'').css("width", that.options.progressBarWidth);
        if (that.options.showTimer) {
            $(".progress-" + index).parent().append('0');
        }
    }

    function addFileToBigField(that, i, index) {
        $(that.element).parent()
            .append('
')
            .css('margin', that.options.margin);
        var file = that.options.files[i];
        var fileName = file.name.trunc(25);
        $(".error-progress-" + index).css({
            width: that.options.progressBarWidth,
            margin: '20px 0 0 0'
        }).append('
File to big (' + humanFileSize(file.size) + ')
');
        $(".error-progress-" + index).wrap('
').css("width", that.options.progressBarWidth);
        $(".error-progress-" + index).parent().append('' + fileName + '');
    }

    function addWrongFileField(that, i, index)
    {
        $(that.element).parent()
            .append('
')
            .css('margin', that.options.margin);
        var file = that.options.files[i];
        var fileName = file.name.trunc(25);
        var extension = file.name.substr(file.name.lastIndexOf('.') + 1);
        $(".error-progress-" + index).css({
            width: that.options.progressBarWidth,
            margin: '20px 0 0 0'
        }).append('
File type (' + extension + ') is not allowed
');
        $(".error-progress-" + index).wrap('
').css("width", that.options.progressBarWidth);
        $(".error-progress-" + index).parent().append('' + fileName + '');
    }

    function showTooltip() {
        $("span").tooltip({
            open: function (event, ui) {
                ui.tooltip.css("max-width", '100%');
            }
        });
    }

    function checkFileType(that, file) {
        if (!file.type && file.size % 4096 === 0) return false;
        if (that.options.allowedFileTypes == '*') return true;

        var extension = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();

        var allowedTypes = that.options.allowedFileTypes.replace(' ', '').split(",");
        var allowedTypesLower = [];

        for (var i = allowedTypes.length - 1; i >= 0; i--) {
            if (allowedTypes[i].indexOf(".") != -1) {
                if (file.type.match(allowedTypes[i]) !== null) return true;
            }
            allowedTypesLower.push(allowedTypes[i].toLowerCase());
        }

        if ($.inArray(extension, allowedTypesLower) != -1) return true;

        return false;
    }
    var validAmount = function (n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    };

    var parsableUnit = function (u) {
        return u.match(/\D*/).pop() === u;
    };

    var incrementBases = {
        2: [
          [["B", "Bytes"], 1],
          [["Kb"], 128],
          [["k", "K", "kb", "KB", "KiB", "Ki", "ki"], 1024],
          [["Mb"], 131072],
          [["m", "M", "mb", "MB", "MiB", "Mi", "mi"], Math.pow(1024, 2)],
          [["Gb"], 1.342e+8],
          [["g", "G", "gb", "GB", "GiB", "Gi", "gi"], Math.pow(1024, 3)],
          [["Tb"], 1.374e+11],
          [["t", "T", "tb", "TB", "TiB", "Ti", "ti"], Math.pow(1024, 4)],
          [["Pb"], 1.407e+14],
          [["p", "P", "pb", "PB", "PiB", "Pi", "pi"], Math.pow(1024, 5)],
          [["Eb"], 1.441e+17],
          [["e", "E", "eb", "EB", "EiB", "Ei", "ei"], Math.pow(1024, 6)]
        ],
        10: [
          [["B", "Bytes"], 1],
          [["Kb"], 125],
          [["k", "K", "kb", "KB", "KiB", "Ki", "ki"], 1000],
          [["Mb"], 125000],
          [["m", "M", "mb", "MB", "MiB", "Mi", "mi"], 1.0e+6],
          [["Gb"], 1.25e+8],
          [["g", "G", "gb", "GB", "GiB", "Gi", "gi"], 1.0e+9],
          [["Tb"], 1.25e+11],
          [["t", "T", "tb", "TB", "TiB", "Ti", "ti"], 1.0e+12],
          [["Pb"], 1.25e+14],
          [["p", "P", "pb", "PB", "PiB", "Pi", "pi"], 1.0e+15],
          [["Eb"], 1.25e+17],
          [["e", "E", "eb", "EB", "EiB", "Ei", "ei"], 1.0e+18]
        ]
    };


    function filesizeParser(input) {
        var options = arguments[1] || {};
        var base = parseInt(options.base || 2);

        var parsed = input.toString().match(/^([0-9\.,]*)(?:\s*)?(.*)$/);
        var amount = parsed[1].replace(',', '.');
        var unit = parsed[2];

        var validUnit = function (sourceUnit) {
            return sourceUnit === unit;
        };

        if (!validAmount(amount) || !parsableUnit(unit)) {
            throw 'Can\'t interpret ' + (input || 'a blank string');
        }
        if (unit === '') return amount;

        var increments = incrementBases[base];
        for (var i = 0; i < increments.length; i++) {
            var _increment = increments[i];

            if (_increment[0].some(validUnit)) {
                return amount * _increment[1];
            }
        }

        throw unit + ' doesn\'t appear to be a valid unit';
    }

    function checkFileSize(that, file) {

        return file.size < filesizeParser(that.options.maxFileSize);
    }

    function humanFileSize(bytes) {
        var thresh = 1024;
        if (Math.abs(bytes) < thresh) {
            return bytes + ' Bytes';
        }
        var units = ['KB', 'MB', 'GB', 'TB'];
        var u = -1;
        do {
            bytes /= thresh;
            ++u;
        } while (Math.abs(bytes) >= thresh && u < units.length - 1);
        return bytes.toFixed(1) + ' ' + units[u];
    }
    String.prototype.trunc = String.prototype.trunc || function (n) {
        return this.length > n ? this.substr(0, n - 1) + '…' : this;
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName,
                new Plugin(this, options));
            }
        });
    };

})(jQuery, window, document);

function uploadDropedDocuments(folderName, file, webUrl, currentUploadDocumentsNumber, callBackOnAllDocumentsUploading)
{

    url = webUrl + "/_api/contextinfo";
    $.ajax({
        url: url,
        type: "POST",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        contentType: "application/json;odata=verbose",
        success: function (data)
        {
            var digest = data.d.GetContextWebInformation.FormDigestValue;
            var libraryName = "LibraryName";
            var reader = new FileReader();
            var arrayBuffer;
            reader.onload = function (e) {
                arrayBuffer = reader.result;
                url = webUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderName + "')/Files/add(url='" + file.name + "',overwrite=true)";
                $.ajax({
                    url: url,
                    type: "POST",
                    data: arrayBuffer,
                    headers: {
                        "Accept": "application/json; odata=verbose",
                        "X-RequestDigest": digest
                    },
                    contentType: "application/json;odata=verbose",
                    processData: false,
                    success: function (response)
                    {
                        callBackTimerArrayList.push('1');
                       
                        var percheatgeComplted = (callBackTimerArrayList.length / callBackOnAllDocumentsUploading) * 100;
                        percheatgeComplted = percheatgeComplted.toFixed();
                        $('#divprogressBarControl').css("width" , percheatgeComplted + "%");
                        $('#divprogressBarControl').text(percheatgeComplted + "%");
                        if (callBackTimerArrayList.length == callBackOnAllDocumentsUploading)
                        {
                            GetMyDocumentsWithFilesFolder(folderName);
                            callBackTimerArrayList = [];
                            $('#uploadingDocumentsStatus').hide();
                            $('#divprogressBarControl').css("width","1%");
                            $('#divprogressBarControl').text("1%");
                        }
                        console.log('File Uploaded Succsefully');                     
                    },
                    error: function () {
                        alert("Please try againg something went wrong.");
                    }
                });
            };
            reader.readAsArrayBuffer(file);
        },
        error: function () {
            alert("Please try againg something went wrong.");
        }
    });
 
}
function readCurrentTargetUrlCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}
function reamoveErrorProgressBar()
{
    setTimeout(function () { $('.extra-progress-wrapper').html('');}, 5000);
}