Hello, SharePoint Framework (SPFx): Getting Started – Quick and Dirty

I know, I know… there’s github, pluralsight, PnP, dev.office.com and a plethora of videos and sites where you can find info on getting started with SPFx.  We’ll just add this one to the list.  This is a quick and dirty getting started guide.  I’ll also provide some references for you to dive deeply into related topics.

Setup

What do I need to install?

For starters, you need to install Node.js. Get yourself the LTS version.  nodejs

Once you have that installed, you can open up a command shell of your choice.  I’ll be using PowerShell.  You’re going to want to install the node package manager (npm) globally so you can use it from the command line for all of your projects.  In order to do that, you’ll just need to run the following command in PowerShell or whatever command shell you decided to use:

npm install npm -g

If the above powershell looks a little weird to you, what we’re saying in english is that we want to use the node package manager to install the latest node package manager globally.

Next up is the Yeoman Generator.  This is a handy little tool that creates your SharePoint project for you.  So we need to go back to your trusty npm and install yeoman globally.

 npm install yo -g 

Once you have the Yeoman generator, you’ll want the SharePoint template generator.

 npm install @microsoft/generator-sharepoint -g 

Next up, Gulp.  Now, gulp is a task automation tool.  We’re basically going to use it to run our solution.

 npm install gulp -g 

There’s one last package that needs to be installed and that’s webpack, but I’ll skip it for now.  We’ll set that up when it’s time to deploy our solution.

First Web Part

Now that we have (almost) everything that we need installed, we can start with our project.  The installs above were 1 time installs since we specified that they were each to be globally installed.

The first thing that we want to do is create the directory where our solution will live.  So in PowerShell, I go to the base directory where I store all of my solutions and then I type the following command to create a directory called “SPFx” (call it whatever you want):

 md SPFx 

The above is the mkdir command so you could type the following and it’s exactly the same:

 mkdir SPFx 

Then we want to go to that newly created directory and run our Yeoman generator to create the project files. (At this point, you should be in your project path in PowerShell)

 yo @microsoft/sharepoint

Next, the generator will start asking you for details like what do you want to call your solution, are you building a web part or an extension, names, descriptions, and what JavaScript library you want to use. (The version of the generator at the time of this post is Version 2.0.0.0). Depending on which version you’re on, you may need to provide different inputs.

Here are my inputs. Once I hit enter, it starts installing a ton of stuff so you have time to check your email or maybe get a beverage of your choice.
sp yeoman

And this is what you’ll see when it’s done.  If you look inside the box in the image, it tells you what you need to “start” your solution.  You can go look at the 252 MB of SharePointy goodness that get’s created in the directory above.  (The size on disk is 297 MB).  I’ll let you inspect the files but for our purposes, we just want to run it.  This part I find kind of cool.  You DON’T need SharePoint installed on your machine for this.

sp yeoman end

Type the following to launch your solution inside the SharePoint Workbench!

 gulp serve 

There are a few things to note here.
First, this isn’t SharePoint but it functions like it in that you can click on the plus symbol to add a new web part. You’ll also see a few buttons at the top that will simulate what the page will look like on a mobile device or tablet.

workbench

Also, you may notice a certificate error and if you pay attention to the last bit of text outputted by the gulp serve command, you’ll see a warning regarding this. The workbench is using https and won’t load your scripts so you’ll want to run 1 more gulp command which we’ll do next, but first, I’ll add my web part to the page.

hello world workbench.PNG

Run the next command to fix the cert issue. The command will install a certificate. You’ll also get a prompt to confirm and the next time you run gulp serve, you won’t see the cert issue.

 gulp trust-dev-cert 

There’s something pretty cool about the workbench. If you have it running, you can go to your SharePoint Online and test out the page from there. Just go to your site and append /_layouts/15/workbench.aspx.  (Example: https://<tenant&gt;.sharepoint.com/_layouts/15/workbench.aspx)

That’s what you need to get started. To recap, we ran a few 1 time installs (nodejs, npm, gulp, yeoman, and the SharePoint generator). We created a solution using the yeoman generator, and we took a look at the SharePoint Workbench.

This was meant to be a quick and dirty starter guide (mainly for me). Below are additional resources if you want to start diving deeper into some of the concepts mentioned above. In another post, I’ll talk about webpack and deploy a solution.

Additional Resources

Error occurred in deployment step ‘Activate Features’

I was recently working on a solution that consisted of custom content types and forms.  I worked on it in my dev environment, made sure it was good to go, and tried to deploy it to a shaky test environment.  When deploying via PowerShell, the deployment status showed “Not Deployed” while the last operation result showed “The solution was successfully deployed”.

SolutionProperties

Everything that needed to go into the hive was where it should be but when I went to the Site Collection Features, my Feature was not there.  That test box also had Visual Studio on it so I tried deploying with Visual Studio and got the following error:

Error occurred in deployment step ‘Activate Features’: Feature with Id ‘<guid>’ is not installed in this farm, and cannot be added to this scope.

As I mentioned earlier, that test server has some issues so I checked everything; permissions, web.config, Visual Studio settings, the ULS, Job Definitions, Services, you name it.  I even created a Empty SP2013 solution with nothing in it other than a Feature.  I got the same errors and the only times that I didn’t were when I removed the Feature from the package or set the Feature’s scope to Web Application which wouldn’t help me.

Solution:  I packaged the wsp, and deployed via PowerShell using Add-SPSolution and Install-SPSolution.  This got me back to where I started where all the files were where they belonged but the Feature wasn’t available in the Site Collection Features page.

I then ran the following PowerShell command and my feature appeared in the Site Collection Features page and I was finally able to activate it.


Install-SPFeature "MyFeature"

SPSite – FileNotFoundException

You may be writing a consoleapp that uses the SPSite object. You write something like:

SPSite site = new SPSite(“http://yourSiteHere&#8221;);

Running the code produces the following error:

The Web application at http://yourSiteHere could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the inteded application.

You may need to go to your Solution properties and select Any CPU. If one doesn’t exist, you can make a copy of an existing platform to create it.

Hiding Items in the Site Actions Menu

I have a client that wanted to trim down the site actions menu to reduce clutter and confusion on their publishing site.  I originally went down the route of using

<HideCustomAction
GroupId = "Text"
HideActionId = "Text"
Id = "Text"
Location = "Text">



in the element manifest but that wasn’t working.  The next attempt involved the CustomSiteAction.xml file found in the Masterpage gallery’s Editing Menu folder.

The file contains an empty Console node.  The example below shows how to remove items.  You can tell from the ChangedNodeID which item in SiteActions is being removed.  Those ID’s can be found in the v4.master or simply by viewing the page’s source.

















Client Object Model

SharePoint 2010 introduces the Client Object Model, which is an alternative to web services when accessing data from SharePoint through remote applications. The Client OM provides you with a way to write code similar to the way you would when using the SharePoint API. It comes in 3 different flavors: .NET managed, Silverlight, and ECMAScript.

The Process

You start off by creating an instance of the client context. Once you have the context, you can start writing any commands that you’ll need (eg. Commands to retrieve list items). After this, you’ll run the ExecuteQuery method on your client context object which will send your request to the client service on the server. The client service is responsible for executing the requests passed to it and those results are then passed back to the client application.

The Code

As you can see, I started by instantiating a ClientContext object. This code is going to return the top 5 items from a products list so I need to pass in the address of the site where the list resides. Next, I create a web and a list object. As you can see, its very similar to what you’re already used to. We don’t have data to work with until we run the ExecuteQuery method.

The Results

The code above grabs the top 5 items in the products list and outputs the product name, description, and price (as seen below).

Sandboxed Solutions

SharePoint 2010 introduces a new feature that grants site collection administrators, the privilige to upload solutions on their own… No need for a farm admin… Yikes!?!

Allowing site collection administrators to do this will allow organizations to deploy solutions quickly, but sandboxed solutions do not provide quick deployment by sacrificing stability or security.

Deploying a Sandboxed Solution – [Site Collection Administrator]

Let’s say that you’re a site collection administrator and you find a webpart on codeplex that meets a business need. In the past, you would need a farm admin to deploy the solution after he/she deploys it in testing environment to make sure that the webpart isn’t going to introduce problems to the farm. The validation process could take a long time and by then, maybe you don’t need it anymore.

So, how does a site collection admin deploy a solution without the farm admin?

In the site settings page, under the Galleries section, click the “Solutions” link


Once you select Solutions, you’ll be redirected to the solutions gallery. As you can see in the next image, the Solutions tab is selected. In the ribbon, the site collection administrator can simply click on Upload Solution and point to the desired wsp file. Once the solution has been uploaded, you’ll see it in the list of solutions on the page. You’ll also need to activate it. To do this, you’ll simply select your solution and click the Activate button found in the ribbon. Once activated, you can freely use your solution within your site collection.

Stability – [Farm Administrator]

Now that the solution is activated, how do we ensure that the solution doesn’t make your environment unstable. SharePoint 2010 allows you to define resource quotas that allow you to monitor your solutions and that will shut down a solution for the day or until the farm admin can reset the solution. So if a developer creates a solution that crashes consistently or runs too many list queries or misuses resources, the farm admin can block the solution until the developer can correct it.

In Central Administration, go to Application Management > Specify Quota Templates.

In this page, you can specify your quota threshold that’s based on a point system.



The following is a list of resources that are monitored:

Resource Description Units Resources per Point Absolute Limit
AbnormalProcessTerminationCount Abnormally terminated process occurrence 1 1
CPUExecutionTime CPU Execution Time for site seconds 3,600 60
CriticalExceptionCount Critical Exception Events events 10 3
InvocationCount Solution Invocation Events events 10 3
PercentProcessorTime Percent CPU usage by solution percentage 85 100
ProcessCPUCycles Solution CPU cycles cycles 1×10^11 1×10^11
ProcessHandleCount Windows handles count items 10,000 1,000
ProcessIOBypes Windows handles count items 0 1×10^8
ProcessThreadCount Thread count in overall process instances 10,000 200
ProcessVirtualBytes Memory consumed bytes 0 1.0×10^9
SharePointDatabaseQueryCount Number of SharePoint database queries instances 20 100
SharePointDatabaseQueryTime Elapsed time to execute query seconds 120 60
UnhandledExceptionCount Number of unhandled exceptions instances 50 3
UnresponsiveProcessCount Number of unresponsive processes instances 2 1

Now, Microsoft didn’t provide Sandboxed Solutions without ensuring that it won’t wreak havoc on your farm. So, how did they make sure that these untrusted solutions can run without harming the farm? Well, typically when a solution is run, it’s managed by the w3wp worker process, also known as the IIS worker process. Sandboxed solutions however are managed by different processes. When a user makes a request to the Front End server, the FE web server identifies the code as a sandboxed solution. Instead of loading the IIS worker process, it contacts the SPUC worker process host service. This is essentially the sandbox environment. The host service then calls the SPUC worker process which will run the untrusted code and grant it access to a subset of the SharePoint Object Model. Now, this isn’t a smaller version of the object model. This is, in fact the full object model, but the SPUC worker process ensures that portions of it are not allowed. Some of the things that aren’t allowed are connections between web parts, editor parts, cross site queries and access to databases and file systems. These restrictions will ensure that your solution doesn’t gather information that is not within the scope of the site collection. Now you can have, for example, a site collection for clients and you don’t have to worry about a web part being configured to access information from various client site collections.

Update Items Quietly

There may come a time where you’ll need to update many items in a list and doing it manually would take way to long. In this post, I’ll show you how to modify list items without changing the last modified metadata and without firing an alert.

In this example, I’m going to change a single item in the announcements list. Here’s my item before I edit it. I’ve highlighted the Title (which is what I’m going to change) and the last modified information.

Now, the code is simple. All I’m doing is getting the specific item by its ID and adding “(Changed)” to the end of the title. To make the change quietly, you can’t use the item.Update() method. Instead, you’ll use item.SystemUpdate(). SystemUpdate will make your changes without firing an alert or updating the last modified information.

After I run my code, you’ll see that in the result, my title is changed and the last modified information is still the same.

One last thing. SystemUpdate also takes a boolean parameter. By default, the value is false; however, if you set it to true, the version number of your item will increment. If you choose to make the change and increment the version number using SystemUpdate(true), the last modified information will still remain the same and you still will not trigger an alert.

Running with Elevated Privileges

There may come a time when you need to run some code on a site regardless of who’s logged in at the time. Before, you would have to impersonate an account that has the privileges needed to execute the specific line(s) of code. Now, there are 2 ways that you can run the code without having to do an impersonaation.
Method#1
Create an SPSecurity.CodeToRunElevated object. When instantiating this object, it expects you to pass a method name as a parameter. Follow this line of code with an SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated object).
In the image below, you’ll see that I create a CodeToRunElevated object called elevatedCreateWeb and I’m passing in the name of my method that needs elevated privileges (CreateWeb). The next line is passed the object that I just created.
This method is the cleanest (easiest to read) way to do this.
Method#2
This method is a little more difficult to read but still simple. Instead of creating the 2 lines as in the example above, you’ll just need to create the second line. Now, since you don’t have a CodeToRunElevated object, you need to pass in delegate() { full code here }.

When you add your code, it will look something like this next image.

If you’ve taken a real good look at the last bit of code, you’ll notice 2 using statements that are used to create an SPSite and SPWeb object. You’ll also notice that when I instantiate them, I’m using other SPSite and SPWeb objects. I’m doing this because you can’t use an SPContext inside the code being run with elevated privileges. If instead I write SPWeb site = SPContext.Current.Web, inside my using statement, you may see an Access is Denied error because your web was created in the context of the current user.

Forms Authentication

If you come across a project that requires you to setup forms based authentication on a SharePoint site, its actually kind of simple. This post will walk you through creating a new database that will handle storing user information like usernames, passwords, and roles. The steps taht we’re going to take are:

  1. Create a database to store user info
  2. Extend a site
  3. Create the necessary web.config entries
  4. Create users and roles
  5. Configure the extended site for forms based authentication
  6. Grant the new users and roles permissions on the extended site

Creating the Database

Luckily, we don’t have to do alot to get a database up and running. You can run the Aspnet_regsql.exe tool to start a wizard that will create this database for you. The exe is found in \WINDOWS\Microsoft.NET\Framework\v2.0.50727. Double-click the file and let’s begin.

Once you run that tool, the ASP .NET SQL Server Setup Wizard will open. Click next to get started.

Make sure the “Configure SQL Server for application services” radio button is selected and click next.

Next, you’ll need to specify the server that will store the database and the database name. Now, for the database name, you have 1 of 3 options. You can leave it blank, like I do for this demo and it will create a generic name for your database “aspnetdb”. You also have the option of selecting a database from the dropdown. When you select a database, it will add the necessary tables and stored procedures without affecting your existing database’s content. The last option is to type in a new database name and it will create your database with the appropriate tables and stored procedures.

The next page will display your selections in the previous page. Confirm that everything is ok, and click Next.

Click Finish.

Once your database is created, you can go view it and inspect the tables and stored procedures provided. Below is an image of the tables created.

Extend a Site

In Central Admin, go to the Application Management tab and click on the Create or extend Web application link. This will take to to the following page. On this page, you’ll need to select the site that you want to extend. This part is pretty straight forward. Just select the Create a new IIS web site radio button, assign an unused port, provide a host header if needed and select a zone from the available items in the dropdown.

Configure the Web.Config

The next thing that we’ll need to do is setup the web.config by adding a connectinoStrings element, a membership element and a rolemanager element. We’re going to want to test the connection before we start to modify the SharePoint web.config. In order to do this, you’ll want to use Visual Studio to create a new website. Open the site’s web.config file and before the section, add your connection string information. Inside add your membership and roleManager.

A few things to pay attention to: In the connectionStrings’ add element, the name attribute’s value is whatever you want it to be. The same goes for the membership’s and roleManager’s defaultProvider.

Go ahead and copy the data, with your particular modifications to the connectionstring. For additional help, you can visit msdn to learn more on the connectionStrings element, the membership element and the roleManager element.

Note: Do not edit the web.config used by your site without creating a backup. If you make a mistake either in the sections that we’re going to add or even if you accidently add/remove a character from some random line in the file, you can break your site.

Create Users and Roles

Now that your web.config is setup in your test website, we’ll need to go to the ASP .NET Configuration. In the image below, it is located under the Project menu item. This will open the ASP.NET Web Site Administration Tool.

When the tool loads, you’ll see 3 sections in the bottom. We’re going to worry about the 1st two (Users and Roles).

First, click on the Select authentication type under the Users section. Make sure, From the Internet is selected. Go back to the previous page, and in the Users section, you’ll see a new link to create users. Click on the link, and create a couple of users. Then click Create or Manage Roles under the Roles section to create roles and assign users to each role. This part is simple, so I’ll leave that to you.

Enable Forms Authentication on the Extended Site

Now we go back to Central Admin. Go to Application Management > Authentication Providers (found under the application security section) and select your extended site. If you don’t see it, make sure that the original web application (the one that you extended) is in the dropdown on the page. When you select your extended site, you’ll see the following page. I’ve highlighted the important sections. You’ll see that the zone that appears is the zone that I selected when I extended the site. You’ll have to select Forms under the authentication type and then you’ll have to provide the Membership Provider and the Role Manager information. This information comes from your web.config file under the provider sections for each.

Once you click the save button, go back to the Application Management page and click the Site collection administrators link under the SharePoint Site Management section.

Make sure the correct web application appears in the dropdown and you can add one of the accounts created earlier in the Secondary site colleciton administrator section. If you use the Check Names button, it should find the account in your database. I created an admin user and admin group earlier and I’ll add the admin here.

Now you can log into the site as the administrator and add the other users from the database to your site.

Best Practice: In my opinion, and I’m sure most will agree with me, it is best to do everything through groups. You’ll want to create a SharePoint group and add users to the group instead of adding them directly to a site or list.

Note: The roles that we created earlier behave like domain groups and you should think of them as such. When you created your roles in the ASP.NET Web Site Administration Tool, you associated individual accounts to each role. Now you can go to a SharePoint group and add the role that you created. This will bring in all the users assigned to that role without you having to add them one by one.

When the user’s attempt to access your new forms authenticated site, they will be greeted with the following page asking for credentials. The system will handle validating the credentials against the database that we created in the beginning without you having to write any code.

Getting Started with Site Definitions

Site Definitions allow you to create you own sites templates that can be selected when creating new sites and contain their own lists/document libraries/webparts/features. (see image below) I’m going to show you how to quickly and easily create your own Site Definition from an existing Site Definition. If you want to add default functionality to your custom site definition, visit my post on Feature Stapling.

The first thing that you’ll want to do is create your own copy of an existing site template. To do this, go to the 12 Hive’s TEMPLATE\SiteTemplates folder. In here, we’re going to create a copy of the sts folder and rename the copy SHAREPOINTLESSONS. (I recommend you use all caps to make it semi-consistent with the rest of the folders; however, your site will work if you use lowercase or mixed case.)

Next, you’ll want to go to the TEMPLATE\1033\XML folder. (1033 for English. For other languages, use the appropriate LCID. If you have multiple LCID’s in your TEMPLATE folder, here is a chart to help you find the appropriate one.)

In this folder, create a new copy one of the webtemp xml files and rename it. In this example, I’ve renamed mine WEBTEMPSPL.xml.

The following image contains the contents of WEBTEMPSPL.xml before I edit it. As you can see, the format is as follows:

I’m going to remove all of the Template elements and create my own. First, create your new Template element and give it a Name attribute, as well as an ID attribute. The name that you use here must be the name of the new folder you created in the SiteTemplates directory. In this example, my template name must be SHAREPOINTLESSONS. As for the ID, it is recommended that you use a number above 10,000 to avoid conflicting with any ID’s that Microsoft may already be using. My ID is 10002 (I’ve already used 10001).

Now we’ll move on to the Configuration element. This one has 6 attributes that will need to be provided.

  1. ID – Unique ID for this particular configuration
  2. Title – Name that will appear for in the list box when users are creating new sites
  3. Hidden – Duh
  4. ImageUrl – Image displayed to the left of the listbox when you select this item
  5. Description – Text that appears beneath the image when you select this item
  6. DisplayCategory – Tab that this item will appear under

Once you are done filling in those attributes, save your xml file and run an IISReset. Now, when you go to create a new site, if you’ve followed this example to the letter, you’ll see a new tab called “Custom SPL Templates” in the Template Selection Section. When you click on that tab, you’ll see “SharePointLessons Site” which came from the Title attribute in the Configuration. To the left, you’ll see the image that I specified in the configuration and just below the image you’ll see the description.

So as you can see, its not difficult to get started. Now, if you want, you can go in and create a ton of features and “staple” them to your new Site Definition so that future uses of your Site Definition will contain default functionality. Here’s a link for a lesson in Feature Stapling.