Sivarajan's Blog

SharePoint | Office 365 | Azure | JavaScript

Client WebPart Starter Project for SharePoint On-Premise / Online using AngularJs with Gulp

Overview SharePoint Framework is completely a client side development model and Microsoft is going to release it soon. As per their notes, this will support only SharePoint Online and SharePoint 2016. This post is mainly who is currently working with SharePoint 2010/2013. Instead of developing a Visual/Standard WebPart, you can build the entire development using front-end technologies (AngularJs, ReactJs or KnockoutJs) and later you can easily convert it into SharePoint Framework easily. Tools and Frameworks I have used the following tools and frameworks for build the starter project. Visual Studio Code and JavaScript IntelliSense This is an open source and cross-platform IDE. Here you can find more details about VS Code and why I used for client side development. Similarly, you can find that how to enable the JavaScript IntelliSense for your project. Node.Js and NPM I have used Node.Js for build and deployment and NPM for install the node packages (AngularJs, Gulp, etc.). Here you can find more details about Node.Js and NPM Gulp This is a build automation tool.  Here you can find more details about Gulp Office UI Fabric This is UI framework for Office 365 and SharePoint, similar to Bootstrap. You can ignore if you are not familiar with this. Setup the Project in Local Machine Please make sure that you installed and configured Visual Studio Code, NodeJs and Gulp properly. If everything is working properly then, you can continue further. You can download the starter project from GitHub location and extract zip file in your local machine. Open the folder in VS code. Package.json file Open the package.json and you can find the two attributes dependencies and devDependencies. { "name": "spo-ng-officeuifabric-gulp", "version": "1.0.0", "description": "SharePoint Angular Office UI Fabric Starter App with Gulp", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Sivarajan Raju", "license": "MIT", "dependencies": { "angular": "^1.5.8", "angular-router": "0.0.2", "ng-office-ui-fabric": "^0.12.2", "office-ui-fabric": "^2.6.1" }, "devDependencies": { "gulp": "^3.9.1", "gulp-changed": "^1.3.1", "gulp-concat": "^2.6.0", "gulp-notify": "^2.2.0", "gulp-sourcemaps": "^1.6.0", "gulp-spsync": "wictorwilen/gulp-spsync", "gulp-uglify": "^1.5.4", "gulp-watch": "^4.3.9" } } Open the extracted file location in the command prompt and run the below command. > npm install Now all the dependencies will be installed in your local machine and you can see the modules under node_modules folder. Gulpfile.js file The next important file is Gulpfile.js file. Open this file and you can find the multiple tasks. Lets see in detail below. This is a list of gulp related plug-ins I used.var gulp = require('gulp'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var notify = require('gulp-notify'); var sourcemaps = require('gulp-sourcemaps'); var changed = require('gulp-changed'); var sp = require('gulp-spsync'); var watch = require('gulp-watch'); //Change your project name here var PROJECT_NAME = 'spo-ng-officeuifabric-gulp'; Authentication Settings I have used gulp-spsync plug-in for for synchronizing local files with a SharePoint library. We need to create security token for SharePoint authentication. Please follow this link to create the client_id ad client_secret and update settings section. var settings = { "client_id":"your here client", "client_secret":"your here client code secret", "realm" : "", "site" : "https://your tenent.sharepoint.com/", "verbose": "true" }; Task : build-app //Combine all the JavaScript files (Controllers and Services) under the App folder and create 'combined.js' file for upload to SharePoint. //with sourcemaps for debugging gulp.task('build-app', function () { console.log('start - dev task'); return gulp.src(SOURCE_APP_SCRIPT_PATH) .pipe(sourcemaps.init()) .pipe(concat('combined.js')) .pipe(sourcemaps.write()) .pipe(gulp.dest(DEST_APP_SCRIPT_PATH)); }); Task : spupload-app //Call the build-app task and then upload the combined.js to SharePoint gulp.task('spupload-app',['build-app'], function() { console.log('starting spupload-app'); return gulp.src('content/**/scripts/*.*') .pipe(sp(settings)) }); Task : spupload-views //upload the HTML templates from content/_catalogs/masterpage/spo-ng-officeuifabric-gulp/views folder to SharePoint gulp.task('spupload-views', function() { return gulp.src('content/**/views/*.*') .pipe(changed('_build')) .pipe(sp(settings)) .pipe(gulp.dest('_build')) }); Task: watch //Whenever we modify the JavaScript files or HTML templates, this task will help to upload the modified file to SharePoint immediately. gulp.task('watch', function() { gulp.watch('content/**/views/*.*', ['spupload-views']); gulp.watch('app/**/*.js', ['spupload-app']); }); Task: copy-npmjs //Each npm packages will have a minified and unminified JavaScript files with documentations. //But we need only minified versions and run this task to copy the mentioned js files to our content folder gulp.task('copy-npmjs', function () { console.log('starting external-scripts task'); return gulp.src([ /* JS Files */ 'node_modules/angular/angular.min.js', 'node_modules/ng-office-ui-fabric/ngOfficeUiFabric.min.js' ]).pipe(gulp.dest(DEST_EXTERNAL_SCRIPTS_PATH)); }); Task: copy-npmcss //Each npm packages will have a minified and unminified CSS files with documentations. //But we need only minified versions and run this task to copy the mentioned css files to our content folder gulp.task('copy-npmcss', function () { console.log('starting external-scripts task'); return gulp.src([ /* CSS Files */ 'node_modules/office-ui-fabric/dist/css/fabric.css', 'node_modules/office-ui-fabric/dist/css/fabric.components.css' ]).pipe(gulp.dest(DEST_EXTERNAL_CSS_PATH)); }); Task: spupload //Upload all the files from content folder to SharePoint including external JavaScripts gulp.task('spupload', function() { return gulp.src('content/**/*.*') .pipe(sp(settings)) .pipe(gulp.dest('_build')) }); Run the gulp task. > gulp <task name> >gulp spupload Now all your files under content folder will be uploaded to SharePoint master page gallery. https://<your tenent>.sharepoint.com/_catalogs/masterpage/Forms/AllItems.aspx   Use the following gulp task for incremental uploads, > gulp watch View the Results We can view the results by using Script/Content Editor. I have used content editor webpart. Add the two content editor webpart in your SharePoint page and set the content link to /_catalogs/masterpage/spo-ng-officeuifabric-gulp/views/include-script.html and /_catalogs/masterpage/spo-ng-officeuifabric-gulp/views/main.html respectively. Summary The advantages of the approach is, while you are working in your local machine, the latest changes will be combined and minified and will be uploaded silently to SharePoint. You can see the latest changes by simply refresh your SharePoint page. I tested this starter project against SharePoint online. For SharePoint On-premises, you need to include the following gulp plug-in additionally. https://github.com/estruyf/gulp-spsync-creds Please let me know if you are facing any issues. Download Source

Retrieve the List item Version History and Attachment URLs in SharePoint

Overview I had a requirement to retrieve the version history and attachment URLs for the list item at client side. We will see here how to retrieve that. List item Version History Instead of using the .NET client object model, we can retrieve the list item using SharePoint list web service (Lists.asmx) easily. public static string GetVersions(string siteUrl, string listId, string itemId, string fieldName) { StringBuilder sb = new StringBuilder(); Lists listService = new Lists(); listService.Credentials = System.Net.CredentialCache.DefaultCredentials; listService.Url = siteUrl + "/_vti_bin/lists.asmx"; #region Get version histories if (!string.IsNullOrEmpty(fieldName)) { XmlNode nodeVersions = listService.GetVersionCollection(listId, itemId, fieldName); foreach (System.Xml.XmlNode xNode in nodeVersions) { string dateHistory = xNode.Attributes["Modified"].Value; dateHistory = FormatDateFromSP(dateHistory); string commentHistory = xNode.Attributes[fieldName].Value; string editor = GetEditor(xNode.Attributes["Editor"].Value); sb.Append(editor + " (" + dateHistory + ") " + commentHistory + "\n\n"); } } #endregion return sb.ToString(); }     This method will return the version history for the particular list column. List Item Attachment URLs Similarly we can retrieve the attachment URLs for the specific list item using Lists.asmx web service.         public static string GetAttachmentUrls(string siteUrl, string listId, string itemId, string fieldName)         {             StringBuilder sb = new StringBuilder();             Lists listService = new Lists();             listService.Credentials = System.Net.CredentialCache.DefaultCredentials;             listService.Url = siteUrl + "/_vti_bin/lists.asmx";             #region Get the list of attachments             XmlNode nodeAttachments = listService.GetAttachmentCollection(listId, itemId);             List<string> values = new List<string>();             foreach (System.Xml.XmlNode xNode in nodeAttachments)             {                 values.Add(xNode.InnerText);             }             return string.Join(";", values.ToArray());             #endregion         } This will return the list of attachments URLs for the particular list item.

Generic List Helpers for .NET Client object model in SharePoint 2013/Office 365

Overview We are using lot of helper methods in day to day activities for manipulating the SharePoint list data. In this post, we will see that how to play with Choice and Lookup Field. Retrieving data using Choice Field (Multiple items) In the choice field, we can add the list of string values or numeric values. But always it will return as object and then we will convert the value to array of object or string. public static string GetChoiceValues(object values) { List<string> results = new List<string>(); if (values != null) { string[] arr = ((IEnumerable)values).Cast<object>() .Select(x => x.ToString()) .ToArray(); foreach (string value in arr) { results.Add(value); } return string.Join(";", results.ToArray()); } return string.Empty; }   Alternative Approach : Retrieving data using Choice Field (Multiple items) Now we will write the same code in different way to retrieve the values using Generic type. So here we can avoid explicit type casting on each and every time. public static List<T> GetChoiceFieldValue<T>(object itemValue) { if (itemValue != null) { return ((IEnumerable)itemValue).Cast<object>() .Select(x => (T)Convert.ChangeType(x, typeof(T))) .ToList<T>(); } return null; }   Usage: List<double> values = ListHelper.GetChoiceFieldValue<double>(item["value1"]); So we can use the same helper method for any data types. Sometime, we may require the selected choice field values as string (comma separated), we will use the following code for that, public static string GetChoiceFieldMultiValue(object itemValue, string delimiter)         {             if (itemValue != null)             {                 List<string> values = GetChoiceFieldValue<string>(itemValue);                 if (values != null && values.Count() > 0)                 {                     return string.Join(delimiter, values.ToArray());                 }                 return null;                            }             return null;         } Usage: string value = ListHelper.GetChoiceFieldMultiValue(item["value1"], ";");  Retrieving data using Choice Field (Single item) If the choice field has created with display option either Radio or Dropdown, we can use the following code to retrieve the selected single value from that. public static T GetChoiceFieldSingleValue<T>(object itemValue)         {             if (itemValue != null)             {                 return (T)Convert.ChangeType(itemValue, typeof(T));             }             return default(T);         } Retrieving data using Lookup Field (Allow Multiple Items) Similarly, we will see how to retrieve the values from Lookup column if the lookup has created with multiple value selection option.         public static List<T> GetLookupFieldValue<T>(object itemValue)         {             if (itemValue != null)             {                 var itemValueArray = itemValue as Microsoft.SharePoint.Client.FieldLookupValue[];                 if (itemValueArray != null && itemValueArray.Count() > 0)                 {                                        return ((IEnumerable)itemValue).Cast<FieldLookupValue>()                                  .Select(x => (T)Convert.ChangeType(x.LookupValue, typeof(T)))                                  .ToList<T>();                 }             }             return null;         } Note: Always the LookupValue attribute will return the value as string. Usage: List<string> values = ListHelper.GetLookupFieldValue<string>(item["Value2"]); We can also use the following method, suppose if we want to retrieve the values with keys.        public static Dictionary<int, T> GetLookupFieldUserIdValue<T>(object itemValue)         {             List<string> results = new List<string>();             if (itemValue != null)             {                 var itemValueArray = itemValue as Microsoft.SharePoint.Client.FieldLookupValue[];                 if (itemValueArray != null && itemValueArray.Count() > 0)                 {                     return ((IEnumerable)itemValue).Cast<FieldLookupValue>()                         .ToDictionary(                                     x => x.LookupId,                                     x => (T)Convert.ChangeType(x.LookupValue, typeof(T)));                                                }             }             return null;         } Usage: Dictionary<int,string> values = ListHelper.GetLookupFieldKeyValue<string>(item["Value2"]); Summary We can use the same approach in Office 365 provider hosted App and will see how to work with other fields (Date, Managed Mata data, etc.) in the next post. Download Source Code

How to create a reusable SharePoint Server 2013 bootable VHD using trial downloads – Part 6

Configuring Active Directory Domain Services Currently our machine is running under Workgroup. Domain services is mandatory for configuring SharePoint Server 2013. We will follow the below link to configure the ADDS. Before starting this process, change our machine name, for my case, I am going to rename to WIN2012SP2013. Use the below link for detailed walkthrough. http://www.sharepointpals.com/post/How-to-Configure-Active-Directory-Domain-Services-on-Windows-Server-2012 For my case, I have configured like below, Once complete the ADDS setup, don’t forget the following change the below settings for user account. Configuring SQL Server 2012 R2 using Prepared Image While preparing a VHD, we have installed SQL Server using prepared image option. Before configuring SharePoint, we should configure the SQL instance. In the start-up menu, click the Complete SQL Server 2012 Installation to complete the SQL server configuration. In the Feature Review tab, we can see the installed SQL Server features. In the Instance Configuration tab, select the default instance, In the Server Configuration tab, set the SQL Server Analysis Services account to System, In the Database Engine Configuration, set the accounts like below, And change the Data Directories like below, In the Ready to Complete Image tab, we can see the Edition and Action as Evaluation and CompleteImage In the Complete tab, we can see the list of configured features, Now we have done the SQL server configuration steps. In the next steps, we will see how to configure the SharePoint. Configuring SharePoint 2013 In the short, we will how to configure the SharePoint 2013 in few steps, Note: you can find the detailed installation steps here   Step 1: Create a new server farm Step 2: Specify the Database Settings Step 3: Specify the port number   Step 4: Here we can see the SharePoint successful configuration message. That’s it. We have completed the SharePoint 2013 VHD using native bootable mode. Please feel free to conduct me if you have any questions on regarding setting up the VHD. For other posts on this series Overview of the native bootable VHD and list of required software Create a native bootable virtual hard drive, installing windows server 2012 and configure boot menu Enabling desktop features in windows server 2012 SQL Server installation using slipstream mode, create the SP1 slipstream into SharePoint 2013 and single shot installation Create a master native bootable VHD using sysprep method Configuring Active Directory and Domain Services, SQL Server 2012 and SharePoint 2013

How to create a reusable SharePoint Server 2013 bootable VHD using trial downloads – Part 5

Prepare Master VHD using sysprep Command We have completed list of actions currently. Prepared bootable Virtual Hard drive. Installed Windows Server 2012 Configured Desktop features Created image for SQL Server 2012 SP1 +CU9 Create slipstream Service Pack 1 into SharePoint Server 2013 Installed SharePoint 2013 (configuration later) Installed Visual Studio 2013, MS Office 2013 and Visio 2013 with trial keys. Installed SharePoint Designer 2013 Now we are going to execute the sysprep commend to remove the trial keys and user related details. Please follow the below link to know more details about sysprep command, http://technet.microsoft.com/en-us/library/cc721940(v=ws.10).aspx 1. Run the sysprep command and select the following options. 2. System will shut down, once complete the clean-up process. After successful completion of sysprep operation, we should get login to our base OS and take the backup of the VHD. We should treat this copy as master. Now again we get login into Windows Server 2012 trial and we can see the windows server installation wizard start freshly. On successful completion, we can see all our installed software’s trial periods has been refreshed except machine name. The following activities are pending to finish the VHD process. Configuring the Active Directory and setting up the domain services. Configuring SQL Server using image Configuring SharePoint 2013 In the next post, we will configure Active Directly and Domain Services for installing SharePoint. For other posts on this series Overview of the native bootable VHD and list of required software Create a native bootable virtual hard drive, installing windows server 2012 and configure boot menu Enabling desktop features in windows server 2012 SQL Server installation using slipstream mode, create the SP1 slipstream into SharePoint 2013 and single shot installation Create a master native bootable VHD using sysprep method Configuring Active Directory and Domain Services, SQL Server 2012 and SharePoint 2013