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;
}