Create SharePoint Framework client side web part for SharePoint On Premises

SharePoint Framework 

  • A new development  (page and part) model for building SharePoint customization.
  • It enables client-side development for building SharePoint experiences.
  • It facilitates easy integration with the SharePoint data and provides support for open source tooling development.

I’m not focusing on what is SPFx and why we use it etc as there are lot of blogs information available, I’ll focus on how to develop and deploy components using SPFx approach.

To have an overview of SPFx, please follow the below tutorials and also look for others as well 😉

Link 1

Link 2

Introduction:

This post introduces you how to develop and deploy SPFx client side web part for SharePoint Server On Premises Environment.

Prerequisites:

  • SharePoint Server 2016 with September 2017 CU
  • SharePoint Feature Pack 2 to enable SharePoint On Premises development
  • Node JS v 6.12
  • SPFx version 1.4 (I’m using 1.4, you can also use 1.3) both supports SP On Premises development

For setting up environment please follow the steps mentioned in the video tutorial

Tools & Technologies

  • PnP JS Core (To Perform CRUD operations), take a look on PnP JS Core
    1. Link 1
    2. YouTube Link
  • VUE JS (JS framework to render the list items)
  • Node JS, TypeScript, Gulp and SharePoint Yeoman Generator to create basic scaffolding/structure of the project and to perform different operations.
  • Visual Studio Code (IDE for SPFx Component development)

lets start step by step

1.Preparing basic project structure / scafolding

    • create a folder on file system with the name “SPFxDemo”, i’ve created under C:\work\SPFxDemo
    • Run Node JS command line as Admin
    • change the directory to “c:\work\SPFxDemo”
    • create project by typing command “yo @microsoft/sharepoint”
    • enter the solution and webpart name, description etc, make sure you selected baseline package for target component “SharePoint 2016 onwards, including SharePoint Online” means this component can be used in SharePoint On Premises and for SharePoint Online as well
    • here is my configurations, see the below screenshot

  • once the scaffolding is done, you would see a success message as

2. Installing / Configuration of PnP JS Core and VUE JS

    • npm install vue@2.3.4 –save
    • npm install sp-pnp-js –save
    • Once PnP and Vue JS installation done, open the code by typing “code .” command

    • Open config -> config.json file and add vue js in externals

Hosting SPFx component assets to SharePoint: we need to store SPFx web part assets somewhere to reference it so you can use CDN or SharePoint server, in this post i’m using SharePoint server document library to store web part assets

    • Create a folder “DemoFiles” in document lib in site contents and add that path to cdnBasePath in Config -> write-manifests.json file

Getting data from SharePoint using PnP and Rendering using VUE JS:

    • Open webpart main file src -> webparts  -> spfxDemo -> SpFxDemoWebpart.ts and add these two references into the file
      • import * as Vue from ‘vue’;
      • import * as pnp from ‘sp-pnp-js’;
    • Render method code


Testing component on local workbench:

  • Run the command “Gulp Serve” to run the application in the Local workbench, it will show nothing ;); you need to run your webpart under SharePoint server workbench as it is SharePoint On Premises component getting the data from SharePoint.
  • open the workbench from your SharePoint server “http://win-464hm9kh0hb:2016/_layouts/15/workbench.aspx
  • click on + button, system will display all available components so select SPFxDemo as shown

Finally here is the result 😉 we are getting the data from SharePoint list and rendering it using VUE JS

Edit the webpart to give any title in the description property.

3. Deploying SPFx client side webpart to SharePoint Server On Premises
MAKE SURE YOU HAVE CONFIGURED APPS FOR CATALOG PROPERLY, How to Configure it click HERE

  • Open Node JS command prompt and enter “CTRL + C” to terminate the current process
  • Run the following commands one by one
    • gulp bundle –ship
    • gulp package-solution –ship
  • Copy the webpart asset files from the project directly directory, these are under /temp/deploy, for me here is the location “C:\work\SPFxDemo\temp\deploy”
  • Place them in the hosting location, I’m using document library so here is that path “http://win-464hm9kh0hb:2016/Documents/DemoFiles“, publish the asset files if you want to show the webpart to anonymous users.

Note: By Default json files are blocked to uploaded into SharePoint, so remove json file from the list Central Administration – > Security -> General Security section -> Define blocked types types

    • Open Apps catalog site and upload the webpart .sppkg file, it is under /sharepoint/solution/ in the project directly….I’ve this path “C:\work\SPFxDemo\sharepoint\solution”
    • When you upload the package, it will prompt you from where webpart will get the contents as shown

  • Click on deploy and deployment is now DONE

4. Adding SPFx webpart to a Page

    • Go to site contents -> add an app -> select sp-fx-demo-client-side-solution app from the apps.

    • Once app would be added, create a page and add that webpart on SharePoint page; as i didn’t defined any group for the webpart so it would be under the “Others Categories

    • Click on Add button, here we go 😉

Some Useful commands for SPFx and Node JS
commands

few tips to improve SharePoint site Performance

Hi,

According to my practical experience, here are some tips to improve SharePoint site performance.

Note: covered only the area where we don’t need to write any code, there are also some more tips over the internet if you need to improve the site using C# code where one should follow the Best SharePoint development practices.

1) Web.Config changes
web.config file Path on Web server C:\inetpub\wwwroot\wss\VirtualDirectories
– stop debuging <compilation debug=”false”>
– enable blob cache <BlobCache enabled=”true”
– Custom errors mode ON <customErrors mode=”On” />
2) Implement caching, i use the HTML 5 local storage for our client. i have also add some code to refresh the cache after two Hours

– Store result set in the object

var storageKey = "EmployeesDataSaved"
localStorage.removeItem(storageKey);
var object = { StoredData: "YourResultSet", timestamp: new Date() }
localStorage.setItem(storageKey, JSON.stringify(object));
//To Get the data
var localStorageObj = JSON.parse(localStorage.getItem(storageKey));
        if (GetDateDiffInHours(localStorageObj) >= 2) {
            //code to get data from the database to refresh cache
        }
         else
            localStorageObj.StoredData; //loading the data from cache

function GetDateDiffInHours(localStorageObj) {
    var savedDate = parseInt(new Date(localStorageObj.timestamp).getTime() / 1000);
    var currentDate = new Date().getTime() / 1000;
    var hoursDiff = (currentDate - savedDate) / 3600;
    return hoursDiff;
}

3) Managing Styles and Scripts
– remove all inline styles and scripts, put them in a separate file
Minify all JS and CSS files
4) Reduce HTTP Number of requests
– Use CSS Sprite images for icons and small images
– use SVG for images as it will go to the server only once to load the one image and for the rest, we are just using the Hash # sign to get relevant image e.g /images/icons.svg#email, /images/icons.svg#phone etc
– Try to combine all CSS files into one file as much as possible
– Try to combine/merge all js files into one file

5) Optimize / compress Images
– Optimize all images that are being used in the site using online websites like tiny png
– reduce image size
– use the Progressive images intead of standard JPEG, for refernece click here

Test Your Site using the following sites

1) GT Metrix
2) Webpage Test
3) Validate html markups

Get File / Image Details from URL

Hi,

There was a requirement from client that they want to get any image detail from SharePoint that will not be the specific list or library?

i’ve tried the WebClient but it not works, WebClient is working fine for Public images but for SharePoint it requires the authentication.

let me show you what i have done with WebClient

My Requirement was to get the image details from the URL

  1. File/image name
  2. Extension
  3. Base64 string

so on the first hand i tried the WebClient


string filePath = "http://6iee.com/data/uploads/9/409437.jpg";//any url of an image i.e go to google images
singleItem.FileName = Path.GetFileName(filePath);
singleItem.FileExtension = Path.GetExtension(filePath);
singleItem.FileContents64Bit = this.ImageToBase64(filePath);
private string ImageToBase64(string filePath)
{
try
{
using (WebClient webClient = new WebClient())
{
byte[] bytes = webClient.DownloadData(filePath);
MemoryStream ms = new MemoryStream(bytes);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
bytes = ms.ToArray();
base64String = Convert.ToBase64String(bytes);
}
}
catch (Exception ex)
{
throw ex;
}
return base64String;

#region image from local drive to base 64
// //string path = "c:\\files\\devicedetails.jpg";
// //using (system.drawing.image image = system.drawing.image.fromfile(path))
// //{
// // using (memorystream m = new memorystream())
// // {
// // image.save(m, image.rawformat);
// // byte[] imagebytes = m.toarray();
// // base64string = convert.tobase64string(imagebytes);
// // return base64string;
// // }
// //}
#endregion
}

Problem with WebClient

it was when i try to pass the filePath of a SharePoint intranet site and it requires the authentication and it says “The remote server returned an error: (403) Forbidden

Solution:

as client only required to get SharePoint image details (File Name, Extension and Base64 string) so i’ve written the following code to achieve

Note: this is not for specific list/lib, it will get the file from root site, subsite etc from the url


public ImageDetails GetImageDetails(string imageUrl)
{
ImageDetails singleItem = new ImageDetails();
SPFile file= null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite sps = new SPSite(imageUrl))
{
using (SPWeb spw = sps.OpenWeb())
{
file = spw.GetFile(imageUrl);

byte[] imageBytes = file.OpenBinary(SPOpenBinaryOptions.None);
singleItem.FileName = Path.GetFileNameWithoutExtension(file.Name);
singleItem.FileExtension = Path.GetExtension(file.Name);
singleItem.FileContents64Bit = Convert.ToBase64String(imageBytes.ToArray());
}
}
});
}
catch (Exception ex)
{
throw ex;
}
return singleItem;
}

public class ImageDetails
{
public string FileName { set; get; }

public string FileExtension { set; get; }

public string FileContents64Bit { set; get; }
}

thats it 😉

Create Bar Chart from SharePoint 2013 List

Guys,

today i had also created a Bar Chart using Google API in SharePoint 2013 by creating a Custom WebPart.

here is my custom SharePoint List (DepartmentBudget)

list updated

 

 

 

 

 

 

 

 

 

 

 

 

 

see the webpart Properties

webpart-properties-bar-chart

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

BAR Chart

bar Chart

CSS class

.BarChartDepartment
    {
	 width:100%;
     height:500px;
     }

.ascx Page

&amp;amp;amp;lt;asp:Label ID=&amp;amp;quot;lblError&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot;&amp;amp;amp;gt;&amp;amp;amp;lt;/asp:Label&amp;amp;amp;gt;

&amp;amp;amp;lt;script type=&amp;amp;quot;text/javascript&amp;amp;quot; src=&amp;amp;quot;https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['bar']}]}&amp;amp;quot;&amp;amp;amp;gt;&amp;amp;amp;lt;/script&amp;amp;amp;gt;
&amp;amp;amp;lt;div&amp;amp;amp;gt;
    &amp;amp;amp;lt;asp:Literal ID=&amp;amp;quot;ltrlScript&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot;&amp;amp;amp;gt;&amp;amp;amp;lt;/asp:Literal&amp;amp;amp;gt;
    &amp;amp;amp;lt;asp:Literal ID=&amp;amp;quot;ltrlCharts&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot;&amp;amp;amp;gt;&amp;amp;amp;lt;/asp:Literal&amp;amp;amp;gt;
&amp;amp;amp;lt;/div&amp;amp;amp;gt;

.ascx.cs Page

#region All Custom Properties

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;web Name&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;web url&amp;amp;quot;)]
        public string webName { get; set; }

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;Chart Title&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;Title of the Chart&amp;amp;quot;)]
        public string ChartTitle { get; set; }

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;List Name&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;List name of department budget&amp;amp;quot;)]
        public string ListName { get; set; }

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;Category Field&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;Category Field Name&amp;amp;quot;)]
        public string CategoryField { get; set; }

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;Value Field 1&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;Field Name of which you want to generate chart&amp;amp;quot;)]
        public string ValueField1 { get; set; }

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;Value Field 2&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;Field Name of which you want to generate chart&amp;amp;quot;)]
        public string ValueField2 { get; set; }

        #endregion

		protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    CreateDepartmentPieChart();
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }

            this.ChromeType = PartChromeType.None;
        }

        private void CreateDepartmentPieChart()
        {
            SPListItemCollection itemsColl = GetAllItemsByBudget();
            if (itemsColl != null &amp;amp;amp;amp;&amp;amp;amp;amp; itemsColl.Count &amp;amp;amp;gt; 0)
            {
                StringBuilder script = new StringBuilder();

                script.AppendLine(&amp;amp;quot;&amp;amp;amp;lt;script type=\&amp;amp;quot;text/javascript\&amp;amp;quot;&amp;amp;amp;gt;&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot;google.load(\&amp;amp;quot;visualization\&amp;amp;quot;, \&amp;amp;quot;1\&amp;amp;quot;, {packages:[\&amp;amp;quot;corechart\&amp;amp;quot;]});&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot;google.setOnLoadCallback(drawChart);&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot;function drawChart() {&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; var data = google.visualization.arrayToDataTable([&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; ['&amp;amp;quot; + CategoryField + &amp;amp;quot;', '&amp;amp;quot; + ValueField1 + &amp;amp;quot;', '&amp;amp;quot; + ValueField2 + &amp;amp;quot;'],&amp;amp;quot;);
                for (int i = 0; i &amp;amp;amp;lt; itemsColl.Count; i++)
                {
                    script.AppendLine(&amp;amp;quot; ['&amp;amp;quot; + itemsColl[i][CategoryField] + &amp;amp;quot;', &amp;amp;quot; + itemsColl[i][ValueField1] + &amp;amp;quot;, &amp;amp;quot;+ itemsColl[i][ValueField2] + &amp;amp;quot;],&amp;amp;quot;);
                }
                script.AppendLine(&amp;amp;quot; ]);&amp;amp;quot;);

                script.AppendLine(&amp;amp;quot; var options = {&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot;chart:{&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; title: '&amp;amp;quot; + ChartTitle + &amp;amp;quot;'&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; },&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; bars:'vertical',&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; vAxis:{format:'decimal'},&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; colors:['green','red']&amp;amp;quot;);

                script.AppendLine(&amp;amp;quot; };&amp;amp;quot;);

                StringBuilder chartDiv = new StringBuilder();
                chartDiv.AppendLine(&amp;amp;quot; &amp;amp;amp;lt;div id=\&amp;amp;quot;BarChartDiv_&amp;amp;quot; + ValueField1 + &amp;amp;quot;\&amp;amp;quot; class=\&amp;amp;quot;BarChartDepartment\&amp;amp;quot; &amp;amp;amp;gt;&amp;amp;amp;lt;/div&amp;amp;amp;gt;&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; var chart = new google.charts.Bar(document.getElementById('BarChartDiv_&amp;amp;quot; + ValueField1 + &amp;amp;quot;'));&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; chart.draw(data, google.charts.Bar.convertOptions(options));&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; }&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; &amp;amp;amp;lt;/script&amp;amp;amp;gt;&amp;amp;quot;);

                ltrlCharts.Text = chartDiv.ToString();
                ltrlScript.Text = script.ToString();
            }
        }

        private SPListItemCollection GetAllItemsByBudget()
        {
            SPListItemCollection listItems = null;
            try
            {
                SPWeb currentWeb = null;
                if (!string.IsNullOrEmpty(webName))
                {
                    currentWeb = SPContext.Current.Site.AllWebs[webName];
                }
                SPQuery query = new SPQuery();
                SPList list = currentWeb.Lists.TryGetList(ListName);
                if (list != null)
                {
                    listItems = list.GetItems(query);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return listItems;
        }

For Ref: Bar Chart

Creating a Pie Chart from SharePoint 2013 List

Hi,

i read on the internet that there is no charts webpart in SharePoint 2013 so i had created a visual webpart to display Pie Chart from SharePoint List with all the configurable properties

Note: i’m using Google API to create Charts

here are the webpart configurable properties

percentage-property

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

We can display it as a 3D or 2D just only we need to check the above property, also we can display actual number/values instead of percentage, see the above properties

Note: you can apply other Pie Chart styles by reading out the Google API

here is the DepartmentBudget List in SharePoint

List

After adding a webpart you can see the following two Pie Charts, one with 3D and other one with 2D

2D

 

 

 

 

 

 

 

 

 

 

 

Now see 3D Pie Chart

3D

 

 

 

 

 

 

 

 

 

 

 

Chart with actual values

Percentage and value - Copy

 

 

 

 

 

 

 

 

 

 

i’m using the following code

.ascx Page

&amp;amp;amp;lt;asp:Label ID=&amp;amp;quot;lblError&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot;&amp;amp;amp;gt;&amp;amp;amp;lt;/asp:Label&amp;amp;amp;gt;

&amp;amp;amp;lt;script type=&amp;amp;quot;text/javascript&amp;amp;quot; src=&amp;amp;quot;https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['corechart']}]}&amp;amp;quot;&amp;amp;amp;gt;&amp;amp;amp;lt;/script&amp;amp;amp;gt;
&amp;amp;amp;lt;div&amp;amp;amp;gt;
    &amp;amp;amp;lt;asp:Literal ID=&amp;amp;quot;ltrlScript&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot;&amp;amp;amp;gt;&amp;amp;amp;lt;/asp:Literal&amp;amp;amp;gt;
    &amp;amp;amp;lt;asp:Literal ID=&amp;amp;quot;ltrlCharts&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot;&amp;amp;amp;gt;&amp;amp;amp;lt;/asp:Literal&amp;amp;amp;gt;
&amp;amp;amp;lt;/div&amp;amp;amp;gt;

Css Class

.PieChartCustomDepartment {
        width:725px;
        height:400px;
    }

.ascx.cs Page

#region All Custom Properties

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;web Name&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;web url&amp;amp;quot;)]
        public string webName { get; set; }

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;Chart Title&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;Title of the Chart&amp;amp;quot;)]
        public string ChartTitle { get; set; }

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;List Name&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;List name of department budget&amp;amp;quot;)]
        public string ListName { get; set; }

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;Category Field&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;Category Field Name&amp;amp;quot;)]
        public string CategoryField { get; set; }

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;Value Field&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;Field Name of which you want to generate chart&amp;amp;quot;)]
        public string ValueField { get; set; }

        [WebBrowsable(true),
                  Category(&amp;amp;quot;Custom&amp;amp;quot;),
                  Personalizable(PersonalizationScope.Shared),
                  WebDisplayName(&amp;amp;quot;Show as 3D Chart&amp;amp;quot;),
                  WebDescription(&amp;amp;quot;flag to display chart in 3D or in 2D&amp;amp;quot;)]
        public bool ShowAs3DChart { get; set; }

        #endregion

        public vwPieChartCustom()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    CreateDepartmentPieChart();
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }

            this.ChromeType = PartChromeType.None;
        }

        private void CreateDepartmentPieChart()
        {
            SPListItemCollection itemsColl = GetAllItemsByBudget();
            if (itemsColl != null &amp;amp;amp;amp;&amp;amp;amp;amp; itemsColl.Count &amp;amp;amp;gt; 0)
            {
                StringBuilder script = new StringBuilder();

                script.AppendLine(&amp;amp;quot;&amp;amp;amp;lt;script type=\&amp;amp;quot;text/javascript\&amp;amp;quot;&amp;amp;amp;gt;&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot;google.load(\&amp;amp;quot;visualization\&amp;amp;quot;, \&amp;amp;quot;1\&amp;amp;quot;, {packages:[\&amp;amp;quot;corechart\&amp;amp;quot;]});&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot;google.setOnLoadCallback(drawChart);&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot;function drawChart() {&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; var data = google.visualization.arrayToDataTable([&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; ['&amp;amp;quot; + CategoryField + &amp;amp;quot;', '&amp;amp;quot; + ValueField + &amp;amp;quot;'],&amp;amp;quot;);
                for (int i = 0; i &amp;amp;amp;lt; itemsColl.Count; i++)
                {
                    script.AppendLine(&amp;amp;quot; ['&amp;amp;quot; + itemsColl[i][CategoryField] + &amp;amp;quot;', &amp;amp;quot; + itemsColl[i][ValueField] + &amp;amp;quot;],&amp;amp;quot;);
                }
                script.AppendLine(&amp;amp;quot; ]);&amp;amp;quot;);

                script.AppendLine(&amp;amp;quot; var options = {&amp;amp;quot;);
               if (ShowAs3DChart)
 {
 script.AppendLine(&amp;amp;quot; title: '&amp;amp;quot; + ChartTitle + &amp;amp;quot;',&amp;amp;quot;);
 if (DisplayPercentage)
 {
 script.AppendLine(&amp;amp;quot; pieSliceText:'percentage',&amp;amp;quot;);
 }
 else
 {
 script.AppendLine(&amp;amp;quot; pieSliceText:'value',&amp;amp;quot;);
 }
 script.AppendLine(&amp;amp;quot; is3D: true&amp;amp;quot;);
 }
 else
 {
 script.AppendLine(&amp;amp;quot; title: '&amp;amp;quot; + ChartTitle + &amp;amp;quot;',&amp;amp;quot;);
 script.AppendLine(&amp;amp;quot; pieSliceText:'value'&amp;amp;quot;);
 }
                script.AppendLine(&amp;amp;quot; };&amp;amp;quot;);

                StringBuilder chartDiv = new StringBuilder();
                chartDiv.AppendLine(&amp;amp;quot; &amp;amp;amp;lt;div id=\&amp;amp;quot;PieChartDiv_&amp;amp;quot; + ValueField + &amp;amp;quot;\&amp;amp;quot; class=\&amp;amp;quot;PieChartCustomDepartment\&amp;amp;quot; &amp;amp;amp;gt;&amp;amp;amp;lt;/div&amp;amp;amp;gt;&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; var chart = new google.visualization.PieChart(document.getElementById('PieChartDiv_&amp;amp;quot; + ValueField + &amp;amp;quot;'));&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; chart.draw(data, options);&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; }&amp;amp;quot;);
                script.AppendLine(&amp;amp;quot; &amp;amp;amp;lt;/script&amp;amp;amp;gt;&amp;amp;quot;);

                ltrlCharts.Text = chartDiv.ToString();
                ltrlScript.Text = script.ToString();
            }
        }

        private SPListItemCollection GetAllItemsByBudget()
        {
            SPListItemCollection listItems = null;
            try
            {
                SPWeb currentWeb = null;
                if (!string.IsNullOrEmpty(webName))
                {
                    currentWeb = SPContext.Current.Site.AllWebs[webName];
                }
                SPQuery query = new SPQuery();
                SPList list = currentWeb.Lists.TryGetList(ListName);
                if (list != null)
                {
                    listItems = list.GetItems(query);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return listItems;
        }

 

For Ref: Click here

Migrate InfoPath Forms and SharePoint Designer 2013 Workflows

Hello Everyone,

Today’s i’m gonna add very interesting thing in my blog, in each organization we have some InfoPath Forms like Leave Request, Business Card, Expense Claim and different types of Allowance and so on….

we had developed some InfoPath forms using InfoPath 2013 and using Workflows of SharePoint Designer 2013.

also i’ve successfully migrated all the forms from Development to Production, here is full detail how one can do this important task.

Note: make sure you have installed SharePoint Workflow Manager 2013 on the server where you want to migrate forms, if there is any pre requisities required install them also.

for our scenario, i first create all the SharePoint groups which i’m using, then installed SharePoint Workflow Manager and performed following steps.

Step 1 – Export and Import All Required Libraries

Create your SharePoint Form/Document Library CMPs by using PowerShell EXPORT/IMPORT command as follows

Exporting from Source SharePoint Site

export-spweb -identity http://ServerName/site -path C:\LibraryName.cmp -itemurl /site/LibraryName/ -includeusersecurity

Importing to Destination SharePoint Site

Import-spweb -identity "http://ServerName/Site" -path "C:\CMPs\LibraryName.cmp" -force

Note: First Export all the Libraries from Source Server and then Import them on Destination server. as per my understanding from above command we cannot export import a List so i create STP in case of List instead of using above commands

Step 2 – Creating Package (WSPs) and Deploy workflows SharePoint Designer 2013

Open your SharePoint Site in SharePoint Designer 2013, select your workflow and click on Save as Template.

save as template

it will be saved in Site Assets Library of your SharePoint site, just download and save on your PC

site assets

Now its time to deploy All Workflow Templates to the Destination Server

Export Workflow as shown below

export wf

Deploy Workflow solution

Go to SharePoint Site Settings and make sure you are on Root Site, now click on Solution link.

Upload all workflow WSPs one by one and activate the solution

After a workflow solution has been activated for a site collection, it is available as a feature for all sub-sites. To activate the workflow feature for a sub-site, follow this procedure.

Activate the workflow feature
Open Site Settings on the site where you wish to activate the workflow feature.
In the Site Actions group, click Manage site features.
Click Activate next to the workflow feature as shown in the figure.

activate feature

NOTE: After activation of workflow feature, open SharePoint Designer now you will see your workflow will be created and you can use it.

For Ref: Click here

Step 3 – Publishing InfoPath Forms to Destination Server

Open your InfoPath form and CHANGE all the Data Connections in order to deploy on another server and make sure you didn’t wrote any server name hard coded in the form code.

after Publishing the form, it will be saved on your local system, NOW its ready to deploy on another server.

Note: in my case, i’ve all forms as Administrator approved templates with full trust

Deploy to Destination Server

Open Destination Server CA->General Application Settings->Manage Form Templates->Upload form template

after successful uploading, it will create a Site Collection feature and activate, associate with your SharePoint Library and add it as a Content Type.

For Ref – Click here

Note: in my case, it stuck in Installing or Upgrading so to remove it in order to upload it again use the following command

Uninstall-SPInfoPathFormTemplate -Identity "SampleTemplate.xsn"

after running above command i got following issue

The solution cannot be removed when a job is schedule or running

so to remove it forcefully, use the following STSADM Commands

stsadm -o enumdeployments
stsadm -o canceldeployment -id or stsadm -o execadmsvcjobs

stsadm -o canceldeployment -id 24bf35d4-5b96-4354-8d89-c4c8b7c539b6

send test email in SharePoint using PowerShell

Hello everyone,

here is the PowerShell Script to check emails are working or not in SharePoint


$site = New-Object Microsoft.SharePoint.SpSite(“http://servername/site”)
$web = $site.OpenWeb()
$sent = [Microsoft.Sharepoint.Utilities.SpUtility]::SendEmail($web,0,0,”email address”,”email subject”,”mail body”)
$sent

Site Feed Webpart SharePoint 2013

Site Feed is very interesting webpart, when you want some sort of microblogging select Site feed webpart.

where is Site Feed webpart located in SharePoint 2013?

first you need to activate Site Feed feature, to do this go to site settings->Manage Site Features and activate it

feature activate

when feature is activated, a list(MicroFeed) will be created on site contents section now you will see Site Feed webpart under Social & Collaboration category

Note: we cannot have two instances of Site Feed webpart in one site, you can place site feed webpart on multiple pages, doing so it will load same feeds on all webparts. if you want different feeds for every department or site then you need to activate Site Feed feature on every site where you want different feeds.

Here is the link where you can read site feed functionality in detail

http://www.sharepointanalysthq.com/2012/07/social-in-sharepoint-2013-newsfeed-posting-and-replying/

but my focus will be on how to customize Site Feed webpart look and feel.

my customization includes

1) hide reply, attach image and elispsis button

2) apply custom css styles

3) change webpart title

4) change Post button caption to “Send

5) Place Site feed webpart on Home Page

first see which css class applies where? here is its structure. one of the blogger has mentioned in very clearly on following url

http://josharepoint.com/2014/06/09/branding-tip-custom-style-in-newsfeed-and-site-feed-webpart-in-sharepoint-2013/

Site feed css classes structure

here is my Site Feed webpart after customization and i’ve placed it on home page

on home page

you can see i’ve customize everything mentioned above

There was some issues i’ve faced these are

Issue 1:      when user post new feed or click on send button or press enter after writing some feed, the reply, elispis, attach image button gets visible so i’ve wrote script for this to handle as the new post creates new div’s to show new post this is dynamic post i’m using DOMNodeInserted to new node inserted and apply custom script on it.

Issue 2: BIG ISSUE

we’ve some webparts which contains Update Panel so when there is async postback occurs on the page! Site Feed webpart gets clear.  but we need to have site feed webpart on home page but we also have to show calendar webpart which contains update panel

Solution: to do this, i’ve made some RnD on the Internet but didn’t find any solution so finally i’m opening Site Feed Webpart in IFRAME, now everything is fine

following is the script which i’m using to hide controls


<script type="text/javascript">
$(document).ready(function() {

hideHeaderFooter();
onPageLoadNewsFeed();

$(document).bind('DOMNodeInserted', function(){
$(".ms-microfeed-mysitemenu-ellipsisImage").hide();
$("a:contains('Reply')").hide();

});

});

function onPageLoadNewsFeed()
{
$('.ms-microfeed-mysitemenu-control').hide();
$("a:contains('Reply')").hide();

$(".ms-microfeed-messageFooter span:Contains('Follow')").hide();

$("#ms-addImageButton").hide();
$("div.ms-microfeed-siteFeedTitleArea").replaceWith("
<div class='generic_heading3'>
<h2>Share your thoughts</h2>
</div>

");
$('#ms-postbutton').html('Send');

}
function hideHeaderFooter()
{
$('.ms-designer-ribbon').hide();
$('.s4-ribbonrow').hide();
$('.logo').hide();
$('.header_row1').hide();
$('.footer').hide();
$('.inner_banner1').hide();
$('.breadcrumbs').hide();
$('.inner_leftcolumn').hide();
$('.inner_rightcolumn').hide();
$('#footer').hide();
$('#suiteBar').hide();
$('.InnerPageTitle').hide();
$('#ms-designer-ribbon').hide();
}
</script>

here is CSS classes which i’m using

</pre>
.ms-microfeed-cancelButton{
background-color: #fcfcfc !important;
border: 1px solid #d4d4d4 !important;
-moz-border-radius: 10px !important;
-webkit-border-radius: 10px !important;
border-radius: 10px !important;
color: #00a6d9 !important;
height: 22px !important;
padding-top: 3px !important;
width: 78px !important;
font-family: Arial !important;
font-size: 11px!important;
font-weight: normal !important;
}
.ms-microfeed-siteFeedTitleArea
{
background-color: silver;
padding-left: 20px;
text-transform:uppercase;
padding-bottom: 3px;
padding-top: 2px;
margin-bottom: 5px;
}

.ms-microfeed-siteFeedMicroBlogPart
{
margin-bottom: 2px;
}
.ms-microfeed-siteFeedTitleLabel
{
color: red !important;
}

.ms-microfeed-threadsDiv
{
height: 250px;
overflow-y: auto;
overflow-x: hidden;
}

.ms-microfeed-thread
{
max-width: 435px;
margin-bottom: 10px;
}
.ms-microfeed-replyArea
{
max-width: 375px;
min-width: 300px;
}

.ms-microfeed-attachmentButton
{
padding-top: 2px;
padding-bottom: 2px;
padding-bottom: 2px;
display: block;
}
.ms-microfeed-postButton
{
margin-top: 2px;
}

.ms-microfeed-postButtonSpan
{
position: absolute;
right: 12px;
}

.ms-microfeed-postBox
{
/* height: 53px;*/
min-height:53px;
}

.ms-microfeed-feedPart
{
margin-left: 10px;
max-width: 620px;
min-width: 290px;
padding-top: 10px;
position: relative;
width: 290px;
}
.ms-microfeed-fullMicrofeedDiv
{
border-radius:15px;
-moz-border-radius:15px;
-webkit-border-radius:15px;
float: left;
margin-bottom: 10px;
width: 310px;
min-width:310px;
background-color:#f3f3f3;

top:0;
left:0px;
position:absolute;
}
.ms-microfeed-microblogpart
{
margin-bottom: 30px !important;
position: relative;
min-width:300px;
}
.ms-postbutton
{
float: right;
text-align: center;
}
.ms-microfeed-focusBoxNoFocus
{
border:1px solid #c6c6c6;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
border-radius: 15px;
margin-left:10px;

background-color:white;
width: 290px;
margin-top:10px;
}
.ms-microfeed-focusBox
{
background-color:white;
border: 1px solid #c6c6c6;
border-radius:15px;
-moz-border-radius:15px;
-webkit-border-radius:15px;
margin-left: 10px;
width: 290px;
margin-top:10px;
}
.input.ms-button-emphasize, button.ms-button-emphasize
{
background-color: #fcfcfc;
border: 1px solid #d4d4d4;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
color: #00a6d9;
height: 22px;
padding-top: 3px;
width: 78px;
font-family: Arial;
font-size: 11px;
font-weight: normal;
}
.input.ms-button-emphasize, button.ms-button-emphasize:hover
{
background-color: #008fbb;
border: 1px solid #008fbb;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
color: #ffffff;
height: 22px;
padding-top: 3px;
width: 78px;
font-family: Arial;
font-size: 11px;
font-weight: normal;
}
.generic_heading3_Share {
background-image: url("/Style%20Library/Images/heading_bg2.png");
background-position: center bottom;
background-repeat: repeat-x;
-moz-border-radius: 15px 15px 0 0;
-webkit-border-radius: 15px 15px 0 0;
border-radius: 15px 15px 0 0;
float: left;
padding: 7px 10px;
width: 290px;
}
h2 {
color: #ffffff;
font-family: Arial;
font-size: 15px;
font-weight: normal;
text-decoration: none;
}

.ms-subtleLink:link, .ms-subtleLink:visited, .ms-atMention:link, .ms-atMention:visited, .ms-hashTag:link, .ms-hashTag:visited
{
color: #444;
font-weight: bold;
}
.ms-microfeed-rootText
{
max-width: 531px;
min-width: 210px;
}
.ms-microfeed-button
{
background: none repeat scroll 0 0 rgba(0, 0, 0, 0);
border: 0 none;
color: #008fbb;
cursor: pointer;
margin-left: 0;
min-width: 1px;
}

.ms-microfeed-button:hover
{
background: none repeat scroll 0 0 rgba(0, 0, 0, 0);
border: 0 none;
color: #008fbb;
cursor: pointer;
margin-left: 0;
min-width: 1px;
}
.ms-spimn-presenceWrapper{
display: none !important;
overflow: hidden;
position: relative;
white-space: nowrap;
}
<pre>

Add BreadCrumb SharePoint 2013

In almost every SharePoint portal we need to add BreadCrumb, we can add this in Page Layout as well as in Master Page, it all depends on your needs….

here is the small snippet for Breadcrumb, add following snippet into your html file

<pre id="pre548766"><strong><span class="code-keyword"><</span><span class="code-leadattribute">div</span> <span class="code-keyword">class="breadcrumbs"</span><span class="code-keyword">></span>
<span class="code-keyword"><!--</span><span class="code-keyword"><span class="code-comment">MS:<ASP:SITEMAPPATH runat="server" 
sitemapproviders="SPSiteMapProvider,SPXmlContentMapProvider" 
rendercurrentnodeaslink="false" hideinteriorrootnodes="true" 
RootNodeStyle-CssClass="bc-root"></span>--></span>
<span class="code-keyword"><!--</span><span class="code-keyword"><span class="code-comment">MS:<PATHSEPARATORTEMPLATE></span>--></span>
<span class="code-keyword"><!--</span><span class="code-keyword"><span class="code-comment">MS: | </span></span><span class="code-keyword">--></span>
<span class="code-keyword"><!--</span><span class="code-keyword"><span class="code-comment">ME:</PATHSEPARATORTEMPLATE></span>--></span>
<span class="code-keyword"><!--</span><span class="code-keyword"><span class="code-comment">ME:</ASP:SITEMAPPATH></span>--></span>
<span class="code-keyword"><</span><span class="code-keyword">/</span><span class="code-leadattribute">div</span><span class="code-keyword">>

</span></strong><span class="code-keyword">i'm using following css class
<strong>.breadcrumbs{</strong>
<strong> float: left;</strong>
<strong> width: 1280px;</strong>
<strong> margin-top: 10px;</strong>
<strong> margin-bottom: 10px;</strong>
<strong> font-family: Arial;</strong>
<strong> font-size: 11px;</strong>
<strong> font-weight: normal;</strong>
<strong> color: #666666;</strong>
<strong> text-decoration: none;</strong>
<strong>}


Thanks