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>