Friday, November 16, 2018

Solution structure in SharePoint Framework (SPFx)

You can open the solution in the code editor like visual studio code.
Go to command prompt, Navigate to the code directory, and type code. and press enter. Your source code will be open up in Visual code.



The Solution structure consist of various folder and configuration files at the root. The primary language used is TypeScript. The code mostly uses classes, modules, and interfaces written in typescript.



Folders in the Solution

Src

Code files are stored inside this folder

Lib

It contains processed code which can be bundled and distributed
All typescript files compiled into JavaScript files are stored here

Dist

Contains final distributed files
Includes javascript bundle file

Config

Contains set of JSON file for configuration

Node_modules

Contains JavaScript modules downloaded by node.js

Typings

Contains typescript typing files for various libraries
Typing support intellisense for JavaScript Library

SharePoint

Contains the final .spapp file post execution of ‘gulp package-solution’ command

Files in Solution

Let’s assume the WebPart Name is HelloWorld

WebPart Class (HelloWorldWebPart.ts)

This defines the entry point of the webpart.

Property Type Interface (IHelloWorldWebPartProps.ts)

The interface resides in the same web part file. The web part class accepts the property type of interface. This interface is used to define our own custom properties for the web part.

WebPart Menifest (HelloWorldWebPart.menifest.json)

This file holds the metadata of webpart such as display name, description, icon, version etc.

Config.json

The configuration file contains the bundling information, the components used in the solution and entry point of the solution.

This file also records the external references (for e.g. jQuery) and its dependencies. Also, references to localization resources are stored in this file.

Deploy-azure-storage.json

This file is used while deploying the client-side web part to Azure CDN. This file contains Azure storage account details.

Package-solution.json

This file contains solution id, name and version number.

Serve.json

File where we can see on what url and port workbench will be served.

Write-menifest.js

File where we can mention where manifest file can be found.

Gulpfile.js

Defines gulp tasks to run.

Package.json

Defines JavaScript library dependencies.

Tsconfig.json

Defines settings for TypeScript compilation

Thursday, November 15, 2018

Overview of SharePoint FrameWork (SPFx)


Now we have Modern Site in SharePoint. And customization in modern pages/sites supported by SharePoint Framework.
SPFx is an Open and connected Platform. It can be entirely developed using client-side languages.

Key Features

      No Iframes
Faster rendering on the browser (all controls are rendered in normal DOM)
Runs in current user context
Controls are responsive
Give controls to access the lifecycle of the SharePoint Framework web part component (Init, render, load. Serialize, de serialize, configuration changes etc)
No dependency of underlying framework. User can choose any framework like React, Angular, Knockout and more)
Open Source Development tools are used (npm, typescript, gulp, yeoman and webpack)
Can be added both classic and modern pages
Client Side Webparts, leverage modern site frameworks
Provides Modern experience, responsiveness Out of Box
Free, Open source tool chain

      Flow of Client Side Web Part



SharePoint FrameWork (SPFx) Tool Chain




While we were developing on On-Premise (2007/2010) we were developing the Solutions (WSP). WSP contains the sets of Features, Site Definitions, assemblies etc written in c # and that get deployed on SharePoint Servers.
After that Microsoft introduced AddIns. SharePoint Addins avoided the Server deployments and change the deployment pattern. Prevented these solutions from running physically on the Web Front End servers.
After that Microsoft has introduced SharePoint Framework (SPFx). A complete client side development and these webparts can run in the context of page it means no Iframe which was the pain area with SharePoint addins, no cross domain calls on your webparts

The New Tool Chain of SharePoint FrameWork.
Tool Chain Info graphics which will tell what replaced what 






This is the development server. Earlier you ware familiar with IIS and Microsoft Visual Studio. Now you just need to install this and forget IIS and VS. You do not need to touch the node.js after installing it.



This is the replacement of your NUGET. Which you were familiar with Visual Studio while installing the things using nugget package.




A Scaffolding tool for development projects, which helps us kick-start new projects, and prescribes best practices and tools to help you stay productive. SharePoint client-side development tools include a Yeoman generator for creating new web parts. The generator provides common build tools, common boilerplate code, and a common playground web site to host web parts for testing.
It’s Same like as you were earlier doing File à New à Project à Select Template in Visual studio.



A task and build manager that provides automation for build tasks, which is like MS build.





TypeScript, React, Knockoout and many other languages can be used to develop the Web part in SharePoint Framework.




Saturday, December 16, 2017

the app for SharePoint is in an invalid state and cannot be uninstalled

Error : The app for Sharepoint is in an invalid state and cannot be uninstalled.

Error : Skipping the uninstall step because the app for SharePoint is in an invalid state and cannot be uninstalled.

Error : Error occurred in deployment step ‘Install app for SharePoint’: The provided App differs from another App with the same version and product ID.

I was having a problem with deploying my SharePoint Hosted App into my Dev SharePoint environment. Earlier version of installed app was having some issues in Removal. while i tried to remove the app got the error "Sorry, we couldn't remove the app. Click to retry"


To Fix all the issues there is one solution. Actually your timer job service got stuck due to this sharepoint is unable to remove the App.

Go to Windows Services and Restart the "Sharepoint Timer Service" once the timer service will restart then again try to remove the App or Redeploy the app again on sharepoint through Visual Studio. Now it should be working fine.


Friday, October 13, 2017

Exception occured:Microsoft.SharePoint.Client.ServerException: Cannot complete this action. Sharepoint 2013

Exception occured:Microsoft.SharePoint.Client.ServerException: Cannot complete this action. Sharepoint 2013


This issue occures usually when your server is running Out of Memory.


You can fix this issue in 2 ways.


  • Reduce the Preformance of Search Service
  • Reduce the NodeRunner.exe impact on Memory


First try to reduce the performance of Search and check if you still face this problem then go for NodeRunner changes


Reduce the Preformance of Search Service

Set-SPEnterpriseSearchService -PerformanceLevel Reduced


Reduce the NodeRunner.exe impact on Memory

The node runner application used by SharePoint 2013 preview for search related process slows down the system due to memory leak issues.

Open the config file at C:\Program Files\Microsoft Office Servers\15.0\Search\Runtime\1.0\noderunner.exe.config.

<nodeRunnerSettings memoryLimitMegabytes="0" />

NodeRunner.exe is resource hungry process. By default it's set to 0 which means it can any amount of memory. You need to fix it by giving any fixed number eg. 50,100,200 etc. This sets the cap limit for memory to be used.

Restart the Sharepoint Search Host Controller Service after this change.

Thursday, October 12, 2017

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel

Exception occured at method XXX-System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

I faced this issues while accessing the site on https and i didn't had the valid certificate. I was trying to connect the sharepoint site through a console application using the CSOM code.

This issue usually come while you don't have the valid certificate.

To solve this proble just add the below line to fix this issue.


ServicePointManager.ServerCertificateValidationCallback = new       
RemoteCertificateValidationCallback
(
   delegate { return true; }
);

Instead of doing this better to use a valid Crtificate

Tuesday, October 10, 2017

Creating SharePoint App/Addin with TypeScript

Typescript language provides strong types, interfaces, and extensible classes that bring common object oriented programming concepts and techniques into JavaScript development.

The TypeScript compiler produces a JavaScript file from a source file with a .ts extension.

Here i am starting with a very simple Sharepoint App. It's just a concept which will help to how to run your app with Typescript. No any Typescript code is involved in this.

1. Create a New Sharepoint App using visual studio ("Hello User Name App")

2. Go to the Solution Explorer Select the app solution, Do the right click on it and Select Unload       Project. Once the project is unloaded do the right click again and click on Edit Project

3. Add the below lines bofore closing of </Project> tag and Save it.

<PropertyGroup>
    <TypeScriptSourceMap>true</TypeScriptSourceMap>
  </PropertyGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" />

4. Reload the Project by doing the Right click on it.

5. Now you need to install "sharePoint.Typescript.DefinitelyTyped" and "jquery.Typescript.DefinitelyTyped". For this do the right click on the solution and Select "Manage NuGet Packages..". In the NuGet Window search for the sharePoint.Typescript.DefinitelyTyped, jquery.Typescript.DefinitelyTyped and install it.

6. Now we have all the prereqisite added with the project.

7. Expand the Solution and go in Script folder. Rename App.js with some other name and add App.ts. Copy all the script from App.js and paste it into App.ts.

8.Add these line on the App.ts file
///<reference path="typings/sharepoint/SharePoint.d.ts" />
///<reference path="typings/jquery/jquery.d.ts" />

9. Build the Project

10. Click on Show All files from the Solution Explorer. You will get App.js and App.js.map. Just include them.

11. Deploy the App

The status code of response is '500'. The status text of response is System.ServiceModel.ServiceActivationException

SharePoint 2013 Error: Unexpected response from server. The status code of response is '500'. The status text of response is System.ServiceModel.ServiceActivationException.


Usually this occures due to server is running out of Memory

You can fix it by reducing the Search service Performance or you can limit the Node runner 

Solution 1.

Reduce the Search Service Performance

PS : Set-SPEnterpriseSearchService -PerformanceLevel Reduced


If this does not solve the problem then you can opt for Solution 2.

Solution 2.

There is a configuration setting for NodeRunner.exe’s configuration file that can limit RAM usage of a single process to specific value in megabytes. his configuration file is located at: C:\Program Files\Microsoft Office Servers\15.0\Search\Runtime\1.0\noderunner.exe.config.



<!-- Settings enforced by the node runner itself. -->
  <!-- These settings can also be set using command line arguments with the same name. -->
    <nodeRunnerSettings memoryLimitMegabytes="0" />

The configuration setting is under the nodeRunnerSettings node and it’s called memoryLimitMegabytes.  Its default value is 0 (unlimited).


Set it to 50 or 100 and save the file. After that restart the Sharepoint Search Host Controller Service.


This will resolve the issue.

Note : Solution 2 is not recommended approach by Microsoft.

Wednesday, August 9, 2017

Sharepoint search refiners and powershell

Most important innovation in search during the past years, has been the use of metadata-driven faceted search, to help users customise search results, one click at a time. 

In SharePoint 2013, these search navigation options are referred to as search refiners. 

Refiners are an extremely important part of the enterprise search experience.

SharePoint search refiners are metadata-driven. 


If we open up our Search Centre and query on some data, down the left hand side of the search results is a search refinement panel. This panel gives a breakdown of some metadata found within the search results which allows you to filter it further.

If you look at the default search refiners, You will get refiners Result Type, Site, Author, Modified Date, and Location.

To get the search to work, you first need to ensure you have put data in a list with the columns you wish to search on, and perform a crawl in Central Administration for any results to show up in search. There are two different types of Search Refiners you can create ManagedPropertyFilterGenerator, or a TaxonomyFilterGenerator.

Here i am taking example of a TaxonomyFilterGenerator Refiners

We can add any custom refiners on the Result Page by Editing the page and editing the Refinement Webpart properties

In this blog we are talking about powershell script to do the same thing.

# Get our page and check it out
$spweb = Get-SPWeb "http://localhost/search/"
$page = $spweb.GetFile("Pages/results.aspx")
$page.CheckOut()

# Find the Refinement web part
$webPartManager = $spweb.GetLimitedWebPartManager("http://localhost/search/Pages/results.aspx", [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$rwp = $webpartmanager.webparts | ? { $_.title -eq 'Refinement' }

# Refiners are Added/updated by changing the JSON
$j = $rwp.SelectedRefinementControlsJson | ConvertFrom-Json
$jsonString = @"
    {
    "sortBy" : 1,
    "sortOrder" : 1,
    "maxNumberRefinementOptions" : 15,
    "propertyName" : "",
    "type" : "Text",
    "displayTemplate" : "~sitecollection/_catalogs/masterpage/Display Templates/Filters/Filter_Default.js",
    "displayName" : "",
    "useDefaultDateIntervals" : false,
    "aliases" : [],
    "refinerSpecStringOverride" : "",
    "intervals" : null
    }
"@
# sortBy : 0-number, 1-Name, 2-Count; sortOrder : 0-Descending, 1-Ascending
# Adding new Refiner in Refinement Webpart
$newRefinerJson = ConvertFrom-Json $jsonString
$newRefinerJson.propertyName = "Your Managed Property Name"
$newRefinerJson.displayName = "Display Name you would like to set"
$j.refinerConfigurations += $newRefinerJson

$refJson =  ConvertTo-Json $j -Depth 3 -Compress
$refJson = $refJson.Replace("null,","")
$rwp.SelectedRefinementControlsJson = $refJson


# Save our changes
$webpartmanager.SaveChanges($rwp)          # save changes to webpart
$page.CheckIn('Added refiner')
$page.Publish('Added refiner')


The above script will add the new Refiner in the Refinement Webpart with the existing Refiners.
If you would like to remove all existing refiners and add the totally new set of Refiners then use the below Powershell script

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
# Get our page and check it out
$siteURL = Read-Host "Enter Search site Url" 
$spweb = Get-SPWeb($siteURL)

try{
Write-Host -ForegroundColor Green "Processing start for :  " $spweb.Title
$page = $spweb.GetFile("Pages/results.aspx")
$page.CheckOut()
Write-Host -ForegroundColor Green "Checking out Result page, Editing Refiners Webpart, Changing Refiners........."
# Find the Refinement web part
$webPartManager = $spweb.GetLimitedWebPartManager($spweb.Url + "/Pages/results.aspx", [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$rwp = $webpartmanager.webparts | ? { $_.title -eq 'Refinement' }
# Refiners are updated by changing the JSON
$refctljson = $rwp.SelectedRefinementControlsJson | ConvertFrom-Json
$refctljson.refinerConfigurations.Clear()
$jsonString = @"
    {
    "sortBy" : 1,
    "sortOrder" : 1,
    "maxNumberRefinementOptions" : 15,
    "propertyName" : "",
    "type" : "Text",
    "displayTemplate" : "~sitecollection/_catalogs/masterpage/Display Templates/Filters/Filter_Default.js",
    "displayName" : "",
    "useDefaultDateIntervals" : false,
    "aliases" : [],
    "refinerSpecStringOverride" : "",
    "intervals" : null
    }
"@
$newRefinerJson = ConvertFrom-Json $jsonString
$newRefinerJson.propertyName = "MPropertyDepartment"
$newRefinerJson.displayName = "Department"
$refctljson.refinerConfigurations += $newRefinerJson
Write-Host -ForegroundColor Green "Refiner 'Department' Added..." 

$refJson =  ConvertTo-Json $refctljson -Depth 3 -Compress
$refJson = $refJson.Replace("null,","")
$rwp.SelectedRefinementControlsJson = $refJson

# Save our changes
$webpartmanager.SaveChanges($rwp)          # save changes to webpart
$page.CheckIn('refiner Added')
$page.Publish('refiner Added')
Write-Host -ForegroundColor Green "Refiner Changed and Page Checkedin for " $spweb.Title
}
catch
{
Write-Host Error occurred while Updating Refiners : $_.Exception.Message -ForegroundColor red

}


In this script only 2 lines are extra from the above script
$refctljson.refinerConfigurations.Clear()

This is to clear all the existing Refiners from the refinement webpart.

once the refiners are removed from the Refinement webpart then in JSON you will get null values for those refiners. And the PS is executed it throws error "Exception setting "SelectedRefinementControlsJson": "Object reference not set to an instance of an object.""

And your JSON would be like below

{"refinerConfigurations":[null,null,null,null,null,null,null,null,null,null,{"sortBy":1,"sortOrder":1,"maxNumberRefinementOptions":15,"propertyName":"MPropertyDepartment","type":"Text",
"displayTemplate":"~sitecollection/_catalogs/masterpage/Display Templates/Filters/Filter_Default.js","displayName":"Department","useDefaultDateIntervals":false,"aliases":[],"refine

rSpecStringOverride":"","intervals":null}]}

To fix this issue we need replace all the null values with blank to get rid of this error.

This line does the same
$refJson = $refJson.Replace("null,","")











Sort Refiner Values Alphabatically Sharepoint Search 2013

If you are using Managed Metadata Terms as a search refiners then you have noticed that your Refiners values are not coming on alphabetically sorted.

Let's take an example for the same

If you have created a Site Column eg. Term1 Type Managed Metadata Column

Associate this column "Term1" with a List
Add some items to the list and tag the Term1 to some Managed Metadata Terms

Run the Full Crawl from Search Service application

Go to Search Schema in Search Service application and search for Crawled Property





in the Search Box type Term1. After search you will get 2 Crawled Properties

  • ows_taxId_Term1
  • ows_Term1


  • ows_taxId_Term1 contins the TermID along with the TermSet display name. If you add this in your refiner and apply sorting on Name it will sort ASC or DESC based on the TermID

  • ows_Term1 contains the TermSet Display Name. If you cannot add this directly in your refiners because it's not a Managed Property. You need to create a managed property for this and Map this crawled property with your managed property.


Steps to Create a Managed Property

Click on "New Managed Property" in Search Schema Page
Name : Provide Some Name eg. MyTerm
Type : Text
Searchable : True
Queryable : True
Retrievable : True
Allow multiple values : True
Refinable : Yes Active
Sortable : Yes Active

In Add Mapping Screen Search for ows_Term1 and add it
Click on OK


Run the Full Crawl

Add your managed property as Refiner  and set the properties as below on the picture


Display Name : Term 1
Sort by : Name
Sort Direction : Ascending

you will get refiner values are appearing in a sorted order.