Sunday, March 31, 2019

Creating Your Own Sitecore Services Client API Controllers

So now that I have my Sitecore Speak 3 Application there are multiple ways you can communicate with it. One way is to use the Sitecore Services Client API.

Sitecore provides a very useful Item Service that is useful to read information about items. The basic usage is something like this:


  • To get an item given its id you would do something like this:

    http://{your sitecore url}/sitecore/api/ssc/item/110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9
  • To get an item by path you can do something like this:

    http://{your sitecore url}/api/ssc/item/?path=/sitecore/content/Home
  • To perform an item search you can do this:

    http://{your sitecore url}/api/ssc/item/search?term=Home
You can extend the Item Service to do more things.  David Peterson has written a good article to help you with this.

In my case, I needed something a bit different. I am getting some data from Sitecore items but additionally calling other APIs and pulling data from SQL Server and other sources.  For that it makes sense to create your own Controllers. 

Step 1: Create your Class Library


When doing this be aware of your version of Sitecore as you will need to make sure you are using the same version of the .NET Framework for your project.  I am using Sitecore 9.1 so I used 4.6.1 for my library.  I tried to use .NET Core or .NET Standard and it would not work for me.  When naming your take into account the routing.  By default it uses this as the route:

        http://localhost/api/ssc/{namespace}/{controller_name}/{id}/{controller_menhod}

        eg. http://localhost/api/ssc/SitecoreGuild-Ssc/Mentoring/123/GetTopics

WARNING: The namespace is important as Sitecore will use it for the default routing. You can override the routing with some more work but for me I tried to keep it simple and simplified my namespace name. This article provides more info on creating custom routes.

Next add the proper references to your .NET Framework 4.6.1 class library project in my case it is these:
  •  Microsoft.AspNet.WebApi.Core v5.2.6 - If you are using 9.1 then you need to use this. There is a newer version but you will get issues as Sitecore uses this version.
  • Sitecore.Services.Core - This would be the version in your bin folder after your Sitecore install.
  • Sitecore.Services.Infrastructure - This would be the version in your bin folder after your Sitecore install.
Before you start your development, you can do a sanity check in your environment to see if that works. I used the Mike Robbins Controller in my .Net Framework project and copied the result to the bin folder. Once I saw that one was coming up I knew my project was configured correctly.  After that I deleted his controller and started on my own.  

Create a new controller and derive it from ServicesApiController. At the top make sure you include

using System.Web.Http;

If you do not then it will prompt you to include the MVC one and if you do that you will get lots of funky errors. This one step will save you lots of confusion later.

Once you are ready to go beyond localhost you will need to do some additional configurations which are mentioned in this article.

On your new controller you will probably want to include a name. If you don't then Sitecore will do it for you and it will likely not look pretty.

    [ServicesController("MyServices/MyController")]
    public class MyControllerServiceApiController : ServicesApiController

As you add actions to your controller you will need to decorate them with an action name.

        [ActionName("GetSample")]
        public string GetSample(string id)
        {
             return "MySample:
        }

If you forget to put action it may work for your first method or it may fail but if you have 2 methods the second one will definitely fail with: 

No action was found on the controller 'MyControllerServiceApiController' that matches the request."}


Friday, March 22, 2019

Getting Speak 3 With A Little Help From My Friends

A Better Way Of Starting A New Speak 3 Project

I began the task to start my Speak 3 application and struggled. More and more people reached out to assist me and my previous blog article was all about that help.  However then this came up and I was surprised it was so buried in Search.  Now that I have found it I am going to let all of you know.

If you are starting with Speak 3 and Angular you will want to check out this article on the Sitecore Speak Starter Template by Mihály Árvai, and the Corresponding GitHub. It will save you a ton of time. The only thing to be aware of is the build command is npm run-script build. If you forget the run-script the command will prompt you so no worries.

Special thanks to:

Creating New Pages

TO DO: I am still doing this for my project but as I do it I will document it here.

Adding Components

When you are ready to add components then your next step should be to set up this Sitecore Speak UI Library project.  This article explains how to get the Sitecore Speak 3 UI Collection set up. Then you can see some components in use and copy them over to your solution as a starting point. 

You will get an error in the header.components.html file. Simply open the header.components.ts and make sure it has the isNavigationShown : boolean; as noted below. This will fix the error and then the project will run. You can then click on component pages and see how components work then use them in your project.

import { Component, OnInit } from '@angular/core';
import { SciLogoutService } from '@speak/ng-sc/logout';

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
// WAS MISSING IN EXAMPLE
isNavigationShown : boolean;

constructor(
public logoutService: SciLogoutService) { }

ngOnInit() {
}

}


Monday, March 18, 2019

Speak Friend and Enter - The Journey Through Mordor to create your first Speak 3 Application

Dain and Diana are currently learning all about Sitecore Speak 3. As they know nothing about NodeJS or Angular this is quite a challenge for them.  This article will help you with some of the obstacles they ran into and how you can overcome them.

A few friends have helped Dain in his quest. Special thanks to:
  • Tim AKA "Hi My Name Is Tim" for writing an amazing article on Creating a Sitecore Speak 3 application
  • Dean Thrasher please follow him on Twitter using @dthrasher. His team created a Speak 3 app as part of Hackathon and that helped us with some of the issues
  • Tony Mamedbekov my hackathon team mate that taught me lots about npm and versions of packages in the packages.json file. Dll hell all over again :)
  • Julia Gavrilova who wrote another amazing article that ensured I knew that I needed Angular 4 not 5. Thanks you saved me a lot of time.
  • James Q Quick please follow him on Twitter using @jamesqquick. I used his article to help me start debugging my Speak 3 app.  
Ok let's get started.

Step 1: Get Prepared First.

As the BoyScouts say, always be prepared. Before we start we need to get things ready.
  • As Tim recommends you should install Visual Studio Code. DAIN and Diana recommend it as well.
  • Install Node.JS. I just installed the Recommended for most users version.
  • Install Angular 4 using

    Npm install -g @angular/cli@1.4

    Beware this is one of those gotchas. Thanks Julia Gavrilova for this tip. I could not figure out why I got the error "Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin'" and then I read your blog and realized
    Sitecore Speak 3 uses Angular 4, which means that all modules you decide to use should support this version of Angular. In addition to that syntax is different between Angular versions, and you need to pay attention to that as well when writing your code. 
    If you previously installed Angular 5 or 6 instead and you run the command it will roll back and reinstall the proper version.
  • As a sanity check you should check the versions. In my case my global Angular CLI version (7.3.6) is greater than my local version (1.2.7).

     ng version
  • If your local version is not new enough you will need to do an uninstall in reinstall of the right one.

Step 2: Creating your application

  • Open a Command Prompt as Run As Administrator. 
  • Change directory to the folder above where you want to create your application and then run this replacing app-name with the name of your application eg. DainSpeak3

    ng new app-name
  • Now you can stumble through or you can take Tim's advice and download the Sitecore Speak 3 Reference Application. I did and it saved me a lot of time. Thanks Tim
  • Once downloaded look in the "Sitecore SPEAK 3.0 Reference Application\SPEAK3.Apps.Minimal\SPEAK3.Apps.Minimal\code\Sc.Integration.Ref.App.Client" folder. Copy the .npmrc and package.json file from here to your application folder.
  • Change directory so you are in your application folder and run

    npm install
  • Now if the versions are not right when you run ng version then you may have to do a few npm uninstall and npm install of given components to get all the right ones.
  • If you try ng server --open from your application folder and it does not load it will often tell you which package it could not load.  If it says config is null or some obscure error then do an npm uninstall and npm install and it should tell you which modules it skipped. Hopefully at some point they will solve this issue with package versions.  Until then you have to play with it.
After running ng server --open I got my application to open on the default port.  It is showing the Welcome to app screen but that is the start. If you got here pat yourself on the back and go buy a poutine and a chocolate milk or if you prefer a nice glass of Jura Scotch.


Now you may be all excited because it opened but remember if you wanted it to be disconnected mode then you need to load it a little differently.

npm run-script start:disconnected

Step 3: Customizing How Your Application Starts

So the default port for your application is 4200 but you don't have to live with that. You can open the 
angular-cli.json and change the port to whatever you wish. The default file will be missing the serve section so you will need to add it so it looks like below.  For those Stephen King fans you will understand the port number.

  "defaults": {
    "styleExt": "css",
    "component": {},
     "serve": {
          "port": 1408
     }

Once you change the port you can open your application again and it will use the new port.

Step 4: Paging Dr Kildare or customizing how your application looks

This is where the real fun begins. Open Visual Studio Code and then from the File menu chooose Open Folder.  Choose your application folder and click Select Folder.  This will open your application.

To start we will look at the app.component.html file located in the /src/apps folder. I simply copied the one from the reference application.

Next you can generated a new landing-page component using ng generate component landing-page

I took the easy way out and copied the \src\app folder from the reference project. If you want to look at the steps to do it yourself you can see them in the article Speak 3 adventures of a back end developer.

Open the angular-cli.json and look for the style section. Change style.css to ../node_modules/@speak/styling/dist/styles/sitecore.css

The style node now looks like this:

      "styles": [
        "../node_modules/@speak/styling/dist/styles/sitecore.css"
      ],

Again you can follow the steps in in the article Speak 3 adventures of a back end developer or you can simply copy over the angular-cli.json from the reference project. I took the short cut and copied it over.

If you choose to copy it like I did then you only have to change the project name to match yours and the port to match yours.

Step 5: Debugging With Visual Studio Code

Speaking of Scotch, this will be a lifesaver especially if you are new to Angular and Speak3.  Check out this article and it will show you step by step how to create a debugging configuration.

https://scotch.io/tutorials/debugging-angular-cli-applications-in-visual-studio-code

Step 6: Simulating Login and Logout while Disconnected

This is done by copying the mock folder in the root of the reference application to your application.

Step 7: Running it inside Sitecore

The first step is creating your Application in Sitecore. Log into the Sitecore admin and click on Desktop. Change the database to core and then open content editor.  Navigate to /sitecore/content/applications. Right-click and create your application.

The second step is to prepare to build your release.

If you copied the packages.json file from Sitecore you will need to edit the application name and version. Under scripts you will need to edit the build property to point to your application.

{
  "name": "MySpeak",
  "version": "0.0.1",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "npm run start:disconnected",
    "start:disconnected": "ng serve --proxy-config disconnected-mode.conf.js",
    "build": "ng build --prod --base-href=/sitecore/shell/client/Applications/MySpeak",
    "postbuild": "ng-sc --entry ./dist/index.html && sc-license-checker",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

If your application uses any more modules the you would need to add them here too. Once you are ready run this command to create your release application in the dist folder.

npm run-script build


To be Continued ...