Wednesday, July 20, 2016

Working with Sitecore SPEAK Chart Controls

This post will help some of you to speed up Sitecore SPEAK development wherein you need to use chart controls and avoid spending time figuring out why some of the things don't work the first time as expected.

Get your hands on some out of the box implementations right away

If you are implementing pages having chart controls, you need to look at this Sitecore SPEAK app and then start navigating into the implementation code on your local sitecore instnace. 

To access Sitecore SPEAK app that comes out of the box with default sitecore installations you need to navigate to this url http://sitecoreinstancename/sitecore/client/Applications/Demos/SpeakCharting/Area. From this page you can navigate to different chart implementation pages.

The codebase (javascript page files) and json data for all these pages are located in your website root folder at this path \SitecoreInstanceName\Website\sitecore\shell\client\Applications\Demos\SpeakCharting 

Getting the Chart Data

  1. For your chart to work, you need to add ChartDataProvider and any of the chart controls that you want to work with on your page / tab
  2. You may also create chart field definition items under your page settings to map it to CategoryChartField, SeriesChartField and ValueChartField (depending on the chart) as shown below
  3. ChartField Settings

  4. For your chart data provider, you may want to get data from your own APIs. If that is the case you can setup the DataUrl property of the ChartDataProvider to the path of your API e.g./api/sitecore/ReportData/GetPerformanceSummary where ReportData is your controller and GetPerformanceSummary is your controller action
  5. In your page code, create requestOptions object (which also can contain dataUrl if you dont want to set it up at design time in control properties)

  6.          var requestOptions = {
                  parameters: "",
                  onSuccess: function (result) {
                      app.getDataCallback.apply(app, arguments);
                  }, 
              };
    

  7. Very importantly, configure the error handler for ChartDataProvider so that you know if there are any issues retriving your chart data (in case you have any custom logic than simply getting and returning values from Sitecore)

  8.           this.ChartDataProvider.on("error", function (errorObject) {
                  console.log('Error in ChartDataProviderJobPerformance: ' + errorObject);
              });
    

  9. ChartDataProvider does not call your API until you yourself make a call to its getData function

  10.           this.ChartDataProvider.viewModel.getData(requestOptions);
    

Data Format and Helper Functions

Another important thing to note is ChartControls expect data in a specific Json format. I was returning valid list of json objects in this format [{}, {}, {}] but chart won't show up any data and no errors are thrown. Even ChartDataProvider was showing that it has the "data" property appropriately setup.

Now when I looked at some of the sample data json files in the location I mentioned before, I figured out that everything has some consistent structure.

So I created some helper functions to return my data in this format

{
  "data": {
    "dataset": [
      {
        "data": [
          { },
          { },
          { }
        ]
      }
    ]
  }
}


Helper Functions in my Controller to wrap my data in this format:

public static string GetJsonSerializedData(object data)
        {
            string jsonData = JsonConvert.SerializeObject(data, Formatting.None, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            string requiredStructure = "{" +
                                    "\"data\": ";
            jsonData = jsonData.Insert(0, requiredStructure);
            jsonData = jsonData.Insert(jsonData.Length, "}");

            return jsonData;
        }

Please note: I am using Json.net Nuget package to serialize my entities into Json and I have to mention the format of the date to show it in human readable format. The list of objects is wrapped around the outer structure required for chart control to work.

public static string AddJsonHeader(string jsonData)
        {
            if (!String.IsNullOrEmpty(jsonData))
            {
                string requiredStructure = "{\"data\": {" +
                                            "\"dataset\": [";
                jsonData = jsonData.Insert(0, requiredStructure);
                jsonData = jsonData.Insert(jsonData.Length, "]}}");
            }
            return jsonData;
        }

Now after doing all this, I am able to see my chart data coming up and being shown nicely


SPEAK Chart


Hope this helps others working on SPEAK applications and using chart controls


No comments:

Post a Comment