Understanding Representational State Transfer (REST)

Introduction

SharePoint 2013 introduces a Representational State Transfer (REST) service that is comparable to the existing SharePoint client object models. REST allows for a minimum data to be passed using the same well-established mechanism that defines the web without a lot of the encumbrances introduced by fatter protocols. It allows programmers to build programs easily that access and act upon data exposed via APIs, even in environments with unreliable network speeds and limited computing power. REST works almost exactly like a website in a browser. A resource is exposed to a program via a URL. This means the developers can perform CreateReadUpdate, and Delete (CRUD) operations from their SharePoint Add-ins, solutions, and client applications, using REST web technologies and standard Open Data Protocol (ODATA) syntax. ODATA standard defines a set of best practices for building and consuming RESTful APIs.

Continue reading Understanding Representational State Transfer (REST)

Automatically Run Programs and Windows Task Scheduler

Introduction

The Task Scheduler has a wide variety of uses such as automatically triggering job schedule, sending email notifications to the appropriate users etc. Scheduling tasks ensures that the productivity and optimum management. Manual scheduling consumes a whole lot of time and resources.

Scheduling a task by either creating a basic task using the ‘Create Basic Task’ or by creating a task using the ‘Create Task’ wizard screen.

Creating a Task

Here, we create the task by selecting the ‘Create Task’. To start, open the Task Scheduler, click the Create Task link at the right side of the Task Scheduler window screen. This link opens an easy-to-use wizard screen and will walk through the process of creating a task. If more advanced options are required click Create Task instead.

Specify a name and description for the task. This will help to remember what the task does later.

Select -trigger and opt the “Daily” option. The task runs daily, weekly, monthly, or only once. In addition, we can setup the task run when the computer starts or when the user logs on and can also have the task start in response to an event ID in the Windows event log history.

If you selected daily, weekly, monthly, or one time, you’ll be prompted to specify a specific time for the event to occur. In the below screen-shot, we have selected the ‘Daily’ option. The job will get start every day 7 AM at every 15 minutes for the duration of 17 hours. Means the job will start by 7 AM and it will end-up at 12 AM (7+17=24 hours).

Then, in the below screen we can opt any of the option like start a program, send an email, or display a message in response to the trigger you specific earlier.

To run a program, paste the required files under C:drive. Click the Browse button and locate the placed .exe/.bat/.ps file. In Start in (optional) paste the .bat file path only. By clicking ‘Next’ it will launch the task automatically at the scheduled time.

Now we are almost done – Windows will display the details of the task we have created. Click the Finish button and the task will be created. To modify further Advanced Settings enable the option “Open the Properties dialog for this task when I click Finish”.

Conclusion

This is one time implementation and no further maintenance is required. It reduces manual effort and based on the result it triggers email notifications to the respective users.

Provision SharePoint in One Click

Introduction

Provisioning SharePoint makes it easier for developers and the organization too, as it reduces time consuming manual effort and resource utilization. More importantly, it is a single-click, reusable component, suitable for anyone!

Here, we will see how to develop a reusable component – methods and functionalists.

SharePoint Web Application Creation

We will create a web application using server-side code. We can achieve the same using client-server object model and power-shell script too.

We will see important methods and the logic involved in creating a feature:

SPWebApplicationBuilder _webAppBuilder = new SPWebApplicationBuilder(SPFarm.Local);
 SPWebApplication _webApplication;
 _webAppBuilder.Port = 2255;
 Uri url = new Uri("http://spTestSite:2255/");
 string host = url.Host;
 int port = 2255;
 _webAppBuilder.HostHeader = host;
 _webAppBuilder.ApplicationPoolId = "Sharepoint - " + port.ToString();
 _webAppBuilder.IdentityType = IdentityType.SpecificUser;

SPFarmManagedAccountCollection manaccountcollection = new SPFarmManagedAccountCollection(SPFarm.Local);
SPManagedAccount maccount = manaccountcollection.FindOrCreateAccount(“DomainUserName”);

//use the SPManagedAccount to receive the username and password automatically
_webAppBuilder.ManagedAccount = maccount;
_webAppBuilder.RootDirectory = new System.IO.DirectoryInfo(“C:\Inetpub\wwwroot\wss\VirtualDirectories\” + host + port.ToString());
_webAppBuilder.CreateNewDatabase = true;

// Create new database name
_webAppBuilder.DatabaseName = “WSS_Content_” + host + port.ToString();

//Mention the database server name
_webAppBuilder.DatabaseServer = “SQL01”;
_webAppBuilder.UseNTLMExclusively = true;

// Create new web application
_webApplication = _webAppBuilder.Create();
_webApplication.Provision();

// Pass the parameter as per your requirement
SPSite mySiteCollection = _webApplication.Sites.Add(“/”, “Test Site”, “Site Description”, 1033, “STS#0”, “PrimaryDomainme”, “PrimaryAdminUserName”, “PrimaryTest@mail.com”);
mySiteCollection.Close();

In this method, we are creating a SharePoint web application using server-side code SPWebApplicationBuilder Member. This initializes a new instance of the class using the default Web application settings and exposes further properties like ManagedAccount, RootDirectory, CreateNewDatabase, DatabaseName, DatabaseServer, UseNTLMExclusively, et.,

The next level code is SPWebApplication Class – It represents Internet Information Services (IIS) load-balanced Web application that is installed on a server farm and exposes the methods as Delete(), Update(), etc.,

SharePoint Top-level Site Collection Creation

In the following method we will see how to create site collection through code using SharePoint objects SPSite, SPWeb and SPSiteCollection as below.

//Code to create site collection programmatically
 string _url = "http://spTestSite:2255/";
 SPSite site = new SPSite(_url);
 SPWeb web = null;
 try {
 SPWebApplication webapp = site.WebApplication;
 web = site.OpenWeb();
 SPSiteCollection spSites = webapp.Sites;
 webapp.Sites.Add("sites/team1", "Title of the Site", "Description", 1033, "STS#0", "PrimaryDomainName", "PrimaryAdminUserName", "PrimaryTest@mail.com");
 }

At this point we have created the web application and the top-level site collection as needed. Where, “sites/team1” is the top level site, “Title of the Site” is to mention the name/title of the top-level site, “Description” is to mention the description, “1033” is the English language code, “STS#0” is the sharepoint site template code, “PrimaryDomainName” is the required primary domain name, “PrimaryAdminUserName” is the first primary admin user and “PrimaryTest@mail.com” is the primary admin user email id.

Further, “Sites.Add()” method will create/add the site collection into the web application with the required parameter as we described in the code.

SharePoint Required Default Features Activation for the Team Site

Next, we need to move on- to activate the SharePoint required features ‘Activate SharePoint Server Publishing Infrastructure’ and ‘Activate the publishing feature’. These features will not get activated by default when the site been created as a “Team Site (STS#0)”. So, let’s activate the same features using code as below.

//Code to activate Sharepoint Features programmatically
 string _url = "http://spTestSite:2255/";
 SPSite site = new SPSite(_url);
 if (site != null) {
 // Activate SharePoint Server Publishing Infrastructure
 site.Features.Add(new Guid("f6924d36-2fa8-4f0b-b16d-06b7250180fa"), true);
 foreach(SPWeb web in site.AllWebs) {
 // Activate the publishing feature for all created webs.
 web.Features.Add(new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb"), true);
 }
 }

Where, SPSite object used to get the current site, the Guid (“f6924d36-2fa8-4f0b-b16d-06b7250180fa”) is the “SharePoint Server Publishing Infrastructure” feature which activates the feature at site level.

Next, the Guid (“94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb”) is the “SharePoint Server Publishing” feature which activates the feature at web level.

SharePoint Group Creation and Role Assign

Now, we create the group using the object SPGroup. First, we check whether the group is created or not using the object SPGroupCollection. Once the group has been created, assign the role using the object ‘SPRoleDefinition’ and ‘SPRoleAssignment ’.

SPGroup groupMngr = null;
 //check group already exists or not
 if (!ContainsGroup(web.SiteGroups, web.Title + "_" + CustomTestGroup)) {
 web.SiteGroups.Add(web.Title + "_" + CustomTestGroup, web.Author, web.Author, "CustomTestGroup");
 groupMngr = web.SiteGroups[web.Title + "_" + CustomTestGroup];
 groupMngr.OnlyAllowMembersViewMembership = false;
 groupMngr.Update();

// assign edit permissions to ‘CustomTestGroup’
SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Editor);
SPRoleAssignment roleAssignment = new SPRoleAssignment(groupMngr);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
web.RoleAssignments.Add(roleAssignment);
web.Update();
}

private bool ContainsGroup(SPGroupCollection groupCollection, string index) {
try {
SPGroup testGroup = groupCollection[index];
return true;
} catch (SPException e) {
return false;
}
}

SharePoint List/Libraries Creation

We then create the document library using the object ‘SPList’, ‘SPDocumentLibrary’. Checking if the library does not exist, create the new list or library as per the requirement. Once the library is created, create the necessary fields with the type accordingly using the object ‘SPFieldType’. Enable the library versioning. Next, break the Inheritance permission of the library and assign custom group permission. Then, create the custom view using the object ‘SPView’ and mention which column should appear in the view state. Finally, update the library at the last to complete the process.

string CustomerLibraryName = “customLibrary”;
 SPList list = web.Lists.TryGetList(CustomerLibraryName);
 if (list == null) {
 Guid customerGUID = web.Lists.Add(CustomerLibraryName, "Custom Document Library", SPListTemplateType.DocumentLibrary);
 SPDocumentLibrary CustomerDocLibrary = web.Lists[customerGUID] as SPDocumentLibrary;

CustomerDocLibrary.Fields.Add(“columnDocName”, SPFieldType.Text, true);
CustomerDocLibrary.Fields.Add(“columnDocCreator”, SPFieldType.Text, true);
CustomerDocLibrary.Fields.Add(“columnDocContributors”, SPFieldType.Text, true);
CustomerDocLibrary.Fields.Add(“columnDocSubject “, SPFieldType.Text, true);
CustomerDocLibrary.Fields.Add(“columnDocDate”, SPFieldType.DateTime, true);

//enable versioning
CustomerDocLibrary.EnableVersioning = true;

//check Inheritance broken or not
if (!CustomerDocLibrary.HasUniqueRoleAssignments) {
CustomerDocLibrary.BreakRoleInheritance(true);
}

CustomerDocLibrary.RoleAssignments.Add(roleAssignment); CustomerDocLibrary.Update();

SPView CustomerView = CustomerDocLibrary.DefaultView; CustomerView.ViewFields.DeleteAll(); CustomerView.ViewFields.Add(“columnDocTitle”); CustomerView.ViewFields.Add(“columnDocLinkFileName”); CustomerView.ViewFields.Add(“columnDocDate”); CustomerView.Update(); CustomerDocLibrary.Update(); web.Lists[customerGUID].Update();
}

Finally, place all implemented code in the SharePoint event receiver file and once the file gets deployed successfully into the SharePoint site, activate the event receiver then the required lists/library, fields and group creation with assigned role. This will create the same in SharePoint, avoids manual creation and helps to save time!