Showing posts with label ClientContext. Show all posts
Showing posts with label ClientContext. Show all posts

Wednesday, March 15, 2023

SharePoint Edit Control Block (ECB) menu or Custom Action Menu In ListItem and Site

 SharePoint Edit Control Block (ECB) menu or Custom Action Menu In ListItem and Site:

<script
  language="javascript"
  type="text/javascript"
  src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"
></script>
<script language="javascript" type="text/javascript">
  $(document).ready(function () {
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", AddCustomUserActionToECB);
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", ModifyUserCustomAction);
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", DeleteUserCustomAction);
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", CreateUserCustomActionSite);
  });

  function AddCustomUserActionToECB() {
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle("testlist");
    var userCustomActionColl = oList.get_userCustomActions();
    var oUserCustomAction = userCustomActionColl.add();
    oUserCustomAction.set_location("EditControlBlock");
    oUserCustomAction.set_sequence(100);
    oUserCustomAction.set_title("Click Here");
    oUserCustomAction.set_url(
      "/sites/pub/Pages/Finance.aspx?ListId={ListId}&ItemId={ItemId}&amp;ItemUrl={ItemUrl}"
    );
    oUserCustomAction.update();
    clientContext.load(userCustomActionColl);
    clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
  }
  function QuerySuccess() {
    console.log("Custom Action added to ECB menu.");
  }
  function QueryFailure() {
    console.log("Request failed - " + args.get_message());
  }

  function ModifyUserCustomAction() {
    var ctx = new SP.ClientContext.get_current();
    var web = ctx.get_web();
    var list = web.get_lists().getByTitle("testlist");
    var CustomActionColl = list.get_userCustomActions();
    ctx.load(list, "UserCustomActions", "Title");
    ctx.executeQueryAsync(
      function () {
        var customActionEnum = CustomActionColl.getEnumerator();
        while (customActionEnum.moveNext()) {
          var custAction = customActionEnum.get_current();
          if (custAction.get_title() == "Click Here") {
            custAction.set_title("Click Here new");
            custAction.update();
            ctx.load(custAction);
            ctx.executeQueryAsync(
              function () {
                alert(
                  "Custom action modified successfully for " + list.get_title()
                );
              },
              function (a, s) {
                alert("Error " + a.get_message());
              }
            );
          }
        }
      },
      function (a, s) {
        alert("Error " + a.get_message());
      }
    );
  }

  function DeleteUserCustomAction() {
    var ctx = new SP.ClientContext.get_current();
    var web = ctx.get_web();
    var list = web.get_lists().getByTitle("testlist");
    var CustomActionColl = list.get_userCustomActions();
    ctx.load(list, "UserCustomActions", "Title");
    ctx.executeQueryAsync(
      function () {
        var customActionEnum = CustomActionColl.getEnumerator();
        while (customActionEnum.moveNext()) {
          var custAction = customActionEnum.get_current();
          if (custAction.get_title() == "Click Here") {
            custAction.deleteObject();
            ctx.load(custAction);
            ctx.executeQueryAsync(
              function () {
                alert(
                  "Custom action deleted successfully for " + list.get_title()
                );
              },
              function (s, a) {
                alert("Error " + a.get_message());
              }
            );
          }
        }
      },
      function (a, s) {
        alert("Error " + a.get_message());
      }
    );

    function CreateUserCustomActionSite() {
      var ctx = new SP.ClientContext.get_current();
      var web = ctx.get_web();
      var CustomActionColl = web.get_userCustomActions();
      var custAction = CustomActionColl.add();
      custAction.set_location("Microsoft.SharePoint.StandardMenu");
      custAction.set_group("SiteActions");
      custAction.set_sequence(101);
      custAction.set_title("site custom action");
      custAction.set_description("Description for custom action.");
      custAction.update();
      ctx.load(web, "Title", "UserCustomActions");
      ctx.executeQueryAsync(
        function () {
          alert("Custom action created successfully for " + web.get_title());
        },
        function (sender, args) {
          alert("Error " + args.get_message());
        }
      );
    }
  }
</script>

<input type="button" value="Create User CustomAction for list" id="create"
    onclick="CreateUserCustomActionList()" /></br ></br >
<input type="button" value="Delete User CustomAction for list" id="Delete"
    onclick="DeleteUserCustomAction()" /></br ></br >
<input type="button" value="Modify User CustomAction for list" id="Modify"
    onclick="ModifyUserCustomAction()" /></br ></br >
<input type="button" value="Create User CustomAction for site" id="Create"
    onclick="CreateUserCustomActionSite()" /></br ></br >
=========================================================
<html>
  <script language="javascript" type="text/javascript">  
    function ClearListItesm(itemID) {
      var ctx = new SP.ClientContext.get_current();
      var web = ctx.get_web();
      var oList = web.get_lists().getByTitle("testlist");
      this.oListItem = oList.getItemById(itemID);
      oListItem.set_item("address", "");
      oListItem.set_item("phone", "");
      oListItem.update();
      ctx.executeQueryAsync(QuerySuccess, QueryFailure);
    }
    function QuerySuccess() {  
        console.log("QuerySuccess");
    }
    function QueryFailure() {        
        console.log("QueryFailure" + args.get_message());
    }
    function getSelectedItemIDs() {
        var items = SP.ListOperation.Selection.getSelectedItems();
        items.forEach(item => {
            console.log(item.id);
            ClearListItesm(item.id);
        });
        location.reload();
    }
  </script>
  <input type="button" value="delete" id="update" onclick="getSelectedItemIDs()"/></br>
</html>
=========================================================

Thursday, December 17, 2015

Authenticating .NET Client Object Model CSOM in Office 365 in SharePoint 2013

Authenticating .NET Client Object Model CSOM in Office 365 in SharePoint 2013
--------------------------------------------------------
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            const string webUrl = "https://sreekanth2.sharepoint.com/";
            const string USER = "sreekanth@sreekanth2.onmicrosoft.com";
            const string PWD = "password";
            var listInfo = ""; 
            using (ClientContext clientContext = new ClientContext(webUrl))
            {
                SecureString passWord = new SecureString();
                foreach (char c in PWD.ToCharArray())
                {
                    passWord.AppendChar(c);
                }
                clientContext.Credentials = new SharePointOnlineCredentials(USER, passWord);
                Microsoft.SharePoint.Client.List spList = clientContext.Web.Lists.GetByTitle("Temperature");
                clientContext.Load(spList);
                clientContext.ExecuteQuery();
                if (spList != null && spList.ItemCount > 0)
                {
                    Microsoft.SharePoint.Client.CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = @"<View><Query><Where><IsNotNull><FieldRef Name='ID' /></IsNotNull></Where><OrderBy><FieldRef Name='ID' /></OrderBy></Query><ViewFields><FieldRef Name='ID' /><FieldRef Name='City' /><FieldRef Name='Month' /><FieldRef Name='Temperature' /></ViewFields></View>";
                    SP.ListItemCollection listItems = spList.GetItems(camlQuery);
                    clientContext.Load(listItems);
                    clientContext.ExecuteQuery();
                    listInfo += "<table border='1'><tr><td>ID</td><td>City</td><td>Month</td><td>Temperature</td></tr>";
                    foreach (SP.ListItem oListItem in listItems)
                    {
                        listInfo += "<tr><td>" + oListItem.Id + "</td><td>" + oListItem["City"] + "</td><td>" + oListItem["Month"] + "</td><td>" + oListItem["Temperature"] + "</td></tr>";
                    }
                    listInfo += "</tr></table>";
                    div1.InnerHtml = "List Items found:<br/>" + listInfo;
                }
            }
        }
    }
}
--------------------------------------------------------
--------------------------------------------------------

Bulk Upload Files to SharePoint remotely using CSOM in SharePoint Online

Bulk Upload Files to SharePoint remotely using CSOM in SharePoint Online
Using PowerShell: https://gallery.technet.microsoft.com/PowerShell-Bulk-Upload-b9e9d600
------------------------------------------------------------------------------------------------
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
using System;
using System.IO;
using System.Linq;
using System.Security;
namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        const string webUrl = "https://sreekanth2.sharepoint.com/";
        const string USER = "sreekanth@sreekanth2.onmicrosoft.com";
        const string PWD = "Password";
        const string parent_dir = @"D:\ToUploadFilesFolder";
        const string listTitle = "MyDocuments"; // Library Display Name and Url should be same.
        public string parent_folderName = "";
        public string sub_folderName = "";
        public string fileName = "";
        public string file_relativeUrl = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            using (ClientContext clientContext = new ClientContext(webUrl))
            {
                SecureString passWord = new SecureString();
                foreach (char c in PWD.ToCharArray())
                {
                    passWord.AppendChar(c);
                }
                clientContext.Credentials = new SharePointOnlineCredentials(USER, passWord);
                var arrayfolderName = parent_dir.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                parent_folderName = arrayfolderName[arrayfolderName.Length - 1];
                if (!FolderExists(clientContext.Web, listTitle, parent_folderName))
                {
                    CreateFolder(clientContext.Web, listTitle, parent_folderName);
                }
                DirSearch(clientContext, parent_dir);
            }
        }
        private void DirSearch(ClientContext clientContext, string dir)
        {
            try
            {
                foreach (string f in Directory.GetFiles(dir))
                {
                    fileName = f.Split(new string[] { dir }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("\\", "/");
                    file_relativeUrl = parent_folderName + "/" + f.Split(new string[] { parent_dir + "\\" }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("\\", "/");
                    //div1.InnerHtml += "/" + file_relativeUrl + "</br>";
                    using (FileStream fs = new FileStream(dir + "\\" + fileName, FileMode.Open))
                    {
                        SP.File.SaveBinaryDirect(clientContext, "/" + listTitle + "/" + file_relativeUrl, fs, true);
                    }
                }
                foreach (string d in Directory.GetDirectories(dir))
                {
                    sub_folderName = d.Split(new string[] { parent_dir + "\\" }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("\\", "/");
                    //div1.InnerHtml += parent_folderName + "/" + sub_folderName + "</br>";
                    if (!FolderExists(clientContext.Web, listTitle, parent_folderName + "/" + sub_folderName))
                    {
                        CreateFolder(clientContext.Web, listTitle, parent_folderName + "/" + sub_folderName);
                    }
                    DirSearch(clientContext, d);
                }
            }
            catch (System.Exception ex)
            {
                div1.InnerHtml += ex.Message + " " + ex.StackTrace;
            }
        }
        public static bool FolderExists(Web web, string listTitle, string folderUrl)
        {
            var list = web.Lists.GetByTitle(listTitle);
            var folders = list.GetItems(CamlQuery.CreateAllFoldersQuery());
            web.Context.Load(list.RootFolder);
            web.Context.Load(folders);
            web.Context.ExecuteQuery();
            var folderRelativeUrl = string.Format("/{0}/{1}", list.RootFolder.Name, folderUrl);
            return Enumerable.Any(folders, folderItem => (string)folderItem["FileRef"] == folderRelativeUrl);
        }
        private static void CreateFolder(Web web, string listTitle, string folderName)
        {
            var list = web.Lists.GetByTitle(listTitle);
            var folderCreateInfo = new ListItemCreationInformation
            {
                UnderlyingObjectType = FileSystemObjectType.Folder,
                LeafName = folderName
            };
            var folderItem = list.AddItem(folderCreateInfo);
            folderItem.Update();
            web.Context.ExecuteQuery();
        }
    }
}
------------------------------------------------------------------------------------------------

Thursday, May 7, 2015

Invalid data has been used to update the list item. The field you are trying to update may be read only | The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested

Issue1: Invalid data has been used to update the list item. The field you are trying to update may be read only.

Issue2: The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

Problem Code:
internal static Void GetFileFromTempDocLib(ClientContext clientContext1)  
{
                var folderRelativeUrl = "";
                Web web = clientContext.Web;                
                clientContext.Load(web, w1 => w1.ServerRelativeUrl, w1 => w1.Url);
                clientContext.ExecuteQuery();
                folderRelativeUrl = web.ServerRelativeUrl;

}

Solution Code:
internal static Void GetFileFromTempDocLib(ClientContext clientContext1)  
{
                var folderRelativeUrl = "";
                Web web = clientContext.Web;
                try
                {
                    folderRelativeUrl = web.ServerRelativeUrl;
                }
                catch (PropertyOrFieldNotInitializedException ex)
                {
                    clientContext.Load(web, w1 => w1.ServerRelativeUrl, w1 => w1.Url);
                    clientContext.ExecuteQuery();
                    folderRelativeUrl = web.ServerRelativeUrl;
                }
}

Featured Post

Mention a Channel or Team – Power Automate

Mention a Channel or Team – Power Automate graph.microsoft.com/v1.0/teams/{teamId}/channels/{channelId}/messages Channel: ---------- {   &qu...

Popular posts