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 ... 

Saturday, December 1, 2018

Machine Learning and Artificial Intelligence

As many of you know I have been playing with Sitecore Dain and the more feisty Sitecore Diana over the past year. Through this process I have learned a lot from a lot of people on AI and ML. The best algorithms to use, how to use multiple providers to reduce bias in algorithms.  Starting last week the Dain and Diana blog is publishing articles on some of that learning.  Look for cross-over posts here as we take some of that learning and apply it specifically to Sitecore and in some cases Cortex.

If you are interested in Machine Learning and Artificial Intelligence and have started using Cortex let me know.  I would love to reference some of your blog posts on amazing things you are doing with it.


Wednesday, November 14, 2018

Sitecore and the Tale of Two Session Config Entries

You probably know the main one in the web.config but the other is used by analytics. If you change one you should probably change the other or session will be in different places.

This article shows the sharedSession tag you need to change:

https://doc.sitecore.net/sitecore_experience_platform/81/setting_up_and_maintaining/xdb/session_state/walkthrough_configure_a_shared_session_state_database_using_the_sql_server_provider

Monday, January 15, 2018

Sitecore Commerce 9 QuickStarts - Installing Sitecore Commerce 9


The first step is to install Sitecore 9. If you are doing so in the development environment please read the Sitecore 9 QuickStart on Installing Sitecore 9

Once you have Sitecore 9 installed you can follow the installation guide. I will list any issues I ran into at each step and ways to resolve them.

WARNING: Make sure you install IIS Url Rewriter module or install will fail

3.6.1 Add a recognized user to the xDB shard databases

At this step you set up your database users.  If you get an error regarding :setvar then you have SQL Management Studio in the wrong mode. You can set the mode by clicking on the query menu and then choosing SQLCMD Mode.


4.3 Generate Sitecore XC Engine Package

During this step be aware that if you have added the .NET Framework using features you still need to install the Dev Pack. If you do not then when you open the project it will not show up in the list or will throw an error during build or publish.  If you get an error and then install it you will have to close Visual Studio and reopen it choosing Run As Adminstrator for it to be fixed.  You may have to click on each project and then right click and choose Properties and choose the 4.6.2 framework from the list. I did in Visual Studio 2017.

The rest of the install went smooth for me based on the instructions supplied. If you run into issue installing feel free to comment here or on the slack channel or on Sitecore StackExchange.  We are very happy to help you get started with this revolutionary version.




Friday, November 17, 2017

Sitecore 9 QuickStarts - Getting Started With xConnect

The best place to get started with XConnect is using Martina's documentation. It walks you through your basic XConnect console application.

Once you have this console app building start taking a look at the Jason Wilkerson blog articles on XConnect. Although tempting, do NOT start with Jason's articles. It is important that you get Martina's application working first and then start adding functionality from Jason's articles. The reason is that Martina's will do all the client certificate stuff properly and that is what you want for production.

I started myself with this console app and am now using Jason's blog articles myself.  My hope is to build out a repository on GitHub along with a series of articles on how to integrate XConnect with a variety of other applications in hopes this will save others time doing this.  If you are building an integration maybe we can collaborate and then add it to the repository for others to use.

When you create your project in Visual Studio 2017, if it defaults to creating your console app as 4.6.1 and you switch to 4.6.2 you may get an error about the root node.  If you do it is a bug in the conversion.  Check your app.config file and make sure it is formatted like this.  In my case it removed the configuration node and put startup within appSettings.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
  </startup>
  <appSettings>
    <add key="xConnectCertificateThumbprint" value="082FF77F7C87A93A3C5FE88CFB3DAB730DEF331A"/>
  </appSettings>
</configuration>

If you do not see the 4.6.2 option in Visual Studio 2017 then you need to install the developer pack

Troubleshooting

The error you may run into and in fact I did is, "Sitecore.XConnect.XdbCollectionUnavailableException: 'The HTTP response was not successful: Unauthorized' The StackExchange mentions these 3 causes:

  1. Your thumbprint or certificate is not properly installed so you are being blocked from connecting to xConnect
  2. Your application does not have access to the certificate (e.g. IIS user does not have permission)
  3. You did not execute the script in the installation guide Post-installation steps.
On first install I had forgot to run the execution script, doh. The second time around it was the second one but it was a step further it was not the certificate itself but a policy applied to my laptop by IT that was not allowing the root authority because I was generating a self-signed certificate on my development environment. Hopefully this will help you when you run into this issue.

If you are running into issues with 401 or 403 errors connecting to xConnnect then this article can help you troubleshooting the certificate issues. It is all about xConnect Security