Not able to view result while building Search Query


Hello SharePointers ;),

Here is another quick finding which I just thought should be shared to save someone precious time. If you are dealing with SharePoint 2013 search and Result sources, you must try to test the query template before saving it. If you are not able to see any results instead just a red error saying below text don’t get scared I have quick solution for you.

“The Search display templates are not present on this site collection. To add them, you need to activate the “Search Server Web Parts and Templates” feature on the Site Collection Features page.

Display Error: The display template had an error. You can correct it by fixing the template or by changing the display template used in either the Web Part properties or Result Types.

Template ‘~sitecollection/_Catalogs/masterpage/DisplayTemplates/System/Control_QueryBuilderPreview.js’ not found or has sytax errors. (Load Template: ) ”

Search_Error

You must get frustrated because your search is properly configured, its crawling the data and you are able to see results while searching.  After looking at what was missing I found that in fact there was a feature missing on the Central Administration site collection. The feature is called Search WebParts.

But its not so quick that you just navigate to Site collection feature and activate it. As this feature is present at central admin site collection level so it requires extra privileges to activate it. To fix the problem, simply run the following command in an elevated SharePoint Management Shell:

Enable-SPFeature SearchWebParts -url http://<central admin url>

Bingo!! Just, re-open the “build your query” page, and everything should work properly!

Search_Error

Hope that post was able to help you. Please press like button it that saved your time.

Happy SharePointing 🙂

SharePoint : Custom Task Email with Outlook ribbon control “Open this Task”


Hi Guys,

It was really interesting to work with my latest client. They had an very interesting and innovated idea to automate their manual file approval process.  The requirement was to create a multistage state machine workflow where users have privilege to approve and reject documents with some comments. It was very interesting to work with end client(as they them self don’t know what they actually want).

I will not go deep into the workflow but surly will come back with another post explaining it. This post is more about a requirement which I faced during the development of the workflow. Just wanted to share the design of the Workflow:

WF

Requirement:  As a user, I should have receive an email from workflow with custom subject having document name embedded to the subject where I can directly do some action like approve/reject or comment on the document. I should see a button in email “Open this task” which will redirect me to the page where I can take actions.

1

It looks bit easy but have hidden challenges in it. Most us are aware of the fact that when a task item is created, either directly in the task list or through a Workflow an alert email would be sent saying a task has been assigned to you (provided alerts are enabled). When we look at that email in Outlook we see an additional control in the ribbon “Open this Task” under the group “Open” as shown in above figure. Let me rephrase the requirements:

  1. We have to customize the body and subject as per their request
  2. Ribbon button “Open this Task” should present when the email is sent

The above mentioned two points are two sides of the coin, which means if you are able to see one then second will not be visible to you. So the final solution’s must have some trick to achieve both cases.

Solution: 

One point is clear that we can not go along with the default workflow email feature, we have to use “SmtpClient” or “SPUtility” to create email with custom body and subjects. Now question is how one can get ribbon button using SPUtility send email function.

  • I have used “SPWorkflowTaskProperties” class in the Task Created Event and sent it two properties “SPWorkflowTaskProperties.HasCustomEmailBody = true” and “SPWorkflowTaskProperties.EmailBody= <My Custom HTML Email Body> ” With this I can satisfy requirement 1 & 2 but not 3 (listed above).  Also if I were to create a task and if I want to send an email using Event Handler on item created I may not be able to use this. So for the generic purposes this would not fit in.
  • Next I thought of modifying the alert template but then it would have an impact on all task lists which is not a recommended option.
  • So, I have decided that I have to disable the alerts for that Task list and use “SmtpClient or SPUtility” class instead to send email which can be used at different requirements such as “event handlers/workflows or any other for that matter. With this class we do have control over all the aspects “From, To, Subject, Email Body, etc”. The only problem with this to achieve the requirement # 2 (Ribbon control in outlook). I always wondered how would outlook recognize that an email is for Task, how is this ribbon control activated as soon as it sees an email.

I believed that the alert email sent has some headers which mark this as Task which is understood by outlook and displays the controls accordingly. So now the question is what are those headers. After some research I figured out the Mail message headers. Below is the code for sending an email which also includes those headers and satisfies all the above mentioned requirements (1 & 2)

/// <summary>
/// Method used to send the task created email instead of default SP WF email notification
/// </summary>
/// <param name=”web”></param>
/// <param name=”htmlBody”></param>
/// <param name=”ToEmailId”></param>
/// <param name=”listItem”></param>
/// <param name=”emailSubject”></param>
/// <returns></returns>
public bool SendTaskMail(SPWeb web, string htmlBody, string toEmailId, SPList taskList, string itemId, string emailSubject)
{
try
{
string domain = web.Site.WebApplication.OutboundMailSenderAddress.Remove(0, web.Site.WebApplication.OutboundMailSenderAddress.LastIndexOf(‘@’));
var messageHeaders = new StringDictionary();
messageHeaders.Add(“to”, toEmailId);//author.User.Email);
messageHeaders.Add(“subject”, emailSubject);
messageHeaders.Add(“content-type”, “text/html”);

messageHeaders.Add(“Message-Id”, “<3BD50098E401463AA228377848493927” + Guid.NewGuid().ToString(“D”) + domain + “>”);
messageHeaders.Add(“X-Sharing-Title”, ConvertToBase64String(“Body”));
messageHeaders.Add(“X-AlertTitle”, ConvertToBase64String(“System”));
messageHeaders.Add(“Content-Class”, “MSWorkflowTask”);
messageHeaders.Add(“X-AlertWebUrl”, ConvertToBase64String(web.Url));
messageHeaders.Add(“X-AlertServerType”, “STS”);
messageHeaders.Add(“X-AlertWebSoap”, ConvertToBase64String(web.Url + “/_vti_bin/alerts.asmx”));
messageHeaders.Add(“X-Sharing-Config-Url”, “stssync://sts/?ver=1.1&type=tasks&cmd=add-folder&base-url=” + Uri.EscapeDataString(web.Url) + “&list-url=” + Uri.EscapeDataString(taskList.RootFolder.ServerRelativeUrl) + “&guid=” + Uri.EscapeDataString(taskList.ID.ToString(“D”)));
messageHeaders.Add(“X-Sharing-Remote-Uid”, taskList.ID.ToString(“D”));
messageHeaders.Add(“X-Sharing-WssBaseUrl”, ConvertToBase64String(web.Url));
messageHeaders.Add(“X-Sharing-ItemId”, ConvertToBase64String(itemId));

SPUtility.SendEmail(web, messageHeaders, htmlBody);

return true;
}
catch (Exception ex)
{
Utilities.UpdateLogErr(ex, “Error while sending email. Please find details in audit logs”);
return false;
}
}

Hope this helps!

Thank you for your time.

Happy SharePointing 🙂 !!

Upload a file in SharePoint using REST and c# console application


Hi,

In my last post, I have explained how to create a sub site using REST from and Console application. In this blog  will explain how we can upload a file, which is located in file system, will be uploaded to sharepoint Document library. So if I brief about requirement here:

  • Need to upload a file to already created SharePoint site.
  • Use REST(not even CSOM) will be used in order to create.
  • API call will be send from some other machine(not SharePoint machine) which is in same domain and can access the SharePoint site.

Follow the given steps to achieve the same:

1) Create a simple console application with c# selected language.

1

2) Next is to install the Newtonsoft.Json. Navigate to Visual studio menu: “View” > “Other Windows” > “Package Manager Console” and Then type the following: “Install-Package Newtonsoft.Json”

2

3) Now install RestSharp using the package manager. Type the following: “Install-Package RestSharp”

3

4) Now open the Program.cs file of console application and paste the code below:

string siteurl = “http://sharepoitsite/sites/subsite&#8221;; //site on which file needs to be uploaded (don’t put / at end)
string documentlibrary = “Documents”; //Document library where file needs to be uploaded

string filePath = @”C:\Users\mohit.vashishtha\Desktop\test.html”;

byte[] binary = System.IO.File.ReadAllBytes(filePath);
string fname = System.IO.Path.GetFileName(filePath);
string result = string.Empty;
//Url to upload file
string resourceUrl = string.Format(“{0}/_api”,siteurl);

RestClient RC = new RestClient(resourceUrl);
NetworkCredential NCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
RC.Authenticator = new NtlmAuthenticator(NCredential);

Console.WriteLine(“Creating Rest Request”);
RestRequest Request = new RestRequest(“contextinfo?$select=FormDigestValue”, Method.POST);
Request.AddHeader(“Accept”, “application/json;odata=verbose”);
Request.AddHeader(“Body”, “”);

string ReturnedStr = RC.Execute(Request).Content;
int StartPos = ReturnedStr.IndexOf(“FormDigestValue”) + 18;
int length = ReturnedStr.IndexOf(@”””,”, StartPos) – StartPos;
string FormDigestValue = ReturnedStr.Substring(StartPos, length);

Console.WriteLine(“Uploading file Site……”);

resourceUrl = string.Format(“/web/GetFolderByServerRelativeUrl(‘{0}’)/Files/add(url='{1}’,overwrite=true)”, documentlibrary ,fname);
Request = new RestRequest(resourceUrl, Method.POST);
Request.RequestFormat = DataFormat.Json;
Request.AddHeader(“Accept”, “application/json;odata=verbose”);
Request.AddHeader(“X-RequestDigest”, FormDigestValue);
Console.WriteLine(“File is successfully uploaded to sharepoint site.”);
Console.ReadLine();

5) Now application is ready to run. Make sure that all the namespace issues are resolved.

6) It will take some time to create site but output window will display the details it got from the Request.

In case of already existing site:

54

Hope this information is helpful to you. Thanks for time.

Happy SharePointing 🙂

 

Get SharePoint search results using REST ajax call from Html


Hi,

We all aware the SharePoint exposed REST Api in order to perform various action at client side. There are some other ways also which a developer can adopt instead of REST(like CSOM) but that requires again client context. So it is recommenced that if we are using SharePoint Apps then use CSOM to get and update the data. Where as REST can be used in apps as well as some external applications.

This blog is intended to show how user can utilize the REST api and get the SharePoint Search results. There are few pre-requisites or conditions which must be fulfilled before proceeding further.

  • The machine where this code will be executed must have access to sharepoint site which means machine must be either in same domain or cross domain accessibility is there.
  • Search must be configured at SharePoint server.
  • Data must be properly crawled and you must get some results when searched for some keyword.

Steps:

1) Open the Explorer or any desired location and create a text file with ant desired name.

2) Now open this txt file in Notepad and click on “Save as..” option. Here select the “Save as type” as “All” and save the file in “.html” format as shown below:

1

3) Now open this file in any desired text editor(I love to use Notepad++ for same) and paste the following code:

<script src=”http://code.jquery.com/jquery-2.1.4.js&#8221; type=”text/javascript”></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(“#SearchQuery”).click(function() {
$.ajax({
url: “http://<server URL>/_api/search/query?querytext='”+$(“#search-input”).val()+”‘&sourceid=%27b09a7990-05ea-4af9-81ef-edfab16c4e31%27″,
headers: { Accept: “application/json;odata=verbose” },
success: function (data) {

console.log(data.d);

},
error: function (jQxhr, errorCode, errorThrown) {
console.log(errorThrown);
}
});
});

});</script>
<input type=”text” id=”search-input”>
<input type=”button” id=”SearchQuery” value=”Search”>
<div id=”resultsDiv”></div>

Issues faced:

1) minFreeMemoryPercentageToActivateService memory issue:

2

Resolution: Open the web config of the web application and find out the entry with

<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” />

to

<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” minFreeMemoryPercentageToActivateService=”1″/>

Happy SharePointing 🙂

 

 

 

Create Sub Site in SharePoint using REST and c# console application


Hi,

Recently, I got an requirement to create a SharePoint sub site from the some .Net application which is hosted somewhere hosted outside the SharePoint environment. It is provided that the .Net application can be added in same domain. So if I brief about requirement here:

  • Need to create a sub site in SharePoint site collection based on some default template(later on custom template)
  • Use REST(not even CSOM) will be used in order to create.
  • API call will be send from some other machine(not SharePoint machine) which is in same domain and can access the SharePoint site.

There are few challenges which I faces if we try to work with such kind of requirements. The authentication tokens and RequestDigest data are the crucial things to retrieve.

I have explored some way to execute REST API and create a sub site without navigating to SharePoint site. Follow the given steps to achieve the same:

1) Create a simple console application with c# selected language.

1

2) Next is to install the Newtonsoft.Json. Navigate to Visual studio menu: “View” > “Other Windows” > “Package Manager Console” and Then type the following: “Install-Package Newtonsoft.Json”

2

 

3) Now install RestSharp using the package manager. Type the following: “Install-Package RestSharp”

3

4) Now open the Program.cs file of console application and paste the code below:

RestClient RC = new RestClient(“http:/SharepointSiteUrl/_api”);
NetworkCredential NCredential = System.Net.CredentialCache.DefaultNetworkCredentials;//new NetworkCredential(“mohitvashishtha”, “******”, “mydomain”);
RC.Authenticator = new NtlmAuthenticator(NCredential);

Console.WriteLine(“Creating Rest Request”);

RestRequest Request = new RestRequest(“contextinfo?$select=FormDigestValue”, Method.POST);
Request.AddHeader(“Accept”, “application/json;odata=verbose”);
Request.AddHeader(“Body”, “”);

string ReturnedStr = RC.Execute(Request).Content;
int StartPos = ReturnedStr.IndexOf(“FormDigestValue”) + 18;
int length = ReturnedStr.IndexOf(@”””,”, StartPos) – StartPos;
string FormDigestValue = ReturnedStr.Substring(StartPos, length);

Console.WriteLine(“Creating Site……”);

var Data = string.Concat(
“{‘parameters’:{‘__metadata’:{‘type’:’SP.WebCreationInformation’},”,
“‘Title’:’Team projects 3′,’Url’:’TeamProjects3′,’WebTemplate’:’STS’,”,
“‘UseSamePermissionsAsParentSite’: true}}”);

Request = new RestRequest(“web/webs/add”, Method.POST);
Request.RequestFormat = DataFormat.Json;
Request.AddHeader(“Accept”, “application/json;odata=verbose”);
Request.AddHeader(“X-RequestDigest”, FormDigestValue);
Request.AddParameter(“application/json;odata=verbose”, Data, ParameterType.RequestBody);

Console.WriteLine(RC.Execute(Request).Content);
Console.WriteLine(“SharePoint Site is successfully created.”);
Console.ReadLine();

5) Now application is ready to run. Make sure that all the namespace issues are resolved.

6) It will take some time to create site but output window will display the details it got from the Request.

In case of already existing site:

4

 

Just a little explanation about the above code, this code is actually getting the request digest first and then in second REST request it will pass the same reader digest. There are few chances that this code will throw 401 unauthorized error if user does not have permission on sharepoint site. But there are option to hardcode the credential too using NetworkCredentials object commented in above code.

Hope this information is helpful to you. Thanks for time.

Happy SharePointing 🙂

 

 

 

Enable SP.JS in publishing sites for SP 2013


Hi,

In my previous post, I have explained the way to add CSOM on master page of any kind of site. But later on when testing same code with publishing site, I realized that sp.js is not loaded on publishing site by default.

So in this post I will discuss how to enable sp.js in Publishing Pages in SharePoint 2013. As the SharePoint uses minimal download strategy it prevents the page to have sp.js when published but the point to note is when you open your ribbon bar (edit or unpublished state) sp.js  script gets loaded in your page .

Note : SharePoint loads scripts on Demand
So to solve this we can do like this: Add a script editor webpart in your page and in script tags just add the following code snippet:
SP.SOD.executeFunc(‘sp.js’, ‘SP.ClientContext’, alert(‘I have loaded the sp.js script.’));
Where instead of alert method you can use any JS method and will be executed after sp.js is loaded.
Happy SharePointing :).

SharePoint CSOM for beginners: Get Current User details


Hi Guys,

This blog is targeted to developers who are novice to the client side object model in SharePoint. SharePoint apps by default provides a basic stub for getting user details inside app. But sometimes it is required to add client side code in simple script file to get user information. I hope this information will also be helpful starters of client side object model.

Pre-requisites:

1) Any version of SharePoint installed: SP 2013, SP 2010 or SP Online

2) A web application and a root site collection inside it. It does not matter whether site is team site or any other type of site.(Note: In case of publishing site you need to enable sp.js file loading).

3) SharePoint Designer installed.

Step I: Create a custom script file

A script file is required in order to place CSOM code to be executed. Well, here depending upon usability user can chooses any one of these two locations to create this file:

List or Style library: It will be hard to update script file if it is placed under style library. Every time one have to update the file in SP Designer in order to make any changes or one have to upload the latest file each time in case of any update.

15 hive folder: This is my favorite place in order to do such kind of research. Create a dummy folder under “15/Template/layouts/dummy”.

I am referring second approach as it is very comfortable to update the files in 15 hive. Now open the dummy folder and create a JS file there with any name say, CSOMDemo.js. Let this file blank as of now.

Step II: Refer a custom script file

Once custom JS file is created, now next is to refer this file to master page so that it will be utilized by SharePoint. There are also many option to refer the file: Master page, Page layout(in case of publishing site), using content editor web part etc.

For this blog I am referring the script file to master page. In order to do same, Open the site using SP Designer and click on All Files > _catalogs >  masterpage > seattle.master(for team site). Then right click on the file and select the option “Edit File in Advanced Mode”.

Capture1                        Capture2

Now find out the head section add following lines:

<script type=”text/javascript” src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js “></script>
<script type=”text/javascript” src=”/_layouts/15/dummy/Script/CSOMDemo.js”></script>

 

Names can vary according to your naming conventions. But one these lines are placed in master page, all site pages will be registered and enabled with jQuery and custom scripts.

Step III: Write CSOM Code

Open the custom script file and paste the following code in side it.

var currentUser;
$( document ).ready(function() {
console.log(‘ready’);
url = window.document.location.href;

// In case of Publishing site please use following code line

// SP.SOD.executeFunc(‘sp.js’, ‘SP.ClientContext’, init);

ExecuteOrDelayUntilScriptLoaded(init,’sp.js’);

function init(){
var context = new SP.ClientContext.get_current();
var web = context.get_web();
currentUser = web.get_currentUser();
currentUser.retrieve();
context.load(web);
context.executeQueryAsync(
function(){
//On success function
console.log(‘init succeeded..’);
console.log(currentUser.get_loginName());
console.log(currentUser.get_id());
console.log( currentUser.get_title());
console.log(currentUser.get_email());
},
function(){ //On fail function
alert(‘Error: ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}
);
}
});

That all. Here is the result:

Capture3

 

Hope that code will be helpful for you.

Happy SharePointing 🙂