Friday, April 5, 2019

Get ID of an inserted list item via CSOM



// Get library columns collection.  
                        var libFields = list.Fields;
                        clientContext.Load(libFields);
                        clientContext.ExecuteQuery();

                        Microsoft.SharePoint.Client.File newFile = clientContext.Web.GetFileByServerRelativeUrl(fileUrl);
                        ListItem item1 = newFile.ListItemAllFields;
                        var fileN = fileName;
                        clientContext.Load(item1);//Load the new item
                        clientContext.ExecuteQuery();
                       // Console.WriteLine("ID of new item:{0}", newItem.Id);//Get ID 

item1.Id

You can refer below sample:
ClientContext context = new ClientContext("http://SiteUrl"); 
List listObj = context.Web.Lists.GetByTitle("ListName"); 
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); 
ListItem newItem = listObj.AddItem(itemCreateInfo); 
newItem["Title"] = "My New Item!"; 
newItem.Update(); 
context.Load(newItem);//Load the new item
context.ExecuteQuery();  
Console.WriteLine("ID of new item:{0}", newItem.Id);//Get ID 

Wednesday, January 23, 2019

Caml & Get access to SP using tokenhelper in webapi

//camlQuery.ViewXml = @"<View Scope='Recursive'><Query></Query></View>";// to get only files
                    //camlQuery.ViewXml = @"<View Scope='RecursiveAll'><Query></Query></View>"; // to get all folders with files
                    //ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllFoldersQuery());




[HttpGet]
        [Route("api/GetRootFolders")]
        public List<SPItem> GetRootFolders()
        {
            //first connect to sharepoint online
            List<SPItem> allItems = new List<SPItem>();
            //first connect to sharepoint online
            string spSiteURL = ConfigurationManager.AppSettings["SharePointURL"];
            Uri siteUrl = new Uri(spSiteURL);
            string realm = TokenHelper.GetRealmFromTargetUrl(siteUrl);
            string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUrl.Authority, realm).AccessToken;

            try
            {
                using (var clientContext = TokenHelper.GetClientContextWithAccessToken(siteUrl.ToString(), accessToken))
                {

                    Web web = clientContext.Web;
                    // We want to retrieve the web's properties.
                    clientContext.Load(web);
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();
                    clientContext.Load(web.CurrentUser);
                    clientContext.ExecuteQuery();
                    string username = web.CurrentUser.LoginName;
                    string webName = web.Title;
                    var list = web.Lists.GetByTitle(ConfigurationManager.AppSettings["LibName"]);
                    clientContext.Load(list);
                    clientContext.ExecuteQuery();
                    CamlQuery camlQuery = new CamlQuery();
                 
                    ListItemCollection listItems = list.GetItems(camlQuery);
                    clientContext.Load<ListItemCollection>(listItems);
                    clientContext.ExecuteQuery();
                    foreach (var item in listItems)
                    {
                        if (item.FileSystemObjectType != FileSystemObjectType.File)
                        {
                            SPItem itemCol = new SPItem();
                            itemCol.Name = item["FileLeafRef"].ToString();
                            itemCol.IsFolder = "Yes";
                            allItems.Add(itemCol);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var errmsg = ex.Message;
            }
            return allItems;
        }

Friday, January 4, 2019

Azure SharePoint WebApi Example code

using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Security;
using System.IO;
using System.Text;
using SpoWebApi.Models;
using System.Collections;
using Newtonsoft.Json;
using System.Web.Script.Serialization;

namespace SpoWebApi.Controllers
{
    public class SparksController : ApiController
    {
        [HttpGet]
        [Route("api/hello")]
        public HttpResponseMessage HelloWorld()
        {
            string result = "Hello world! Time is: " + DateTime.Now;
            var resp = new HttpResponseMessage(HttpStatusCode.OK);
            resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
            return resp;
        }
        [HttpGet]
        [Route("api/UpdateSharePoint")]
        public IHttpActionResult GetSparksDataUpdateSharePointList()
        {
            // this should process the order asynchronously
            var tasks = new[]
            {
            Task.Run(() => processMethod())
            };
            return Ok("ok");
        }
        public void processMethod()
        {
            string sharePointUrl = ConfigurationManager.AppSettings["SharePointURL"];
            var requestUrl = ConfigurationManager.AppSettings["getResourceUri"];
            var _sparkVMSKey = ConfigurationManager.AppSettings["vmsAppKey"];
            var _sparkServiceReqKey = ConfigurationManager.AppSettings["serviceReqResKey"];
            //var _sparksrcAppKey = ConfigurationManager.AppSettings["srcAppKey"];
            string _spUserName = ConfigurationManager.AppSettings["userName"];
            string _spPwd = ConfigurationManager.AppSettings["Password"];
            string _spListName = ConfigurationManager.AppSettings["listName"];
            Stream dataStream;
            WebResponse response;
            string responseFromServer;
            StreamReader reader;
            responseFromServer = "";
            reader = null;
            dataStream = null;
            response = null;
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var _ErrorLogPath = "/TestMapPath";
            var returnMessage = "";
            ArrayList myAL = new ArrayList();
            string postData = string.Format("destAppKey=" + _sparkVMSKey + "&resKey=" + _sparkServiceReqKey);//required for sendTO + "&srcAppKey=" + _sparksrcAppKey

            try
            {
                ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; };
                WebRequest request = WebRequest.Create(requestUrl);
                request.Method = "POST";
                // string postData = dataPost;
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                response = request.GetResponse();
                dataStream = response.GetResponseStream();
                reader = new StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
                Result sparksResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Result>(responseFromServer);
                string webTitle = "";
                if (sparksResult.sparksResponse.status)
                {
                    foreach (Datum outData in sparksResult.sparksResponse.data)
                    {
                        Resdata sparksResData = Newtonsoft.Json.JsonConvert.DeserializeObject<Resdata>(outData.resdata);
                        //if status is true , please update SP list - 3 columns , Update list item depends on ProcessType
                        //VisitorRequestID ( CabRequestRaised ,  ITRequestRaised ,  FacilitiesReqRaised ) either YES OR NO
                        string spItemID = sparksResData.VisitorRequestID;
                        if (sparksResData.status == "true" && sparksResData.processType.Contains("AdhocCab"))
                        {
                            try
                            {
                                using (ClientContext clientContext = new ClientContext(sharePointUrl))
                                {
                                    var passWord = new SecureString();
                                    foreach (char c in _spPwd.ToCharArray()) passWord.AppendChar(c);
                                    clientContext.Credentials = new SharePointOnlineCredentials(_spUserName, passWord);
                                    Web web = clientContext.Web;
                                    List oList = clientContext.Web.Lists.GetByTitle(_spListName);
                                    ListItem oListItem = oList.GetItemById(spItemID);// spItemID);
                                    oListItem["CabRequestRaised"] = "1";
                                    oListItem["VisitorRequestID"] = sparksResData.requestId;
                                    oListItem["SSMsg"] = sparksResData.message;
                                    oListItem["PendingWith"] = sparksResData.pendingWith;
                                    oListItem.Update();
                                    clientContext.ExecuteQuery();
                                    clientContext.Load(web);
                                    clientContext.ExecuteQuery();
                                    webTitle = web.Title;
                                    myAL.Add(spItemID);
                                }
                            }
                            catch (Exception ex)
                            {
                                var errmsg = ex.Message;
                            }

                            returnMessage += sparksResData.message + webTitle;
                        }
                        else if (sparksResData.status == "true" && sparksResData.processType.Contains("ITSupport"))
                        {
                            //update ITRequestRaised;
                            try
                            {
                                using (ClientContext clientContext = new ClientContext(sharePointUrl))
                                {
                                    var passWord = new SecureString();
                                    foreach (char c in _spPwd.ToCharArray()) passWord.AppendChar(c);
                                    clientContext.Credentials = new SharePointOnlineCredentials(_spUserName, passWord);
                                    Web web = clientContext.Web;
                                    List oList = clientContext.Web.Lists.GetByTitle(_spListName);
                                    ListItem oListItem = oList.GetItemById(spItemID);
                                    oListItem["ITRequestRaised"] = "1";
                                    oListItem["VisitorRequestID"] = sparksResData.requestId;
                                    oListItem["SSMsg"] = sparksResData.message;
                                    oListItem["PendingWith"] = sparksResData.pendingWith;
                                    oListItem.Update();
                                    clientContext.ExecuteQuery();
                                    myAL.Add(spItemID);
                                }
                            }
                            catch (Exception ex)
                            {
                                var errmsg = ex.Message;
                            }
                        }
                        else if (sparksResData.status == "true" && sparksResData.processType.Contains("Facilities"))
                        {
                            //update FacilitiesReqRaised
                            try
                            {
                                using (ClientContext clientContext = new ClientContext(sharePointUrl))
                                {
                                    var passWord = new SecureString();
                                    foreach (char c in _spPwd.ToCharArray()) passWord.AppendChar(c);
                                    clientContext.Credentials = new SharePointOnlineCredentials(_spUserName, passWord);
                                    Web web = clientContext.Web;
                                    List oList = clientContext.Web.Lists.GetByTitle(_spListName);
                                    ListItem oListItem = oList.GetItemById(spItemID);
                                    oListItem["FacilitiesReqRaised"] = "1";
                                    oListItem["VisitorRequestID"] = sparksResData.requestId;
                                    oListItem["SSMsg"] = sparksResData.message;
                                    oListItem["PendingWith"] = sparksResData.pendingWith;
                                    oListItem.Update();
                                    clientContext.ExecuteQuery();
                                    myAL.Add(spItemID);
                                }
                            }
                            catch (Exception ex)
                            {
                                var errmsg = ex.Message;
                            }
                        }

                    }
                }
            }
            catch (Exception e)
            {
                var error = e.InnerException;
                ErrorLog errorLog = new ErrorLog();
                errorLog.message = "Something Went Wrong";
                errorLog.status = false;
                returnMessage = JsonConvert.SerializeObject(errorLog);
                System.IO.File.AppendAllText(System.Web.HttpContext.Current.Server.MapPath(_ErrorLogPath), e.Message + Environment.NewLine);
            }

            try
            {
                //ArrayList myDeleteIds = new ArrayList();
                //myDeleteIds.Add("12346781_Facilities");
                if (myAL.Count > 0)
                {
                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    string output = jss.Serialize(myAL);
                    string postData1 = string.Format("destAppKey=" + _sparkVMSKey + "&resKey=" + _sparkServiceReqKey + "&dataIds=" + output);
                    string requestDeleteUrl = ConfigurationManager.AppSettings["deleteReports"];
                    ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; };
                    WebRequest request = WebRequest.Create(requestDeleteUrl);
                    request.Method = "POST";
                    byte[] byteArray = Encoding.UTF8.GetBytes(postData1);
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = byteArray.Length;
                    dataStream = request.GetRequestStream();
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Close();
                    response = request.GetResponse();
                    dataStream = response.GetResponseStream();
                    reader = new StreamReader(dataStream);
                    responseFromServer = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                var errmsg = ex.Message;
            }
        }
    }
}

Sparks Model

using System.Collections.Generic;

namespace SpoWebApi.Models
{
    public class SparksModel
    {
    }
    public class Datum
    {
        public string sourceapp { get; set; }
        public string size { get; set; }
        public string destinationapp { get; set; }
        public string resdata { get; set; }
        public string id { get; set; }
        public string resname { get; set; }
        public string timestamp { get; set; }
    }

    public class SparksResponse
    {
        public string msg { get; set; }
        public int count { get; set; }
        public List<Datum> data { get; set; }
        public bool status { get; set; }
    }
    public class Result
    {
        public SparksResponse sparksResponse { get; set; }
    }
    public class RootObject
    {
        public Result result { get; set; }
    }
    public class Resdata
    {
        public string pendingWith { get; set; }
        public string VisitorRequestID { get; set; }
        public string requestId { get; set; }
        public string processType { get; set; }
        public string id { get; set; }
        public string message { get; set; }
        public string taskId { get; set; }
        public string requestStatus { get; set; }
        public string status { get; set; }
    }
    public class ErrorLog
    {
        public string message { get; set; }
        public bool status { get; set; }
    }
}

Javascript code - Copy selected Items from One SP list webpart to another SP LIst

var sourceListName="CustomerDetails";
var targetListName="WelcomeList";
var sourceListURL="https://.sharepoint.com/sites/m/vms/Lists/CustomerDetails/AllItems.aspx";
var targetListURL="https://your site/sites/SecurityTeam/Lists/WelcomeList/AllItems.aspx";
var siteUrl ="https://Target site URL/";
var sourceSiteUrl="yoursite/VisitorManagement/";
//var userName,Company;

function clickMethod() {             
                var ctx = SP.ClientContext.get_current();
                var items = SP.ListOperation.Selection.getSelectedItems(ctx);
                var mySeletedItems = '';
                var i=0;
             
                    for (i in items) {
                        mySeletedItems += '|' + items[i].id;
                        var itemID = items[i].id;
                        //createListItem();
                         GetRequestItem(itemID);
                    }
                //alert(mySeletedItems);
                return false;
        }

     function GetRequestItem(rItemID) {
           // alert("GetRequestItem called");
            // Getting our list items
            var ItemId = rItemID;
            var currentSiteUrl = "https://your site name/";
            var requestUri = currentSiteUrl + "/_api/web/lists/getbytitle('CustomerDetails')/items(" + ItemId + ")";

            $.ajax({
                url: requestUri,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: function (data) {
                 
                    // Returning the results
                    //console.log(requestUri);
                    var userName = data.d.Title;
                    var userCompany = data.d.Visitor_x0020_Company;
                    var uDesignation = data.d.UserDesignation;
                    var salutation= data.d.Salutation;             
                    createListItem(userName,userCompany,uDesignation,salutation);

                },
                error: function (data) {
                    console.log(data.message);
                }
            });
        }

//ShowOnDisplayBoard
function createListItem(uName,uCompany,uDesig,salutation) {
//alert("createListItem starts now :"+siteUrl);
var userArray = uName.split('.');
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle(targetListName);
    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', uName);
    oListItem.set_item('Gender', salutation);
    oListItem.set_item('PersonName', uName);
    oListItem.set_item('UserCompanyName', uCompany);
    oListItem.set_item('UserDesignation', "DemoDesignation");
     oListItem.set_item('OrderBy', "1");
     oListItem.set_item('UserImage', "https://(yoursite)/sites/ST/SiteAssets/WelcomePage/DemoImage.png");
    oListItem.update();
    clientContext.load(oListItem);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
    window.location.href = window.location.href;
}

function onQuerySucceeded() {
    alert('Selected Item is copied to welcome list: ' + oListItem.get_id());
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}



SharePoint 2013 Installation






https://collab365.community/step-by-step-installation-of-sharepoint-2013-on-windows-server-2/

Get Folders under Subfolder

 public string sMenuString = "";
        [HttpGet]
        [Route("api/GetFolderTreeView")]
        public string GetFolderTreeView()
        {
            string sharePointUrl = ConfigurationManager.AppSettings["SharePointURL"];
            string _spUserName = ConfigurationManager.AppSettings["userName"];
            string _spPwd = ConfigurationManager.AppSettings["Password"];
            try
            {
                using (ClientContext clientContext = new ClientContext(sharePointUrl))
                {
                    var passWord = new SecureString();
                    foreach (char c in _spPwd.ToCharArray()) passWord.AppendChar(c);
                    clientContext.Credentials = new SharePointOnlineCredentials(_spUserName, passWord);
                    Web web = clientContext.Web;
                    // We want to retrieve the web's properties.
                    clientContext.Load(web);
                    clientContext.Load(web.Lists);
                    clientContext.Load(web, wb => wb.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    List list = web.Lists.GetByTitle("SampleDocuments");
                    clientContext.Load(list);
                    clientContext.ExecuteQuery();

                    Microsoft.SharePoint.Client.Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + "/SampleDocuments/0019E00000hQCs4QAG");
                    clientContext.Load(folder);
                    clientContext.ExecuteQuery();

                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = @"<View Scope='RecursiveAll'>
                                     <Query>
                                     </Query>
                                 </View>";
                    camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
                    ListItemCollection listItems = list.GetItems(camlQuery);
                    clientContext.Load(listItems);
                    clientContext.ExecuteQuery();

                    clientContext.Load(list.RootFolder);
                    clientContext.Load(list.RootFolder.Folders);
                    clientContext.ExecuteQuery();

                    foreach (var item in listItems)
                    {
                        if (item.FileSystemObjectType == FileSystemObjectType.Folder)
                        {
                            // This is a  Folder
                            clientContext.Load(item.Folder);
                            clientContext.ExecuteQuery();
                            sMenuString += "Folder" + item.Folder.Name;

                        }
                        else if (item.FileSystemObjectType == FileSystemObjectType.File)
                        {
                            // This is a File
                            clientContext.Load(item.File);
                            clientContext.ExecuteQuery();
                            //sMenuString += "File : "+item.File.Name;
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                var errmsg = ex.Message;
            }

            return sMenuString;
        }
           

Friday, September 28, 2018

Using JSLink as an alternative for Calculated columns to Display Images Depending on Checkbox values

alert("Hello");

(function () {
    alert('starting')
    var fieldCtx = {};

    fieldCtx.Templates = {};
    fieldCtx.Templates.Fields = {
        "ShowOnDisplayBoard": //This is field name, make sure to enter the internal column name
        {
            "View": UpdateApprovalTempalte //Enter the function name
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(fieldCtx);
})();

var imgTrue = "<img src='/siteassets/checked.png' width='16px'/>"
var imgFalse = "<img src='/siteassets/uncheck.png' width='16px'/>"
 

function UpdateApprovalTempalte(ctx) {
    var columnValue = ctx.CurrentItem.ShowOnDisplayBoard;  // get the value of the ApprovalColumn field of the current item
    var returnValue = "";
    if (columnValue == 'Yes')
        returnValue = imgTrue;
    else if (columnValue == 'No')
        returnValue = imgFalse;
    else if (columnValue == '')
        returnValue = imgFalse;
    else
        returnValue = columnValue;

    return returnValue;
}

Thursday, August 2, 2018

Backup and restore SharePoint online site

To back up and restore data in SharePoint Online, we can create an Office 365 support ticket to achieve it.
More information:
Thanks
Best Regards


I hope the above suggestion clarifies your concern, In SharePoint Online, we cannot backup and restore contents as what we do in SharePoint Server 2013. Instead, the backup and restoring features are reflected by the following features: version, template, recycle bin and some third party solutions.

Please follow this links to get more information about backup process in SharePoint Online

https://itsolutionsblog.net/the-backup-options-in-sharepoint-online/

How to back-up a Office 365 SharePoint Online site and data

Restore options in SharePoint Online
Hope this helps!


Migration solution to migrate to-and-from SharePoint and Office 365 along with File Servers, Exchange/Office 365 Public Folders, Google Drive and OneDrive Business to SharePoint Online/On-premise migration.

How to Deploy Your HTML Website on a Linux Server (Apache + SFTP)

Launching a simple HTML website on your own Linux server is easier than you might think. Whether you're sharing a static landing page or...