Monday, July 10, 2023

datetime picker user webpart properties in spfx webpart

In SharePoint Framework (SPFx), you can create a custom web part with properties that allow users to configure settings, including a datetime picker. To implement a datetime picker as a user web part property, you can follow these steps:

  1. Create a new SPFx web part project using the SharePoint Yeoman generator and set up your development environment.

  2. Define the necessary properties in the web part manifest file (webpart.manifest.json) to represent the datetime picker value. For example, you can add a property named selectedDateTime of type DateTimePicker to the properties section of the manifest file:

json
"properties": { "selectedDateTime": { "type": "DateTimePicker", "label": "Selected Date and Time" } }
  1. In your web part's main TypeScript file (MyWebPart.ts), import the necessary dependencies to use the datetime picker control:
typescript
import { PropertyPaneDateTimePicker } from '@microsoft/sp-property-pane'; import { DateTimePicker } from '@pnp/spfx-controls-react/lib/dateTimePicker';

Make sure you have installed the required dependencies using npm or yarn.

  1. Register the property pane control for the datetime picker in the getPropertyPaneConfiguration() method of your web part class:
typescript
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { header: { description: "Web Part Properties" }, groups: [ { groupName: "Settings", groupFields: [ PropertyPaneDateTimePicker('selectedDateTime', { label: "Select Date and Time", showLabels: true, disabled: false, initialDate: this.properties.selectedDateTime || new Date(), formatDate: (date: Date) => { return date.toLocaleString(); }, onPropertyChange: this.onPropertyPaneFieldChanged }) ] } ] } ] }; }

In this example, we're using the PropertyPaneDateTimePicker control from the @microsoft/sp-property-pane package.

  1. Render the selected datetime value in your web part's UI by adding a placeholder element or component:
typescript
public render(): void { const element: React.ReactElement<IMyWebPartProps> = React.createElement( MyWebPartComponent, { selectedDateTime: this.properties.selectedDateTime } ); ReactDom.render(element, this.domElement); }

In the example above, MyWebPartComponent is the component where you want to use the selected datetime value.

  1. Build and package your SPFx solution using the necessary commands (gulp bundle, gulp package-solution).

  2. Deploy and test your web part on a SharePoint page. You should see the datetime picker property in the web part's configuration pane, allowing users to select a date and time.

By following these steps, you can create a datetime picker as a user web part property in SPFx and utilize the selected value within your custom web part.

Thursday, March 18, 2021

Create list item in SharePoint list using REST API

 HttpWebRequest contextinfoRequest =

    (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/contextinfo");

contextinfoRequest.Method = "POST";

contextinfoRequest.ContentType = "text/xml;charset=utf-8";

contextinfoRequest.ContentLength = 0;

contextinfoRequest.Headers.Add("Authorization", "Bearer " + accessToken);


HttpWebResponse contextinfoResponse = (HttpWebResponse)contextinfoRequest.GetResponse();

StreamReader contextinfoReader = new StreamReader(contextinfoResponse.GetResponseStream(), System.Text.Encoding.UTF8);

var formDigestXML = new XmlDocument();

formDigestXML.LoadXml(contextinfoReader.ReadToEnd());

var formDigestNode = formDigestXML.SelectSingleNode("//d:FormDigestValue", xmlnspm);

string formDigest = formDigestNode.InnerXml;


//Execute a REST request to get the list name and the entity type name for the list.

HttpWebRequest listRequest =

    (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/Web/lists(guid'" + listId + "')");

listRequest.Method = "GET";

listRequest.Accept = "application/atom+xml";

listRequest.ContentType = "application/atom+xml;type=entry";

listRequest.Headers.Add("Authorization", "Bearer " + accessToken);

HttpWebResponse listResponse = (HttpWebResponse)listRequest.GetResponse();

StreamReader listReader = new StreamReader(listResponse.GetResponseStream());

var listXml = new XmlDocument();

listXml.LoadXml(listReader.ReadToEnd());


//The entity type name is the required type when you construct a request to add a list item.

var entityTypeNode = listXml.SelectSingleNode("//atom:entry/atom:content/m:properties/d:ListItemEntityTypeFullName", xmlnspm);

var listNameNode = listXml.SelectSingleNode("//atom:entry/atom:content/m:properties/d:Title", xmlnspm);

string entityTypeName = entityTypeNode.InnerXml;

string listName = listNameNode.InnerXml;


//Execute a REST request to add an item to the list.

string itemPostBody = "{'__metadata':{'type':'" + entityTypeName + "'}, 'Title':'" + newItemName + "'}}";

Byte[] itemPostData = System.Text.Encoding.ASCII.GetBytes(itemPostBody);


HttpWebRequest itemRequest =

    (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/Web/lists(guid'" + listId + "')/Items");

itemRequest.Method = "POST";

itemRequest.ContentLength = itemPostBody.Length;

itemRequest.ContentType = "application/json;odata=verbose";

itemRequest.Accept = "application/json;odata=verbose";

itemRequest.Headers.Add("Authorization", "Bearer " + accessToken);

itemRequest.Headers.Add("X-RequestDigest", formDigest);

Stream itemRequestStream = itemRequest.GetRequestStream();


itemRequestStream.Write(itemPostData, 0, itemPostData.Length);

itemRequestStream.Close();


HttpWebResponse itemResponse = (HttpWebResponse)itemRequest.GetResponse();

RetrieveListItems(accessToken, listId);

How to list all sites and subsites in SharePoint Online using PowerShell?

function Get-SPOWebs(){

param(

   $Url = $(throw "Please provide a Site Collection Url"),

   $Credential = $(throw "Please provide a Credentials")

)


  $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)  

  $context.Credentials = $Credential 

  $web = $context.Web

  $context.Load($web)

  $context.Load($web.Webs)

  $context.ExecuteQuery()

  foreach($web in $web.Webs)

  {

       Get-SPOWebs -Url $web.Url -Credential $Credential 

       $web

  }

}

How to read more than 5000 items from document library in SharePoint RestApi?

  1. First call a ajax function with parameters "/_api/Web/Lists/GetByTitle(ListName)/Items?$orderby=Id desc&$top=1". Now you will get the latest added "Id".
  2. Now Divide the Id returned by the ajax by 5000. (Id/5000) So that you will get a result of how many times you need to perform the ajax.
  3. Now you can perform the ajax function repeatedly be filtering every 5000 items, with filter like, $filter=Id ge 0 and Id le 5000, $filter=Id ge 5000 and Id le 10000, ........ , etc.
  4. You can have a foreach loop to perform the ajax repeatedly with a dynamic filter, $filter=Id ge (5000*LoopValue) and Id le (5000*(LoopValue+1)).

Also make sure, the ajax to have async:true, to avoid performance issue. You can store the returned data in array and perform further actions, so that you could store more than 5000 data to perform your functions.

 

 var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('DocumentList')/items?$select=customerID&$top=1000";

    var response = response || [];  // this variable is used for storing list items

    function GetListItems(){

        return $.ajax({

            url: url,  

            method: "GET",  

            headers: {  

                "Accept": "application/json; odata=verbose"  

            },

            success: function(data){

                response = response.concat(data.d.results);

                if (data.d.__next) {

                    url = data.d.__next;

                    GetListItems();

                }

                $.each(response, function(index, item) {

                    arrayCustomerID[index] = item.customerID;

                });

            },

            error: function(error){

            }

        });

    }

Wednesday, March 17, 2021

How to check whether the current user has edit permission for a particular list using JSOM in SharePoint 2013

 we first need to get the login name of user and pass it to the get_effectiveBasePermissions method.


To ensure that user has edit permission, we will check the SP.PermissionKind.editListItems enum.


SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {

    getCurrentUserPermission();

});



function getCurrentUserPermission()

{    

    var web,clientContext,currentUser,oList,perMask;


    clientContext = new SP.ClientContext.get_current();

    web = clientContext.get_web();

    currentUser = web.get_currentUser();   

    oList = web.get_lists().getByTitle('Test List');

    clientContext.load(oList,'EffectiveBasePermissions');

    clientContext.load(currentUser); 

    clientContext.load(web);           


    clientContext.executeQueryAsync(function(){

        if (oList.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems)){

            console.log("user has edit permission");

        }else{

             console.log("user doesn't have edit permission");

        }   

    }, function(sender, args){

        console.log('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());

    });

}

How to get permission of a SharePoint list for a user using RESTApi

 Use EffectiveBasePermissions to get permissions of the user on a list. Example:


/_api/web/lists/getbytitle('L2')/EffectiveBasePermissions

Note that this will give the permissions of the logged in user


function checkPermissions() {

    var call = jQuery.ajax({

        url: _spPageContextInfo.webAbsoluteUrl +

            "/_api/Web/effectiveBasePermissions",

        type: "GET",

        dataType: "json",

        headers: {

            Accept: "application/json;odata=verbose"

        }

    });


    call.done(function (data, textStatus, jqXHR) {

        var manageListsPerms = new SP.BasePermissions();

        manageListsPerms.initPropertiesFromJson(data.d.EffectiveBasePermissions);


        var manageLists = manageListsPerms.has(SP.PermissionKind.manageLists);


        var message = jQuery("#message");

        message.text("Manage Lists: " + manageLists);

    });

}

unable to install SP1 for my sharepoint designer, error “The expected version of the product was not found on the system”

Open Command Prompt use below command


C:\path_of_download_directory\spdsp2013-kb2817441-fullfile-x86-en-us.exe  PACKAGE.BYPASS.DE

Saturday, January 23, 2021

How do I retrieve the value of a lookup-field in a workflow?

 The workflow is looking for a Date and Time field, but lookups return text. You need to return the field as Lookup text.


Set Variable: lookupStart to Current Item:Lookup: Sprint Start Date, Return fields as Lookup Value (as Text)

Last Modified date for site collection?

 Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.Office.Server.Search.Query”)  


[String]$lastDate = "1/1/2018"


foreach($sc in $webapplication | Get-SPSite -Limit All)

{

    Write-Host $sc.Url -ForegroundColor Yellow


    $keywordQuery = New-Object Microsoft.Office.Server.Search.Query.KeywordQuery($sc)

    $keywordQuery.QueryText = "ContentClass:STS_ListItem AND LastModifiedTime>=$($lastDate) AND site:$($sc.Url)"

    $keywordQuery.RowLimit = 5;

    $searchExec = New-Object Microsoft.Office.Server.Search.Query.SearchExecutor

    $searchResults = $searchExec.ExecuteQuery($keywordQuery)


    If( 0 -eq $searchResults.Table.Count ){

        Write-Host "`tSite Collection $($sc.Url) is old" -ForegroundColor Red


}

Sort Order of a Lookup Column in SharePoint?

In this article ,  sort my lookup column based on a column 

 <script type="text/javascript" language="javascript">

    $().SPServices.SPFilterDropdown({ //This is the function that does the sorting.

        relationshipList: "Code", //This is the name of the lookup field in the form.

        relationshipListColumn: "Title", //This is the original column name from the lookup list as SharePoint knows it.

        relationshipListSortColumn: "Sortby"

        columnName: "Code", //This is the column name in the lookup list as it shows up.

        CAMLQuery: "<Neq><FieldRef Name='Title'/><Value Type='Text'></Value></Neq>", //This is the CAML Query if you want to select a specific set of items from the list. In this example it doesn't select items where the Title column is null. Note, the Title column is the original column name.

        debug: true

    });

</script>