Wednesday, 26 April 2017

Query List/Document Library in Specific Folder

To query SharePoint List or Document Library in specific Folder “FolderServerRelativeUrl” as part of the CAML Query

Code Snippet

using (ClientContext clientContext = new ClientContext(siteURL))
{
List customList = clientContext.Web.Lists.GetByTitle("CustomListName");
CamlQuery camlQueryCustomList = new CamlQuery();
camlQueryCustomList.ViewXml = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='CustomField'/>" +
"<Value Type='Boolean'>1</Value></Eq></Where></Query></View>";
camlQueryCustom.FolderServerRelativeUrl = "/Lists/CustomListName/FolderName";
ListItemCollection items = customList.GetItems(camlQueryCustomList);
clientContext.Load(items);
clientContext.ExecuteQuery();
}

Friday, 21 April 2017

How to Expose Sharepoint Rating Feature as Service

Problem Statement:

Recently, I came across a situation where SharePoint List was used as the repository and application was built in other technologies. We wanted to expose SharePoint Rating feature as service and we encountered that rating was done in the context of the service account/App pool account contrary to it should be in current user’s context.

Solution:


We exposed the Web API service as Provider hosted App and consumed Token Helper’s  GetS2SClientContextWithWindowsIdentity  method to create client context.

Code Snippet:

[Authorize]
        [HttpPost]
        public string SetRating([FromBody]RatingDetails folderDetails)
        {
            try
            {
               //Site Collection/Web URL
                Uri hostWeb = new Uri(“https://sharepoint.domain.com/sites/1”);

                //Item Id for which user want’s to rate     
                int itemID = Convert.ToInt32(folderDetails.ItemId);
                int rating = Convert.ToInt32(folderDetails.Rating);

  using (var clientContext =   TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb,   HttpContext.Current.Request.LogonUserIdentity))
                {
                    clientContext.Load(clientContext.Web, web => web.Title);
                    clientContext.Load(clientContext.Web.CurrentUser);
                    Web w = clientContext.Web;
                    clientContext.Load(w, cw => cw.CurrentUser);
                    List curentList = w.Lists.GetByTitle("MyListName");
                    clientContext.Load(w.CurrentUser);
                    clientContext.Load(curentList, cl => cl.Id);
                    clientContext.ExecuteQuery();
                    string ListID = curentList.Id.ToString();
                    Reputation.SetRating(clientContext, ListID, itemID, rating);
                    clientContext.ExecuteQuery();

                    ListItem ratedItem = curentList.GetItemById(itemID);
                    clientContext.Load(ratedItem, item => item.Id, item =>                                       item["AverageRating"], item => item["RatingCount"], item =>                                   item["Ratings"]);
                    clientContext.ExecuteQuery();
                    return Convert.ToString(ratedItem["AverageRating"]);
                }


            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

Web Config Changes:

key="ClientId" value="689c2335-715b-4c50-969b-2d19f520adf7"
key="ClientSigningCertificatePath" value="D:\Cert\HighTrustCertOS.pfx"
key="ClientSigningCertificatePassword" value="Password123"

key="IssuerId" value="b7e4be28-8baa-4c18-83c9-73130305cb7a"

Note: You have to give permission on the SharePoint Site Collection for this App

   
   
   
   

Tuesday, 18 April 2017

Retrieve All the Files From Specific Folder Along with properties like ID, File Size,Editor etc

Below Code will fetch all the files under MyFolder in Documents library along with extended metadata like document id, modified by, document size and document url etc. ListItemAllFields will do the trick to get all the extended properties of the document.

var folderUrl  = "sites/sc1/Documents/MyFolder"
$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/GetFolderByServerRelativeUrl('" + folderUrl + "')/Files?$expand=ModifiedBy,ListItemAllFields",
    type: "Get",
    cache: false,
    async: true,
    crossDomain: true,
    beforeSend: function(xhr, settings) {
        // To do any operation before sending the request              
    },
    xhrFields: {
        withCredentials: true
    },
    dataType: "json",
    contentType: "application/json",

    success: function(data) {
        $.each(data.value, function(index, item) {
            var obj = {};
            obj["ID"] = item.ListItemAllFields.ID;
            obj["Name"] = itemN.ame;
            obj["LastUpdatedBy"] = item.ModifiedBy.Title;
            obj["LastUpdatedOn"] = item.TimeLastModified;
            var fileSize = item.Length / 1024;
            obj["Size"] = fileSize.toFixed() + "KB";
        });
    },
    error: function(err) {
       console.log("Error Occurred. : " + err);
     }
});

Tuesday, 4 April 2017

Getting the current item's icon path in Search Display Template Code

To show the file icon for the results in search display template, below code can be used.

// Get the current path of the file
var currentItem = ctx.CurrentItem.Path;
// Get the file extension from path 
Var ext = currentItem.split(",")[0].split(".").pop().split('?')[0];
// Add this extension in an object
Var  extObject = new Object();
extObject["FileExtension"] = ext;
// Get the icon url using below getIconUrlByFileExtension method
var iconUrl = SP.Utilities.HttpUtility.htmlEncode(Srch.U.ensureAllowedProtocol(Srch.U.getIconUrlByFileExtension(extObject, null)));

Monday, 3 April 2017

SharePoint Online/ SharePoint 2013 - Calling Sync Function Through Javascript


Sharepoint enables users to take the document library offline and sync the documents on personal devices leveraging OneDrive for Business feature

  1. Sync option is available in Sharepoint Online as well Sharepoint 2013 on premise (Provided we have Onedrive installed on our local machine
  2. In case we have customized our masterpage and we are not using  OOB document library views we can’t use sync feature
  3. In this scenario we need to hook some client script to call the sync functionality on custom event.
  4. To call the sync functionality on click of control/using javascript below method can be used 

EnsureScriptFunc('offline.js', 'TakeOfflineToClientReal', function() { TakeOfflineToClientReal(2, 1, 'https://mydomain.sharepoint.com/sites/sc/webname', 1, 101,'989F78C3-FB40-46DE-ABF5-60380B44D201', '');});

989F78C3-FB40-46DE-ABF5-60380B44D201 – Is the GUID of the document library

Tuesday, 5 March 2013

Using Modules to Include Files in the Solution

I have seen lots of people struggle with Modules. Sometimes modules are getting deployed successfully but files are not reflecting in Document library.


First of all the Element.xml file should have below structure.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

  <Module Name="MyCustomModule" Url="SitePages" Path="MyCustomModule">
    <File Url="Sample.aspx" Type="GhostableInLibrary"/>
  </Module>
</Elements>

In above XML few things need to be taken care.

Url ( In Module element): Url in module element indicates the URL of the library where files need be created.

Url (In File element) : The location where the file will be deployed on the SharePoint server

Type: It indicates that whether file is available in Document library as a Item. If this attribute is missing, file would be available under list/libraries but it won’t show up in any of the Views.

Tuesday, 26 February 2013

Populating current logged in user in people picker

Sometimes there are requirement to populate the current logged in user in People picker field.
I had tried to populate using PickerEntity class, but it use to fail on click of "Check Names" button. So changed the approch to se the comma seprated names and it worked.

1. Take the curent Logged user

loginName = SPContext.Current.Web.CurrentUser.LoginName

2. Assign the login to picker control. 
pkrControlName.CommaSeparatedAccounts =loginName

Note: You can have multiple comma serpated login names to populate multiple users in people picker field.

Wednesday, 5 September 2012

Retrieve existing base permission using powershell

Below script can be used to retrieve the existing Base Permission for the given permission level.
param(

[Parameter(Position=0, Mandatory=$true)]
[string]
$siteURL
)
$snapin = Get-PSSnapin
Where-Object { $_.Name -eq "Microsoft.SharePoint.Powershell" }
if ($snapin -eq $null) {
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}

$site=Get-SPSite $siteURL
$web=$site.RootWeb
$permissionLevel=$web.RoleDefinitions["PermissionName"]
Write-Host $permissionLevel.BasePermissions
$web.Dispose()
$site.Dispose()

Thursday, 24 November 2011

Save ViewState at server side to reduce Page Size

Some time we have lots of heavy controls (like GridView,DataGrid) which emits lots of ViewState information on the page. This results to increase in Page size and apparently it would reduce the page performance.
So to reduce the page size ViewState can be stored on Server side which would reduce the page size.
We need to override SavePageStateToPersistenceMedium method to save the ViewState at server side and LoadPageStateFromPersistenceMedium method to retrieve the ViewState.

Note: These two methods needs to be overridden in code behind file of ASP.Net page.

Sample Code snippet.

protected override void SavePageStateToPersistenceMedium(object state)
{
try
{
string VSKey = "VIEWSTATE_" + base.Session.SessionID + "_" +
Request.RawUrl + "_" + DateTime.Now.Ticks.ToString();
Cache.Add(VSKey, state, null, DateTime.Now.AddMinutes(Session.Timeout),
Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
ClientScript.RegisterHiddenField("__VIEWSTATE_KEY", VSKey);
}
catch
{
base.SavePageStateToPersistenceMedium(state);
}
}

protected override object LoadPageStateFromPersistenceMedium()
{
string VSKey = Request.Form["__VIEWSTATE_KEY"];
return Cache[VSKey];
}

Wednesday, 3 August 2011

Admin SVC must be running in order to create deployment timer job

Issue : Recently, while using a PowerShell command (Update-SPSolution) I encountered below error.

Admin SVC must be running in order to create deployment timer job

Solution : You would encounter above error if “ SharePoint 2010 Administration” services is nor running. So to resolve above issue goto run -> type “services.msc” and start “SharePoint 2010 Administration” service.

Friday, 1 July 2011

Multiple list instances of list definition

Problem:

Recently, I observed one weird thing in my SharePoint application.I was creating a list definition which had multiple views. I wanted to create one instance of the site definition but I could see multiple list instances of the same list in my site.

Reason:

I figured out the reason behind this issue.

In schema.xml under the views node I had multiple views definitions.
I had created one view and replicated the same for rest of the views.

<View DisplayName="By Customer Name" DefaultView="TRUE" BaseViewID="1" Type="HTML" MobileView="TRUE" MobileDefaultView="TRUE" ImageUrl="/_layouts/images/generic.png" XslLink="main.xsl" WebPartZoneID="Main" Url="By Customer Name.aspx" SetupPath="pages\viewpage.aspx">
<Toolbar Type="Standard" />
<XslLink>main.xsl</XslLink>
<Query>
</Query>
<ViewFields>
</ViewFields>
<RowLimit Paged="TRUE">100</RowLimit>
</View>


I was modifying the query and fieldrefs. Erroneously DefaultView="TRUE" attribute was present in all the views, which was resposible for creating multiple instances of the list and keeping that particular view as the default view.

Sunday, 19 June 2011

How to programmatically download attachments from list items

To download an attachment, you must first find the download link and then redirect to another page.

The ending of the response from current page does not affect the functionalities on the second one.


using (SPSite site = new SPSite("http://SiteCollectionURL"))
{
using (SPWeb web = site.OpenWeb())
{
string file = string.Empty;
SPList list = web.Lists["MyList"];
SPListItem currentItem = myList.GetItemById(id);
if (currentItem["AttachmentName"] != null)
{
file = "/Lists/ MyList/Attachments/" +
id.ToString() + "/" +
currentItem["AttachmentName"].ToString();
System.Web.HttpContext.Current.Session["FileName"] =
currentItem["AttachmentName"].ToString();
System.Web.HttpContext.Current.Session["Attachment"] =
file.Trim();
}
else
{
lblReport.Text = "No File name found";
}
if (file != string.Empty)
{
Reponse.Redirect("download.aspx");
}
}
}

On the download.aspx page, you need to the code shown below to download the file.

if (System.Web.HttpContext.Current.Session["Attachment"] != null)
{
string strName = System.Web.HttpContext.Current.Session["FileName"].ToString();
string sbURL = System.Web.HttpContext.Current.Session["Attachment"].ToString();
System.Web.HttpResponse response;
response = System.Web.HttpContext.Current.Response;
System.Web.HttpContext.Current.Response.ContentEncoding =
System.Text.Encoding.Default;
response.AppendHeader("Content-disposition", "attachment; filename=" + strName);
response.AppendHeader("Pragma", "cache");
response.AppendHeader("Cache-control", "private");
response.Redirect(sbURL);
response.End();
}

Deleting an Attachment from SPList

Use below method to delete attachment of specific list item.

public void DeleteAttachment(int id,string fileName)
{
using (SPSite site = new SPSite("http://SiteCollectionURL"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["MyListName"];
SPListItem delItem = list.GetItemById(id);
SPAttachmentCollection files = delItem.Attachments;
files.Delete(fileName);
delItem.Update();
}
}
}

Adding an Attachment to an Item

Below code can be used to add attachment to list item.

using (SPSite site = new SPSite("http://SiteCollectionURL"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["MyListName"];
SPListItem newItem = list.GetItemById(id);
byte[] contents = null;
if (fileUpload.PostedFile != null && fileUpload.HasFile)
{
using (Stream fileStream = fileUpload.PostedFile.InputStream)
{
contents = new byte[fileStream.Length];
fileStream.Read(contents, 0, (int) fileStream.Length);
fileStream.Close();
}
SPAttachmentCollection attachments = newItem.Attachments;
string fileName = Path.GetFileName(fileUpload.PostedFile.FileName);
attachments.Add(fileName, contents);
newItem.Update();
}
}
}

Saturday, 18 June 2011

How to check if User is Present in a Group

You can add extension method to SPUser class to achieve this requirement.

Add the below namespace.

using System.Linq;


public static bool UserExist(this SPUser user, string groupName)
{
return user.Groups.Cast().Any(gn => gn.Name == groupName);
}

How to close the sharepoint modal dialog and refresh the parent page.

Recently, I stumbled upon a situation where I had Calendar list and I had provided custom save and cancel button.

In List setting I had kept "Launch forms in a dialog" option to "No" so that my NewForm/EditForm/DispForm can open on same page instead of a dialog window.

But in case of Calendar View Edit and Display form always opens in Dialog.So after updating the record we explicitly need to close the dialog and redirect to any view.

At server side I tried below code.

Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
Context.Response.Flush();
Context.Response.End();

But It didn't worke!!!! So I tried below approach and it worked.

Since I had to close the window only user is editing form Calendar view.So wherever you open a dialog a querystring is passed with name "IsDlg" and value ="1". So If ""IsDlg" is present in the URL redirect the user to your custom page from server side, and use below javascript to close the dialog.

Server Side Code


if (Request.QueryString["IsDlg"] != null)
{
dlgID = Request.QueryString["IsDlg"].ToString();
}
if (!string.IsNullOrEmpty(dlgID))
{
Response.Redirect(SPContext.Current.Web.Url + "/Default.aspx?Close=1");
}


Write below code in Default.aspx or your custom defualt page.

var closeFlag =location.search.substring(1).split("Close=");
if(closeFlag !="")
{
var flag = closeFlag[1].split("&");
if(flag=="1")
{
Close();
}
}

function Close()
{
// Will close the window and update the view.
window.frameElement.commitPopup();
}
</script>

Tuesday, 7 June 2011

Error while deploying solution

Error:

The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Solution:

Recently I encountered above error while deploying the solution. This error can be observed due to below two reasons:

1. Your Solution name/Project Name is too long

2. Your VS Solution/Project is under a deep folder structure for e.g. "D:\Dev\Code\Phase1\Latest\..\..\ etc..."

So to resolve this issue you can reduce the folder hierarchy or shorten the project/solution name.

Sunday, 5 June 2011

Adding Custom Links in Central Admin 2010

To Create a custom link in Central Admin 2010 below steps can be followed

1. Open Visual Studio 2010 and create "Empty SharePoint Project".
2. Add EmptyElement
3. Paste below XML

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction Id="EA36F5EB-311D-4ee0-973E-1C503933D740"
GroupId="SiteCollections"
Location="Microsoft.SharePoint.Administration.Applications"
Sequence="1500"
Title="My Title"
Description="My Description">
<UrlAction Url="My URL" />
</CustomAction>
</Elements>

4. Add this Element in Feature.
5. Deploy it.

Note:

Above Link will appear under Central Admin -->Application Management-->Site Collections

To display the link at any other place "GroupId" and "Location" properties can be changed.

Please refer below table to get the Location and GroupID

Wednesday, 25 May 2011

How to check your code is running under sandbox Worker Process

You can use below code to check if your application is running withing sandbox worker process

if(System.AppDomain.CurrentDomain.FriendlyName.Contains(“Sandbox”))
{
// Your code is running in the sandbox.
}

Monday, 21 February 2011

Using ~SiteCollection prefix for referring javascript files

Recently I faced a javascript reference issue in my application. I had javascript file referenced in my master page. I had given relative path to the JavaScript files.

<span style="font-weight:bold;"><script type="text/javascript" src= "../../Script%20Library/jquery-1.4.2.min.js"></script></span>

It was not working for all the pages across application due to different hierarchy.
So below dynamic reference style can be used to overcome this issue.


<script type="text/javascript" src= "<asp:Literal runat='server' Text='<%$SPUrl:~sitecollection/Script%20Library/jquery-1.4.2.min.js%>'/>"></script></span>

Query List/Document Library in Specific Folder

To query SharePoint List or Document Library in specific Folder “ FolderServerRelativeUrl ” as part of the CAML Query Code Snippet ...