Sunday, 17 March 2019

SPList fields using pnp

private GetSPListFields():void
{
pnp.sp.web.lists.getByTitle("Employee").fields.get().then(function(response){

for(let index:number=0;index<response.length;index++)
{
//Show title
console.log("InternalName :"+response[index].InternalName+" StaticName:"+response[index].StaticName+" Title:"+response[index].Title);
}

}).catch(function(exception){
alert("Something went wrong :"+exception);
});
}

SharePoint Lists using pnp



private GetLists():void
{
pnp.sp.web.lists.get().then(function(response){
for(let index:number=0;index<response.length;index++)
{
//Show title
console.log(response[index].Title);
}
});
}

SPfx Crud operation using pnp

import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneDropdown,
PropertyPaneToggle,
PropertyPaneSlider
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import * as jQuery from 'jquery';
import * as pnp from 'sp-pnp-js';
import 'jqueryui';
import{IListItem} from './IListItem';

import styles from './HellowWebpartWebPart.module.scss';
import * as strings from 'HellowWebpartWebPartStrings';

export interface IHellowWebpartWebPartProps {
description: string;
dropdown:string;
}
export interface ISPList {
Id: number;
Title: string;
Salary: string;
Company:string;
Department:string;
}
export default class HellowWebpartWebPart extends BaseClientSideWebPart<IHellowWebpartWebPartProps> {

public render(): void {
this.domElement.innerHTML =`
<div class="${ styles.container }">
<div class="${ styles.container }">
<div class="${ styles.row }">
<div class="${ styles.column }">
<span class="${ styles.title }">CRUD operations</span>
<p class="${ styles.subTitle }">No Framework</p>
<div class="${ styles.container }">
<div class="${ styles.row }">
<div class="${ styles.column }">Item id</div><div class="${ styles.column }"><input type="text" class="${styles.description} itemid"></div>
</div>
<div class="${ styles.row }">
<div class="${ styles.column }">Name</div><div class="${ styles.column }"><input type="text" class="${styles.description} name"></div>
</div>
<div class="${ styles.row }">
<div class="${ styles.column }">Salary</div><div class="${ styles.column }"><input type="text" class="${styles.description} salary"></div>
</div>
<div class="${ styles.row }">
<div class="${ styles.column }">Company</div><div class="${ styles.column }"><input type="text" class="${styles.description} company"></div>
</div>
<div class="${ styles.row }">
<div class="${ styles.column }">Department</div><div class="${ styles.column }"><input type="text" class="${styles.description} department"></div>
</div>
</div>
<br/>
<div class='itemTable'>
</div>
<br/>
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<button class="${styles.button} create-Button">
<span class="${styles.label}">Create item</span>
</button>
<button class="${styles.button} read-Button">
<span class="${styles.label}">Read item</span>
</button>
<button class="${styles.button} update-Button">
<span class="${styles.label}">Update item</span>
</button>
<button class="${styles.button} delete-Button">
<span class="${styles.label}">Delete item</span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>`;
this.setButtonsEventHandlers();

}
private setButtonsEventHandlers(): void
{
const webPart: HellowWebpartWebPart = this;
jQuery(".create-Button").click(function()
{
webPart.createItem();
});
jQuery(".update-Button").click(function()
{
webPart.updateItem();
});
jQuery(".delete-Button").click(function()
{
webPart.deleteItem();
});
jQuery(".read-Button").click(function()
{
webPart.readItem();
});
webPart.readItem();
}
private createItem(): void
{
const webPart: HellowWebpartWebPart = this;
pnp.sp.web.lists.getByTitle("Employee").items.add(
{
Title:jQuery('.name').val(),
Salary:jQuery('.salary').val(),
Company:jQuery('.company').val(),
Department:jQuery('.department').val()
}).then(function(response)
{
webPart.readItem();
alert("Item Added Succes fully")
}).catch(function(exception){

alert("Something went wrong :"+exception);
});
}
private readItem(): void
{
const webPart: HellowWebpartWebPart = this;
pnp.sp.web.lists.getByTitle("Employee").items.getAll().then(function(response)
{
let items: ISPList[]=response;
let html: string = '<table class="TFtable" border=1 width=style="bordercollapse: collapse;">';
html += `<th></th><th>ProfileId</th><th>Name</th><th>Salary</th><th>Company</th><th>Department</th>`;
if (items.length>0)
{
items.forEach((item: ISPList) => {
html += `
<tr>
<td><input type="radio" id="ProfileId" class='profileid' name="ProfileId" value="${item.Id}"> <br> </td>
<td>${item.Id}</td>
<td>${item.Title}</td>
<td>${item.Salary}</td>
<td>${item.Company}</td>
<td>${item.Department}</td>
</tr>
`;
});
}
else
{
html +="No records...";
}
html += `</table>`;
jQuery('.itemTable').html(html);
jQuery('.profileid').click(function()
{
webPart.readListItemById(jQuery(this).val());
});

}).catch(function(exception){
alert("Something went wrong :"+exception);
});
}
private readListItemById(itemid:number):void
{
pnp.sp.web.lists.getByTitle("Employee").items.getById(itemid).get().then(function(response)
{
let item:ISPList=response;
jQuery('.itemid').val(item.Id),
jQuery('.name').val(item.Title),
jQuery('.salary').val(item.Salary),
jQuery('.company').val(item.Company),
jQuery('.department').val(item.Department)
}).catch(function(exception){
alert("Something went wrong :"+exception);
});
}
private updateItem(): void
{
const webPart: HellowWebpartWebPart = this;
pnp.sp.web.lists.getByTitle("Employee").items.getById(jQuery('.itemid').val()).update(
{
Title:jQuery('.name').val(),
Salary:jQuery('.salary').val(),
Company:jQuery('.company').val(),
Department:jQuery('.department').val()
}).then(function(response)
{
webPart.readItem();
alert("Item updated Succesfully");
}).catch(function(exception){

alert("Something went wrong :"+exception);
});


} private deleteItem(): void
{
const webPart: HellowWebpartWebPart = this;
pnp.sp.web.lists.getByTitle("Employee").items.getById(jQuery('.itemid').val()).delete().then(function(response)
{
webPart.readItem();
alert("Item deleted Succesfully");
}).catch(function(exception){
alert("Something went wrong :"+exception);
});;
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}


protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
}),
PropertyPaneDropdown('dropdown', {
label: "City Name",
options:[{key:'1',text:'Saharanpur'},
{key:'2',text:'Banglore'},
{key:'3',text:'Meerut'},
{key:'4',text:'New Delhi'},
{key:'5',text:'Agra'}]
}),
PropertyPaneToggle('toggle',{
label:"Toggle button"
}),
PropertyPaneSlider('Slider',{
label:"Slider",min:1,max:10
})
]
}
]
}
]
};
}
}

Wednesday, 28 November 2018

Update Request Digest Value in sharepoint without making any custom method

Update Request Digest Value in sharepoint without making any custom method ,use Sharepoint inbuilt function


setInterval(function() {
     UpdateFormDigest(_spPageContextInfo.webServerRelativeUrl, _spFormDigestRefreshInterval);
}, 8 * 60000);

it will update the request digest value on every minutes.

Above function is referenced from          "INIT.js"

Sunday, 7 October 2018

implement authentication on WEB API and consume with ajax Call


Below Steps to implement authentication on WEB API and consume with ajax Call

1.       Add a class in model folder  WebApiSecurity” and paste below code
                  using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApiDemo.Models
{
   public class WebApiSecurity
    {
        public static bool VaidateUser(string username, string password)
        {
            // Check if it is valid credential 
            if (true)//CheckUserInDB(username, password)) 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

2.       Create another class for basic authorization “BasicAuthenticationAttributeand paste below code
                 
              using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace WebApiDemo.Models
{
   public class BasicAuthenticationAttribute: AuthorizationFilterAttribute
    {
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
            else
            {
                // Gets header parameters 
                string authenticationString = actionContext.Request.Headers.Authorization.Parameter;
                string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));

                // Gets username and password 
                string usrename = originalString.Split(':')[0];
                string password = originalString.Split(':')[1];

                // Validate username and password 
                if (!WebApiSecurity.VaidateUser(usrename, password))
                {
                    // returns unauthorized error 
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }

            base.OnAuthorization(actionContext);
        }
    }
}

3.       Add Basic Authentication Attribute [BasicAuthentication] on Web API Method like below code
                    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" }
        };
        [BasicAuthentication]
        [HttpGet]
        public IEnumerable<EmployeeDetail> GetAllEmplyees()
        {
return emp;           
        }
       
    }
}





Below steps to consume API with Ajax , Credential parameter like below code

function GetAllEmployees()
    {
                var username="userName";
                var password="user@123";
        var resturl = "http://localhost:44739/api/Employee/";
        resturl += "GetAllEmplyees";
        $.ajax({
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose',
                                                                'Authorization' :'Basic ' + btoa(username + ':' + password)
            },
            async: false,
            success: function (data)
            {
              
                console.log(data)
            }, eror: function (data)
            {
                alert('error');
            }
        });
    }