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”; //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 🙂

 

Advertisements

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 🙂

 

 

 

SharePoint get followed sites using REST Api


Recently I was tasked with a project requirement that the user should be able to see list of content he/she followed. To me this sounds much like using the following feature of SharePoint 2013 which allows you to follow documents, sites, people and tags. Also, we don’t want the user to navigate to his/her mySite and have a look on to the content followed.

We can use the SharePoint 2013 Representational State Transfer (REST) service to do the same tasks you can do when you use the .NetCSOM, JSOM.

Here I explain how to retrieve the site name and URL followed by the current user in SharePoint 2013 using a client object model (REST API and JavaScript) and displaying it in the SharePoint page.

1. Create a new page and a Content Editor Webpart (CEWP).

Create a New page

2. Edit the web part that was added to the page.

Edit the web part

3. Upload your text file script into the site assests and copy the path of the text file and paste it into the Content link in CEWP.

4. Output

Output

Code

The following example shows how to retrieve all of the following sites:

<html>
<head>
<script type=”text/javascript” src=”//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js”></script>

<script type=”text/javascript”>
var followingManagerEndpoint;
var followedCount;

var followingEndpoint;
var URL;
var website;
var clientContext;

SP.SOD.executeFunc(‘sp.js’, ‘SP.ClientContext’, loadWebsite);
function loadWebsite() {
clientContext = SP.ClientContext.get_current();
website = clientContext.get_web();
clientContext.load(website);
clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
}

function onRequestSucceeded() {

URL = website.get_url();
followingManagerEndpoint = decodeURIComponent(URL) + “/_api/social.following”;

getMyFollowedContent();
}

function onRequestFailed(sender, args) {
alert(‘Error: ‘ + args.get_message());
}

// Get the content that the current user is following.
// The “types=14” parameter specifies all content types
// (documents = 2 + sites = 4 + tags = 8).
function getMyFollowedContent() {

$.ajax( {
url: followingManagerEndpoint + “/my/followed(types=14)”,
headers: {
“accept”: “application/json;odata=verbose”
},
success: followedContentRetrieved,
error: requestFailed
});
}

// Parse the JSON data and iterate through the collection.

function followedContentRetrieved(data) {
var stringData = JSON.stringify(data);
var jsonObject = JSON.parse(stringData);
var types = {
1: “document”,
2: “site”,
3: “tag”
};

var followedActors = jsonObject.d.Followed.results;
var followedList = “You’re following items:”;

for (var i = 0; i < followedActors.length; i++) {
var actor = followedActors[i];
followedList += “<p>The ” + types[actor.ActorType] + “: \”” +actor.Name + “\”</p>”+”<p>Site URL ” + “: \”” +
actor.Uri+ “\”</p>”;;
}
$(“#Follow”).html(followedList);
}

function requestFailed(xhr, ajaxOptions, thrownError) {
alert(‘Error:\n’ + xhr.status + ‘\n’ + thrownError + ‘\n’ + xhr.responseText);
}

</script>
</head>
<body>
<div id=”Follow”></div>
</body>
</html>

Happy SharePointing 🙂