Wednesday 28 October 2015

Set Display Name of fields of a SharePoint List in SharePoint 2013



There may be necessity to change the display name of a field of SharePoint list in order to handle localization issue. The following code snippets illustrates how to do that in C#.





Suppose we have list called PLinks. 




    public static void SetDisplayNamePLinkListFields(ClientContext context)

        {

            Web web = context.Web;



            List lstPlinks = web.Lists.GetByTitle("PLinks");

            context.Load(lstPlinks);
            context.ExecuteQuery();


            // Get Field Reference or Internal Name

           Field fieldBackgroundImageLocation  =
           lstPlinks.Fields.GetByInternalNameOrTitle("BackgroundImageLocation");


           // Set Display Name

           fieldBackgroundImageLocation.Title ="Background Image Location" ;


           fieldBackgroundImageLocation.Update();




            Field fieldDescription = lstPlinks.Fields.GetByInternalNameOrTitle("Description");

            fieldDescription.Title ="Description of Image" ;
            fieldDescription.Update();


            Field fieldLinkLocation = lstPlinks.Fields.GetByInternalNameOrTitle("LinkLocation");

            fieldLinkLocation.Title ="Link Location";
            fieldLinkLocation.Update();


            Field fieldLaunchBehavior =
            lstPlinks.Fields.GetByInternalNameOrTitle("LaunchBehavior"); 
            fieldLaunchBehavior.Title ="Launch Behavior" ;
            fieldLaunchBehavior.Update();


            Field fieldDisplayOrder = lstPlinks.Fields.GetByInternalNameOrTitle("DisplayOrder");

            fieldDisplayOrder.Title ="Display Order" ;
            fieldDisplayOrder.Update();



            lstPlinks.Update();



        } 


Happy SharePointing....................:)

Sunday 25 October 2015

Programmatically check if a field is already existed in a SharePoint list or not using CSOM


In the method below, it is checked that if a particular field is already created/existed in a SharePoint 
list  or not. The return type of the list is bool. It returns true if the field is existed otherwise returns false.


 public static bool ContainsField(List list, string fieldName)
        {
            try
            {
                var ctx = list.Context;
                var result = ctx.LoadQuery(list.Fields.Where(f => f.InternalName == fieldName));

                ctx.ExecuteQuery();

                return result.Any();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }


Happy SharePointing.....................:)

Check if a SharePoint List is already created or not in a site collection in CSOM


The following methods determines whether list is already created or not in a site collection :



public static bool CheckIfListCreated(ClientContext context, string listName, ref string message)
        {

            try
            {
                ListCollection listCollection = context.Web.Lists;
             
                context.Load(listCollection, lists => lists.Include(list => list.Title).Where(list => list.Title == listName));
                context.ExecuteQuery();

                if (listCollection.Count > 0)
                {
                    message += listName + " " + string.Format("{0}", "Lists already exist.");
                    return true;

                }
                else
                {
                    message += string.Empty;
                    return false;
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }


Happy SharePointing..........................:)

Get all list items using CSOM in SharePoint 2013


There are several ways to get all the list items in CSOM. In the following method all the list items are retrieved using CSOM.


 private void GetAllListItems(ClientContext context, string listName)
        {
            try
            {

                Web web = context.Web;
                ListCollection lists = web.Lists;

                List selectedList = lists.GetByTitle(listName);

                context.Load<ListCollection>(lists);
                context.Load<List>(selectedList);

                context.ExecuteQuery();

                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = @"<View><Query></Query></View>";

                Microsoft.SharePoint.Client.ListItemCollection listItems = selectedList.GetItems(camlQuery);

                if (listItems.Count > 0)
                {
                    context.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                    context.ExecuteQuery();
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

Happy SharePointing...................:)

Get Attachment URL of a SharePoint list item using CSOM


Suppose, you have a SharePoint list that stores images and its link  URL. The image may also be attached to the list item. In order to get the attachment url we can use the following method or you can modify it as your own purposes:




 public static List<string> GetAttachemntUrls(ClientContext context, Guid listId, int itemId)
        {
            List<string> urls = new List<string>();
            try
            {
                context.Load(context.Web, w => w.Lists);

                List list = context.Web.Lists.GetById(listId);
                context.Load(list, l => l.RootFolder);

                Folder rootFolder = list.RootFolder;
                context.Load(rootFolder, rf => rf.Folders);

                FolderCollection folders = rootFolder.Folders;
                context.Load(folders);

                context.ExecuteQuery();

                foreach (Folder folder in folders)
                {
                    if (folder.Name == "Attachments")
                    {
                        FolderCollection attachmentFolders = folder.Folders;
                        context.Load(attachmentFolders);
                        context.ExecuteQuery();

                        foreach (Folder itemFolder in attachmentFolders)
                        {
                            if (itemFolder.Name == itemId.ToString())
                            {
                                FileCollection files = itemFolder.Files;
                                context.Load(files);
                                context.ExecuteQuery();

                                foreach (File file in files)
                                {
                                    urls.Add(file.ServerRelativeUrl);
                                }
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return urls;
        }


Happy SharePointing.....................:)

Tuesday 4 August 2015

Execution of a CAML query by means of a POST method type REST call to get list view data in the Host Web from App Web


Few days ago, We faced a requirement from our client. The requirement was to read a SharePoint listview in the host web from app web. As we all know, view is just a query on a list maintaining certain conditions. It has no physical existence. So the challenge was to get those data from list by maintaining certain conditions.

As we want to get data from a list, so the primary thinking was to read data by means of a GET 
method call using REST API. But we didn't get such method to find a solution of this problem.


The following method illustrates the scenario:

 function getListItemsForView(webUrl, listTitle, viewTitle)
{
        
        
        $.when(getJson(webUrl, listTitle, viewTitle)).then(function (data)
            {
                var viewQuery = data.d.ViewQuery;
                return getListViewItems(webUrl, listTitle, viewQuery);
            });
    }


The idea is to get the view query by means of a GET method call as follows:

 function getJson(appweburl, listname, viewTitle) 
{
        
        var d = $.Deferred();
        var datalist = null;
        var executor;

        executor = new SP.RequestExecutor(appweburl);

        executor.executeAsync({
            url: appweburl + "/_api/SP.AppContextSite(@target)/web/Lists/getbytitle('" + listname + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery?@target='" + _hostWebUrl + "'",
            method: "GET",
            headers: {
                "content-type": "application/json; odata=verbose"
                "Accept": "application/json;odata=verbose"
            },
            success: function (data) {
                if (data.body != null ) {
                    datalist = JSON.parse(data.body);
                }
                d.resolve(datalist);
            },
            error: function (data, errorCode, errorMessage) {
                d.reject(errorMessage);
            }
        });
        return d.promise();
    }


Then we need to POST the view query  in JSON format to get the view data as list items.

function getListViewItems(appweburl, listTitle, queryText)
 {
        var viewXml = '<View><Query>' + queryText + '</Query></View>';      
        var queryPayload = {
            'query': {
                '__metadata': { 'type': 'SP.CamlQuery' },
                'ViewXml': viewXml
            }
        };
        
        
        var d = $.Deferred();
        var datalist = null;
        var executor;
        executor = new SP.RequestExecutor(appweburl);
        executor.executeAsync({
            url:  appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listTitle + "')/getitems?@target='" + _hostWebUrl + "'",
            method: "POST",
            body: JSON.stringify(queryPayload),
            headers: {
                        
                        "Accept": "application/json; odata=verbose",
                        "content-type": "application/json; odata=verbose"
                    },
            success: function (data) {
                if (data.body != null ) {
                    datalist = JSON.parse(data.body).d.results;
                }
                
            
                d.resolve(datalist);

               

            },
            error: function (data, errorCode, errorMessage) {
                d.reject(errorMessage);
            }
        });
   
        return d.promise();
        
    }

Actually above method call is returning the result of the view query from the list
passed by the listTitle parameter like shown below:

<View><Query><Where><Eq><FieldRef Name="My_x0020_Column" /><Value Type="Text">01</Value></Eq></Where></Query></View>

So the trick is the execution of a CAML query by means of a POST method type REST call to get view data.



Happy SharePointing..................:)

Sunday 21 June 2015

Programmatically Create a Term Group if not exist in SharePoint 2013 Online Term Store Management


It is possible to programmatically create a term group  if not exist in SharePoint 2013 Online Term Store Management. The following method illustrates the steps:



public static Microsoft.SharePoint.Client.Taxonomy.TermGroup CreateTermGroupIfNotExist(ClientContext context, TermStore parent, Guid termGroupId, string termGroupName, string termGroupDescription = null)
        {
            Microsoft.SharePoint.Client.Taxonomy.TermGroup termGroup = null;
            try
            {
                context.Load(parent, ts => ts.Groups);
                termGroup = parent.GetGroup(termGroupId);
                context.Load(termGroup, ts => ts.Id);
                context.ExecuteQuery();

                if (termGroup.ServerObjectIsNull != null && termGroup.ServerObjectIsNull.Value)
                {
                    parent.CreateTermGroup(termGroupName, termGroupId, termGroupDescription);
                    context.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
               
                throw ex;
            }
            return termGroup;
        }

The above method will create a term group by the name termGroupName with the id termGroupId and description termGroupDescription.


Happy SharePointing.........:)

Tuesday 2 June 2015

Change look up field to allow multiple values by means of REST Call



It is possible change a look up field of a SharePoint list to allow multiple values by means of REST Call. The following code snippets illustrates the scenario:





    var hostweburl;
    var appweburl;

    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

function changeLookupFieldToAllowMultipleValues(listName, fieldName, callback) {

    var executor;
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/Lists/getbytitle('" + listName + "')/fields/getbytitle('" + fieldName + "')?@target='" + hostweburl + "'",
        method: "POST",
        body: "{ '__metadata': { 'type': 'SP.FieldLookup' }, 'AllowMultipleValues': true }",
        headers: {
            "content-type": "application/json; odata=verbose", "Accept": "application/json;odata=verbose", "X-HTTP-Method": "MERGE"
        },
        success: function (data) { callback({ Status: "Success", Message: data }); },
        error: function (error) { callback({ Status: "Error", Message: error }); }
    });

}


Test it on your own environment.


Happy SharePointing.....................:)

Create a sharepoin list in the host web for SharePoint hosted app by means of REST Call


It is possible to create a list in the host web by means of REST call from the app web for SharePoint hosted app. The following code snippets illustrates the scenario:



function createList(listName, onCreated, onError) {

    var executor;
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/Lists?@target='" + hostweburl + "'",
        method: "POST",
        body: "{ '__metadata': { 'type': 'SP.List' }, 'Hidden':true,  'AllowContentTypes': true,'BaseTemplate': 100,'Description': '" + listName + "', 'Title':'" + listName + "'}",
        headers: {
            "content-type": "application/json; odata=verbose", "Accept": "application/json;odata=verbose"
        },
        success: onCreated,
        error: onError
    });


}

Test it in your own environment.



Happy SharePointing....:)

Check if whether a field is exist in list by REST Call


We can check whether a field is existed in a sharepoint list by means of REST call. The following code illustrates the scenario:



    var hostweburl;
    var appweburl;

    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

function isFieldExist(listName, fieldName, callback) {

    var executor;
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/Lists/getbytitle('" + listName + "')/fields?$Filter=StaticName eq '" + fieldName + "'&@target='" + hostweburl + "'",
        method: "GET",
        headers: {
            "content-type": "application/json; odata=verbose", "Accept": "application/json;odata=verbose"
        },
        success: function (data) {
            var fields = JSON.parse(data.body).d.results;
            if (fields.length == 0) callback({ Status: false, Field: null });

            else callback({ Status: true, Field: fields[0] });
        },
        error: function (error) {
            callback({ Status: false, Field: null });
        }
    });


}


Sunday 31 May 2015

Check If a list exist in host web from app web by means of REST call for provider hosted app



We can check whether a list exists in host web for the app web. This can be done by REST call to the Host web from App Web. The below code samples illustrates the scenario:



function isListExist(listName, onExist, onNotExist) {
    var executor;
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/Lists/getbytitle('" + listName + "')?                   @target='" + hostweburl + "'",
        method: "GET",
        headers: {
            "content-type": "application/json; odata=verbose", "Accept": "application/json;odata=verbose"
        },
        success: onExist,
        error: onNotExist
    });
}

Sunday 24 May 2015

Check if the Document is a Folder and folder is an OneNote Notebook


 While Searching for documents in a SharePoint site, it is possible to determine whether the  document  is a folder or not. The following code snippets illustrates the scenario:


              // Check if a document library elements  is folder or not
              foreach (DataRow row in table.Rows)
               {
                   var isFolder = row["IsContainer"] == null || row["IsContainer"] == DBNull.Value ?
                                           false : Convert.ToBoolean(row["IsContainer"]);
                }


  Again, we can check whether a folder is OneNoteBook or not.

              if ( isFolder)
                    {

                        if (row["ProgID"].ToString() == "OneNote.Notebook")
                        {
                            row["DocIcon"] = "../Images/OneNoteBook.png";
                        }
                        else
                        {
                            row["DocIcon"] = "../Images/folder.png";
                        }

                   }



 That's it...............:)

Monday 18 May 2015

Load all Publishing Pages Library from a site collection by Base Template ID


Suppose you want to load all the Pages library form a Sharepoint Site. For this we can check the Base Template ID's of each list. For our case, the Base Template ID of Pages document library is 850.
The following method illustrates the successfull loading of the Pages library to a dropdown control.




private void LoadDocLibraries(string token)
        {
         
                using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(SitePicker.SelectedNode.Value, token))
            {
                Web web = context.Web;
                ListCollection lists = context.Web.Lists;
                context.Load(web);

                context.Load(lists, all => all
               .Where(l => l.BaseTemplate == 850)  //TemplateId of Publishing Pages Library=850 
               .Include(l => l.Title, l => l.RootFolder.Name));
               context.ExecuteQuery();

               ddlLibrary.Items.Clear();

                    foreach (List list in lists)
                    {

                        var item = new DropDownListItem
                        {
                            Value = list.RootFolder.Name,
                            Text = list.Title
                        };
                        ddlLibrary.Items.Add(item);

                    }
                }
            }
            catch (Exception ex)
            {
                ddlLibrary.Items.Clear();
                throw ex;
            }
        }

Sunday 17 May 2015

Get User Information List By means of Base Template Code



Sometimes it may happened that you are dealing with a multilingual site  collection and the with the change in language, the name of the User Information List also changes. And the program generates
"No List Found" error. To overcome the problem, we can use the Base Template code of the list to find necessary information. The method is illustrated below for developer's sincere observations:



private List GetUserInformationList(ClientContext clientContext)
        {
            try
            {
                var lists = clientContext.Web.Lists;
                clientContext.Load(clientContext.Web.Lists);
                clientContext.ExecuteQuery();

                foreach (var list in lists)
                {
                    /* BaseTemplate code of the User Information List */
                    if (list.BaseTemplate == 112)
                    {
                        return list;
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return null;
        }



Happy SharePointing...!!

Thursday 14 May 2015

Get all Managed metadata/Terms/Enterprise Keywords by TermSetId from Term Store Management


All the Terms or Managed Metadata or Enterprise Keywords are stored in a list named "TaxonomyHiddenList". By querying on the list, we can get our desired terms. The method is illustrated below:



private List<string> getTerms(string termSetId)
        {
            var terms = new List<string>();
            try
            {
                var spContext = GetSharepointContext();
                using (ClientContext context = spContext.CreateUserClientContextForSPHost())
                {
                    List list = context.Web.Lists.GetByTitle("TaxonomyHiddenList");

                    var camlQuery = new CamlQuery();
                    camlQuery.ViewXml = @"<View><Query><Where><Eq>
                                                    <FieldRef Name='IdForTermSet'/><Value Type='Text'>"
                                               + termSetId + "</Value></Eq></Where></Query></View>";
                    Microsoft.SharePoint.Client.ListItemCollection listItems = list.GetItems(camlQuery);
                    context.Load(listItems);
                    context.ExecuteQuery();

                    foreach (var term in listItems.ToList())
                    {
                        var termName = term.FieldValues["Title"].ToString();
                        if (terms.Contains(termName) == false)
                            terms.Add(termName);
                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return terms;
        }


Get Current User Information from a provider hosted app



In order to get current user information for a provider-hosted app, you need to write the following method in the web application part of the provider-hosted app. The method is written below:




private User GetCurrentUserInfo(SharePointContext context)
        {
            try
            {
                using (var clientContext = context.CreateUserClientContextForSPHost())
                {
                    var currentUser = clientContext.Web.CurrentUser;
                    clientContext.Load(currentUser);
                    clientContext.ExecuteQuery();
                    return currentUser;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return null;
        }



The returned  object currenUser contains all the users infomation like login name, email etc.

Wednesday 13 May 2015

CAML query to get all article page from Pages library for provider hosted app

In order to query on pages, we need to know the contentTypeId of Article page. The process is illustrated below:



 var contentTypeId =
 "0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3 900242457EFB8B24247815D688C526CD44D";

Microsoft.SharePoint.Client.ListItemCollection _collListItem = null;

  var token = GetAccessToken();
  using (var clientContext = TokenHelper.GetClientContextWithAccessToken(siteUrl, token))
      {
     List list = clientContext.Web.Lists.GetByTitle(library);
     var camlQuery = new CamlQuery();
      camlQuery.ViewXml =
@"<View><Query><Where><BeginsWith><FieldRef Name='ContentTypeId' />                                  <Value Type='ContentTypeId'>" +contentTypeId + "</Value></BeginsWith>                                      </Where><QueryOptions></QueryOptions></Query></View>";

                        _collListItem = list.GetItems(camlQuery);
                        clientContext.Load(_collListItem);
                        clientContext.ExecuteQuery();
                   }

Now you can iterate through  _collListItem  to get/use the pages according to your requirements.

In order to get the Access Token, the below method can be used:

 private string GetAccessToken()
        {
      string token = string.Empty;
         
   try
            {
                if (ViewState["Sp_AccessToken"] == null)
                {
                    EnsureChildControls();

                    if (HfAccessToken != null && !string.IsNullOrEmpty(HfAccessToken.Value))
                    {
                        token = HfAccessToken.Value;
                    }
                    else
                    {
 string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

                        if (contextTokenString == null)
                         {
string redirectUrl = TokenHelper.GetAppContextTokenRequestUrl(HostWebUrl,
                        HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.Url.ToString()));
                        Response.Redirect(redirectUrl, true);
                         }

                        else
                        {
var contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString,                       Request.Url.Authority);

var sharepointUrl = new Uri(HostWebUrl);
 token = TokenHelper.GetAccessToken(contextToken,sharepointUrl.Authority).AccessToken;
                      }

                        if (HfAccessToken != null && !string.IsNullOrEmpty(token))
                              {
                                 HfAccessToken.Value = token;
                               }
                        }
                   }
               else
                     token = ViewState["Sp_AccessToken"].ToString();
    }
    catch (Exception ex)
          {
                throw ex;
          }
            ViewState["Sp_AccessToken"] = token;

        return token;
}



Wednesday 29 April 2015

Find all the Managed Metadata or Enterprise Keywords columns from a document library for Provider Hosted Apps




Suppose we have a dropdown control that shows the document libraries of a site collection and we have another dropdown that will load the columns of Managed Metadata type. For that we need to
do the following coding:


protected void ddlLibrary_SelectedIndexChanged(object sender, EventArgs e)
        {

            LoadColumns();

        }

        private void LoadColumns()
        {
            string token = GetAccessToken();
            string url = SitePicker.SelectedNode.Value;
            string library = ddlLibrary.SelectedValue;
            if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(library))
            {
                return;
            }

    using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(url, token))
            {
                List list = SharePointList.GetListFromRootfolder(context, library);

                DropDownColumns.Items.Clear();

                var fields = list.Fields;

                context.Load(fields);
                context.ExecuteQuery();

                foreach (var field in fields)
                {
                    var fieldType = field.TypeAsString;

                    if (fieldType == "TaxonomyFieldType" || fieldType == "TaxonomyFieldTypeMulti")
                    {
                        var fieldName = field.Title;
                        var fieldIternalName = field.InternalName;

                        var fieldtermSetId = ((TaxonomyField)field).TermSetId;
                        var item = new DropDownListItem
                        {
                            Value =string.Format("{0}:{1}",fieldtermSetId,fieldIternalName),
                            Text = fieldName
                        };
                        DropDownColumns.Items.Add(item);
                    }
                }
            }
        }


Here, token is the Access Token for provider hosted apps and url is the URL of the site collection.