Getting Started with Windows Forms Application

This section describes how to create a Windows Forms application with embedded dashboard viewer.

Project Creation

Create a new Windows Forms Application Project using Microsoft Visual Studio IDE 2012 or higher.

Adding files and references

Add the scripts, styles and refer fonts that are required for the dashboard from the following location to the application project and set the Build Action and Copy to Output Directory properties to Content and Copy always, respectively as shown in below screenshot for the items inside those folders.

%localappdata%\Syncfusion\Dashboard Platform SDK\Getting Started Samples\Common\Html

Include the dashboard file (*.sydx) in the project from the below mentioned location and set the Build Action and Copy to Output Directory properties to Content and Copy always, respectively as shown in below screenshot.

`%localappdata%\Syncfusion\Dashboard Platform SDK\Getting Started Samples\Common\Dashboards`

Set the Output Directory value to script, themes, and fonts.

Include the below mentioned files into project from the SDK build installed location as shown in figure below.

This image represents adding CefSharp files to the application.

⦁ cef.pak

⦁ cef_100_percent.pak

⦁ cef_200_percent.pak

⦁ d3dcompiler_43.dll

⦁ d3dcompiler_46.dll

⦁ icudtl.dat

⦁ libcef.dll.dll

⦁ libEGL.dll

⦁ libGLESv2.dll

The above mentioned files can be found in the following Dashboard SDK samples location:

%localappdata%\Syncfusion\Dashboard Platform SDK\Getting Started Samples\Common\Packages

Set the Build Action property to Content and the Copy to Output Directory property to Copy always as shown in the following image for all the files added to the project.

Set the Output Directory value to CefSharp files.

Adding Dashboard Viewer Assembly References

Right-click the project and add the following assembly references through choosing Add > Reference... as shown below,

This image represents the Add Reference option in References.

selecting the below mentioned assemblies in dialog shown, which allows you to use any of the Syncfusion Windows Form control within it.

⦁ CefSharp.Core.dll

⦁ CefSharp.WinForms.dll

⦁ CefSharp.dll

⦁ CefSharp.BrowserSubprocess.dll

⦁ CefSharp.BrowserSubprocess.Core.dll

The above mentioned assembly files can be found in the following Dashboard SDK samples location:

%localappdata%\Syncfusion\Dashboard Platform SDK\Getting Started Samples\Common\Packages

This image represents choosing Cefsharp dlls to be added.

This image represents the chosen Cefsharp dlls to be added in the application.

Generating URL

Add the below code Main method of Program class so to initialize the ChromiumWebBrowserinstance before the code where Form instance is initialized.

var settings = new CefSettings();
   settings.PackLoadingDisabled = true;
   settings.LogSeverity = LogSeverity.Disable;
   if(!Cef.Initialize(settings))
   {
	  if(Environment.GetCommandLineArgs().Contains("--type=renderer"))
	    Environment.Exit(0);
   }
Dim settings = New CefSettings()
settings.PackLoadingDisabled = True
settings.LogSeverity = LogSeverity.Disable
If Not Cef.Initialize(settings) Then
	If Environment.GetCommandLineArgs().Contains("--type=renderer") Then
		Environment.[Exit](0)
	End If
End If

Include the following code under the Form1 class that you will launch with dashboard from Main method.

using CefSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

    public partial class Form1 : Form
    {
        private string _sydxFileName = "WorldWideCarSalesDashboard.sydx";
        public string SydxFileName
        {
            get { return _sydxFileName; }
            set { _sydxFileName = value; }
        }

        internal static Process dashboardServiceProcess = new Process();

        public string Url { get; set; }

        private string dashboardsDirectory = string.Empty;
        // Get the service from Common Folder
        private string serviceDirectory = Path.GetFullPath(Path.Combine(@"..\..\..\..\..\")) + "Service";

        /// <summary>
        /// Initializing widget on  window and closing IIS Express while closing widget window.
        /// </summary>
        public Form1()
        {
            this.FormClosing += Form1_Closing;
            if (GenerateUrl())
                InitializeComponent();
            else
                Environment.Exit(0);
        }
        /// <summary>
        /// Close IIS Express Process while closing Window.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Closing(object sender, FormClosingEventArgs e)
        {
            DashboardWindowsServiceInfo.ClearIISExpressProcess(dashboardServiceProcess);
        }
        /// <summary>
        /// Generate the serviceUrl to render Dashboard
        /// </summary>
        private bool GenerateUrl()
        {
            DashboardWindowsServiceInfo dashboardViewer = new DashboardWindowsServiceInfo(dashboardServiceProcess, serviceDirectory);

            string url = dashboardViewer.GetUrlOfHtmlPage(SydxFileName);
            if (!string.IsNullOrWhiteSpace(url))
            {
                Url = url;
                return true;
            }
            else
                return false;
        }

    }
Imports CefSharp
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Diagnostics
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms
Imports System.IO

Public Partial Class Form1
	Inherits Form
	Private _sydxFileName As String = "WorldWideCarSalesDashboard.sydx"
	Public Property SydxFileName() As String
		Get
			Return _sydxFileName
		End Get
		Set
			_sydxFileName = value
		End Set
	End Property

	Friend Shared dashboardServiceProcess As New Process()

	Public Property Url() As String
		Get
			Return m_Url
		End Get
		Set
			m_Url = Value
		End Set
	End Property
	Private m_Url As String

	Private dashboardsDirectory As String = String.Empty
	' Get the service from Common Folder
	Private serviceDirectory As String = Path.GetFullPath(Path.Combine("..\..\..\..\")) + "Common\Service"

	''' <summary>
	''' Initializing widget on  window and closing IIS Express while closing widget window.
	''' </summary>
	Public Sub New()
		AddHandler Me.FormClosing, AddressOf Form1_Closing
		If GenerateUrl() Then
			InitializeComponent()
		Else
			Environment.[Exit](0)
		End If
	End Sub
	''' <summary>
	''' Close IIS Express Process while closing Window.
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	Private Sub Form1_Closing(sender As Object, e As FormClosingEventArgs)
		DashboardWindowsServiceInfo.ClearIISExpressProcess(dashboardServiceProcess)
	End Sub
	''' <summary>
	''' Generate the serviceUrl to render Dashboard
	''' </summary>
	Private Function GenerateUrl() As Boolean
		Dim dashboardViewer As New DashboardWindowsServiceInfo(dashboardServiceProcess, serviceDirectory)

		Dim url__1 As String = dashboardViewer.GetUrlOfHtmlPage(SydxFileName)
		If Not String.IsNullOrWhiteSpace(url__1) Then
			Url = url__1
			Return True
		Else
			Return False
		End If
	End Function

End Class

Create a class named DashboardWindowsServiceInfo and add the below code within the class.

using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using System.Text;
using System.Windows;
using Microsoft.Win32;
using System.Xml.Serialization;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Net;
using System.Linq;
using System.Diagnostics;
using System.Globalization;


    /// <summary>
    ///     Class for Dashboard Viewer
    /// </summary>
    public class DashboardWindowsServiceInfo
    {
        #region Private Variables

        private readonly string _environmentFolder = AppDomain.CurrentDomain.BaseDirectory;

        string Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

        private const string HtmlFolder = "Html\\";

        public string ServiceUrl;

        public string ErrorMessage;

        #endregion

        /// <summary>
        ///     Constructor for class DashboardWindowsServiceInfo
        /// </summary>
        public DashboardWindowsServiceInfo(Process serviceProcess, string serviceDirectoryPath)
        {
            DashboardServiceProcess = serviceProcess;
            string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            #region Pick IISExpress Dashboard Service Url
            ServiceUrl = GetIISExpressServiceUrl(serviceDirectoryPath);
            if (ValidateDashboardService(ServiceUrl))
            {
                ServiceUrl = string.Empty;
                ErrorMessage = "An Error Occurred while hosting Dashboard Service";
                MessageBox.Show(ErrorMessage);
                Environment.Exit(0);
            }
            #endregion
        }
        /// <summary>
        /// used to clear other Process while running IIS Express.
        /// </summary>
        /// <param name="process"></param>
        public static void ClearIISExpressProcess(Process process)
        {
            if (IISExpress.IsRunning(process))
            {
                process.Kill();
            }
        }
        /// <summary>
        /// Used to pick the Hosted IISExpress Dashboard Service URL 
        /// </summary>
        /// <param name="dashboardServicePath"></param>
        /// <returns></returns>
        private string GetIISExpressServiceUrl(string dashboardServicePath)
        {
            string availablePort = IISExpress.StartIISExpress(DashboardServiceProcess, dashboardServicePath);
            return "http://localhost:" + availablePort + "/DashboardService.svc";
        }
        /// <summary>
        /// Validate whether Dashboard Service is running in the Url
        /// </summary>
        /// <param name="dashboardServiceUrl">Dashboard Service Url</param>
        /// <returns>returns whether valid dashboard service</returns>
        private static bool ValidateDashboardService(string dashboardServiceUrl)
        {
            bool errorOccurred = false;
            try
            {
                if (string.IsNullOrWhiteSpace(dashboardServiceUrl))
                {
                    return true;
                }
                if (!dashboardServiceUrl.Contains("http://") && !dashboardServiceUrl.Contains("https://"))
                    dashboardServiceUrl = "http://" + dashboardServiceUrl + @"/IsServiceExists";
                else
                    dashboardServiceUrl = dashboardServiceUrl + @"/IsServiceExists";
                WebRequest request = WebRequest.Create(new Uri(dashboardServiceUrl, UriKind.Absolute));
                request.Method = "GET";
                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        string text = reader.ReadToEnd();
                        if (!text.Contains(System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("DashboardServiceExists"))))
                        {
                            errorOccurred = true;
                        }
                    }
                }
                dashboardServiceUrl = dashboardServiceUrl.Replace(@"/IsServiceExists", "");

            }
            catch (Exception e)
            {
                dashboardServiceUrl = dashboardServiceUrl.Replace(@"/IsServiceExists", "");
                errorOccurred = true;
            }
            return errorOccurred;
        }
        /// <summary>
        ///     Get Url string for the generated HTML page
        /// </summary>
        /// <param name="sydxFileName">SYDX file name</param>
        /// <param name="serviceUrl">Service URL</param>
        /// <returns></returns>
        public Process DashboardServiceProcess { get; set; }

        public string GetUrlOfHtmlPage(string sydxFileName)
        {
            if (string.IsNullOrWhiteSpace(sydxFileName) || string.IsNullOrWhiteSpace(ServiceUrl))
                return string.Empty;

            DashboardProperties dashboardProperties = new DashboardProperties
            {
                SydxFileName = sydxFileName,
                ServiceUrl = ServiceUrl,
            };
            return GetUrlOfHtmlPage(dashboardProperties);
        }

        /// <summary>
        ///     Generate Viewer HTML String
        /// </summary>
        #region Generate Viewer HTML String        

        private const string BeforeHeadHtml = "<!-- saved from url=(0014)about:internet -->\n"
                                          + "<!DOCTYPE html>\n"
                                          + "<html xmlns=\"http://www.w3.org/1999/xhtml\" style=\"height :100% ;width:100%;\">\n"
                                          + "<head>\n"
                                          + "<meta charset=\"utf-8\" content=\"width=device-width, initial-scale=1.0\">"
                                          + "<script>window.destroyAll = function(){try{ej.widget.destroyAll($('.e-js').off());}catch(e){} $(document.body).html('-'); CollectGarbage(); }; </script>";

        /// <summary>
        ///     Get Url string for the generated html page
        /// </summary>

        private string GetUrlOfHtmlPage(DashboardProperties dashboardProperties)
        {
            var jsFiles = new List<string>
            {
                "jquery-1.10.2.min.js",
                "jquery.easing.1.3.min.js",
                "ej.dashboardViewer.all.min.js",
            };

            var cssFiles = new List<string>
            {
				"default-theme/ej.dashboardViewer.all.min.css",
                "chromium.css",
            };

            try
            {
                string htmlString = GetHtmlString(GetViewer(dashboardProperties), jsFiles, cssFiles).ToString();

                //Below code block is used to copy the HTML related files from app folder since app folder doesn't have required permission to write file.
                string sourceFolderPath = AppDomain.CurrentDomain.BaseDirectory + HtmlFolder;
                if (!File.Exists(sourceFolderPath))
                    Directory.CreateDirectory(sourceFolderPath);
                string filePath = sourceFolderPath + "Temp.html";
                //End

                using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
                {
                    using (StreamWriter w = new StreamWriter(fileStream, Encoding.UTF8))
                    {
                        w.Write(htmlString);
                    }
                }

                return filePath;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return string.Empty;
        }
        /// <summary>
        /// Get HTML JavaScript files CSS files. 
        /// </summary>
        private StringBuilder GetHtmlString(string bodyString, IEnumerable<string> jsFiles, IEnumerable<string> cssFiles)
        {
            var headSb = new StringBuilder();
            foreach (var item in jsFiles)
            {
                headSb.Append("<script src=\"scripts/" + item + "\" type=\"text/javascript\"></script>");
            }
            foreach (var item in cssFiles)
            {
                headSb.Append("<link href=\"themes/" + item + "\" rel=\"stylesheet\"></link>");
            }
            var htmlSb = new StringBuilder();
            htmlSb.Append(BeforeHeadHtml);
            htmlSb.Append(headSb);
            htmlSb.Append("</head>\n");
            htmlSb.Append(bodyString);
            htmlSb.Append("</html>");
            return htmlSb;
        }
        /// <summary>
        ///     Generate the Viewer HTML String
        /// </summary>
        private string GetViewer(DashboardProperties dashboardProperties)
        {
            if (dashboardProperties == null) return string.Empty;

            var sydxPath = _environmentFolder + dashboardProperties.SydxFileName;
            var viewerStr = "$('#dashboard').ejDashboardViewer({serviceUrl: '" + dashboardProperties.ServiceUrl +
                            "', dashboardPath: '" +
                            sydxPath.Replace(@"\", @"\\") +
                            "',filterParameters:location.search.substr(1)});";
            var stringBuilder = new StringBuilder();
            stringBuilder.Append("<body style=\"width:100%; height:100%; overflow:hidden;\">");
            stringBuilder.Append("<div id=\"dashboard\" style=\"width:100%; height:100%;\" />");
            stringBuilder.Append("<script type=\"text/javascript\" language=\"javascript\">");
            stringBuilder.Append(viewerStr);
            stringBuilder.Append("</script>");
            stringBuilder.Append("</body>");
            return stringBuilder.ToString();
        }

        #endregion
    }

    /// <summary>
    ///     Class for Dashboard Properties
    /// </summary>
    public class DashboardProperties
    {
        /// <summary>
        ///     Gets or sets the SYDX File Name
        /// </summary>
        public string SydxFileName { get; set; }

        /// <summary>
        ///     Gets or sets the ServiceUrl
        /// </summary>
        public string ServiceUrl { get; set; }
    }
Imports System.Collections.Generic
Imports System.IO
Imports System.Security
Imports System.Text
Imports System.Windows
Imports Microsoft.Win32
Imports System.Xml.Serialization
Imports System.Windows.Forms
Imports System.Net.NetworkInformation
Imports System.Net
Imports System.Linq
Imports System.Diagnostics
Imports System.Globalization


''' <summary>
'''     Class for DashboardWindowsServiceInfo
''' </summary>
Public Class DashboardWindowsServiceInfo
	#Region "Private Variables"

	Private ReadOnly _environmentFolder As String = AppDomain.CurrentDomain.BaseDirectory

	Private Version As String = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()

	Private Const HtmlFolder As String = "Html\"

	Public ServiceUrl As String

	Public ErrorMessage As String

	#End Region

	''' <summary>
	'''     Constructor for class DashboardWindowsServiceInfo
	''' </summary>
	Public Sub New(serviceProcess As Process, serviceDirectoryPath As String)
		DashboardServiceProcess = serviceProcess
		Dim version As String = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
		'#Region "Pick IISExpress Dashboard Service Url"
		ServiceUrl = GetIISExpressServiceUrl(serviceDirectoryPath)
		If ValidateDashboardService(ServiceUrl) Then
			ServiceUrl = String.Empty
			ErrorMessage = "An Error Occurred while hosting Dashboard Service"
			MessageBox.Show(ErrorMessage)
			Environment.[Exit](0)
			'#End Region
		End If
	End Sub
	''' <summary>
	''' used to clear other Process while running IIS Express.
	''' </summary>
	''' <param name="process"></param>
	Public Shared Sub ClearIISExpressProcess(process As Process)
		If IISExpress.IsRunning(process) Then
			process.Kill()
		End If
	End Sub
	''' <summary>
	''' Used to pick the Hosted IISExpress Dashboard Service URL 
	''' </summary>
	''' <param name="dashboardServicePath"></param>
	''' <returns></returns>
	Private Function GetIISExpressServiceUrl(dashboardServicePath As String) As String
		Dim availablePort As String = IISExpress.StartIISExpress(DashboardServiceProcess, dashboardServicePath)
		Return (Convert.ToString("http://localhost:") & availablePort) + "/DashboardService.svc"
	End Function
	''' <summary>
	''' Validate whether Dashboard Service is running in the Url
	''' </summary>
	''' <param name="dashboardServiceUrl">Dashboard Service Url</param>
	''' <returns>returns whether valid dashboard service</returns>
	Private Shared Function ValidateDashboardService(dashboardServiceUrl As String) As Boolean
		Dim errorOccurred As Boolean = False
		Try
			If String.IsNullOrWhiteSpace(dashboardServiceUrl) Then
				Return True
			End If
			If Not dashboardServiceUrl.Contains("http://") AndAlso Not dashboardServiceUrl.Contains("https://") Then
				dashboardServiceUrl = (Convert.ToString("http://") & dashboardServiceUrl) + "/IsServiceExists"
			Else
				dashboardServiceUrl = dashboardServiceUrl & Convert.ToString("/IsServiceExists")
			End If
			Dim request As WebRequest = WebRequest.Create(New Uri(dashboardServiceUrl, UriKind.Absolute))
			request.Method = "GET"
			Using response As WebResponse = request.GetResponse()
				Using reader As New StreamReader(response.GetResponseStream())
					Dim text As String = reader.ReadToEnd()
					If Not text.Contains(System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("DashboardServiceExists"))) Then
						errorOccurred = True
					End If
				End Using
			End Using

			dashboardServiceUrl = dashboardServiceUrl.Replace("/IsServiceExists", "")
		Catch e As Exception
			dashboardServiceUrl = dashboardServiceUrl.Replace("/IsServiceExists", "")
			errorOccurred = True
		End Try
		Return errorOccurred
	End Function
	''' <summary>
	'''     Get Url string for the generated HTML page
	''' </summary>
	''' <param name="sydxFileName">SYDX file name</param>
	''' <param name="serviceUrl">Service URL</param>
	''' <returns></returns>
	Public Property DashboardServiceProcess() As Process
		Get
			Return m_DashboardServiceProcess
		End Get
		Set
			m_DashboardServiceProcess = Value
		End Set
	End Property
	Private m_DashboardServiceProcess As Process

	Public Function GetUrlOfHtmlPage(sydxFileName As String) As String
		If String.IsNullOrWhiteSpace(sydxFileName) OrElse String.IsNullOrWhiteSpace(ServiceUrl) Then
			Return String.Empty
		End If

		Dim dashboardProperties As New DashboardProperties() With {
			Key .SydxFileName = sydxFileName,
			Key .ServiceUrl = ServiceUrl
		}
		Return GetUrlOfHtmlPage(dashboardProperties)
	End Function

	''' <summary>
	'''     Generate Viewer HTML String
	''' </summary>
	#Region "Generate Viewer HTML String"

	Private Const BeforeHeadHtml As String = "<!-- saved from url=(0014)about:internet -->" & vbLf + "<!DOCTYPE html>" & vbLf + "<html xmlns=""http://www.w3.org/1999/xhtml"" style=""height :100% ;width:100%;"">" & vbLf + "<head>" & vbLf + "<meta charset=""utf-8"" content=""width=device-width, initial-scale=1.0"">" + "<script>window.destroyAll = function(){try{ej.widget.destroyAll($('.e-js').off());}catch(e){} $(document.body).html('-'); CollectGarbage(); }; </script>"

	''' <summary>
	'''     Get Url string for the generated HTML page
	''' </summary>

	Private Function GetUrlOfHtmlPage(dashboardProperties As DashboardProperties) As String
		Dim jsFiles = New List(Of String)() From {
			"jquery-1.10.2.min.js",
			"jquery.easing.1.3.min.js",
			"ej.dashboardViewer.all.min.js"
		}

		Dim cssFiles = New List(Of String)() From { 
			"default-theme/ej.dashboardViewer.all.min.css",
			"chromium.css"
		}

		Try
			Dim htmlString As String = GetHtmlString(GetViewer(dashboardProperties), jsFiles, cssFiles).ToString()

			'Below code block is used to copy the HTML related files from app folder since app folder doesn't have required permission to write file.
			Dim sourceFolderPath As String = AppDomain.CurrentDomain.BaseDirectory + HtmlFolder
			If Not File.Exists(sourceFolderPath) Then
				Directory.CreateDirectory(sourceFolderPath)
			End If
			Dim filePath As String = sourceFolderPath & Convert.ToString("Temp.html")
			'End

			Using fileStream As New FileStream(filePath, FileMode.Create)
				Using w As New StreamWriter(fileStream, Encoding.UTF8)
					w.Write(htmlString)
				End Using
			End Using

			Return filePath
		Catch ex As Exception
			MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
		End Try
		Return String.Empty
	End Function
	''' <summary>
	''' Get HTML JavaScript files CSS files. 
	''' </summary>
	Private Function GetHtmlString(bodyString As String, jsFiles As IEnumerable(Of String), cssFiles As IEnumerable(Of String)) As StringBuilder
		Dim headSb = New StringBuilder()
		For Each item As var In jsFiles
			headSb.Append("<script src=""scripts/" + item + """ type=""text/javascript""></script>")
		Next
		For Each item As var In cssFiles
			headSb.Append("<link href=""themes/" + item + """ rel=""stylesheet""></link>")
		Next
		Dim htmlSb = New StringBuilder()
		htmlSb.Append(BeforeHeadHtml)
		htmlSb.Append(headSb)
		htmlSb.Append("</head>" & vbLf)
		htmlSb.Append(bodyString)
		htmlSb.Append("</html>")
		Return htmlSb
	End Function
	''' <summary>
	'''     Generate the Viewer HTML String
	''' </summary>
	Private Function GetViewer(dashboardProperties As DashboardProperties) As String
		If dashboardProperties Is Nothing Then
			Return String.Empty
		End If

		Dim sydxPath = _environmentFolder & dashboardProperties.SydxFileName
		Dim viewerStr = (Convert.ToString("$('#dashboard').ejDashboardViewer({serviceUrl: '") & dashboardProperties.ServiceUrl) + "', dashboardPath: '" + sydxPath.Replace("\", "\\") + "',filterParameters:location.search.substr(1)});"
		Dim stringBuilder = New StringBuilder()
		stringBuilder.Append("<body style=""width:100%; height:100%; overflow:hidden;"">")
		stringBuilder.Append("<div id=""dashboard"" style=""width:100%; height:100%;"" />")
		stringBuilder.Append("<script type=""text/javascript"" language=""javascript"">")
		stringBuilder.Append(viewerStr)
		stringBuilder.Append("</script>")
		stringBuilder.Append("</body>")
		Return stringBuilder.ToString()
	End Function

	#End Region
End Class

''' <summary>
'''     Class for Dashboard Properties
''' </summary>
Public Class DashboardProperties
	''' <summary>
	'''     Gets or sets the SYDX File Name
	''' </summary>
	Public Property SydxFileName() As String
		Get
			Return m_SydxFileName
		End Get
		Set
			m_SydxFileName = Value
		End Set
	End Property
	Private m_SydxFileName As String

	''' <summary>
	'''     Gets or sets the ServiceUrl
	''' </summary>
	Public Property ServiceUrl() As String
		Get
			Return m_ServiceUrl
		End Get
		Set
			m_ServiceUrl = Value
		End Set
	End Property
	Private m_ServiceUrl As String
End Class

Add a class named DashboardServiceSerialization and add the below code withing the class to serialize and deserialize the DashboardService URL when Dashboard Service is running in IIS Express.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

 public class DashboardServiceSerialization
    {
        static readonly XmlSerializer previewSerializer = new XmlSerializer(typeof(DashboardServicePreviewSettings));
        public void Serialize(DashboardServicePreviewSettings settings, string path)
        {
            try
            {
                using (StreamWriter writer = new StreamWriter(path))
                {
                    previewSerializer.Serialize(writer, settings);
                }
            }
            catch (Exception)
            {

            }

        }
        public DashboardServicePreviewSettings Deserialize(string path)
        {
            DashboardServicePreviewSettings settings = new DashboardServicePreviewSettings();
            try
            {
                using (StreamReader reader = new StreamReader(path))
                {
                    settings = (DashboardServicePreviewSettings)previewSerializer.Deserialize(reader);
                }
            }
            catch (Exception)
            {

            }
            return settings;
        }
    }

    public class DashboardServicePreviewSettings
    {
        public string ServiceURL { get; set; }
        public List<Guid> DashboardServiceInstances { get; set; }
        public DashboardServicePreviewSettings()
        {
            DashboardServiceInstances = new List<Guid>();
        }
    }
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Web
Imports System.Xml.Serialization

Public Class DashboardServiceSerialization
	Shared ReadOnly previewSerializer As New XmlSerializer(GetType(DashboardServicePreviewSettings))
	Public Sub Serialize(settings As DashboardServicePreviewSettings, path As String)
		Try
			Using writer As New StreamWriter(path)
				previewSerializer.Serialize(writer, settings)
			End Using

		Catch generatedExceptionName As Exception
		End Try

	End Sub
	Public Function Deserialize(path As String) As DashboardServicePreviewSettings
		Dim settings As New DashboardServicePreviewSettings()
		Try
			Using reader As New StreamReader(path)
				settings = DirectCast(previewSerializer.Deserialize(reader), DashboardServicePreviewSettings)
			End Using

		Catch generatedExceptionName As Exception
		End Try
		Return settings
	End Function
End Class

Public Class DashboardServicePreviewSettings
	Public Property ServiceURL() As String
		Get
			Return m_ServiceURL
		End Get
		Set
			m_ServiceURL = Value
		End Set
	End Property
	Private m_ServiceURL As String
	Public Property DashboardServiceInstances() As List(Of Guid)
		Get
			Return m_DashboardServiceInstances
		End Get
		Set
			m_DashboardServiceInstances = Value
		End Set
	End Property
	Private m_DashboardServiceInstances As List(Of Guid)
	Public Sub New()
		DashboardServiceInstances = New List(Of Guid)()
	End Sub
End Class

Add a class named IISExpress and add the below code withing the class.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

    public static class IISExpress
    {
        internal static string StartIISExpress(Process iisExpressProcess, string location)
        {
            string availablePort = GetAvailablePort();
            string iisInstalledPath = GetIISExpressInstalledPath();
            try
            {
                if (!string.IsNullOrEmpty(iisInstalledPath))
                {
                    iisExpressProcess.StartInfo = new ProcessStartInfo { FileName = iisInstalledPath + "iisexpress.exe", WindowStyle = ProcessWindowStyle.Hidden, Arguments = @"/path:""" + location + "\" /port:" + availablePort, UseShellExecute = false, CreateNoWindow = true };
                    iisExpressProcess.Start();

                    return availablePort;
                }
            }
            catch (Exception e)
            {
                if (e.HResult == -2147467259)
                {
                    MessageBox.Show("IIS Express file is not found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return string.Empty;
        }

        private static string GetAvailablePort()
        {
            int startIndex = 3002, endIndex = 9000, unusedPort = 0;
            IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] tcpEndpoints = properties.GetActiveTcpListeners();
            List<int> usedPorts = tcpEndpoints.Select(p => p.Port).ToList();
            for (int port = startIndex; port < endIndex; port++)
            {
                if (!usedPorts.Contains(port))
                {
                    unusedPort = port;
                    break;
                }
            }
            return unusedPort.ToString(CultureInfo.InvariantCulture);
        }

        private static string GetIISExpressInstalledPath()
        {
            return Environment.GetEnvironmentVariable("PROGRAMFILES") + @"\IIS Express\";
        }
        internal static bool IsRunning(Process process)
        {
            try { Process.GetProcessById(process.Id); }
            catch (InvalidOperationException) { return false; }
            catch (ArgumentException) { return false; }
            return true;
        }
    }
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Globalization
Imports System.Linq
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms

Public NotInheritable Class IISExpress
	Private Sub New()
	End Sub
	Friend Shared Function StartIISExpress(iisExpressProcess As Process, location As String) As String
		Dim availablePort As String = GetAvailablePort()
		Dim iisInstalledPath As String = GetIISExpressInstalledPath()
		Try
			If Not String.IsNullOrEmpty(iisInstalledPath) Then
				iisExpressProcess.StartInfo = New ProcessStartInfo() With {
					Key .FileName = iisInstalledPath & Convert.ToString("iisexpress.exe"),
					Key .WindowStyle = ProcessWindowStyle.Hidden,
					Key .Arguments = Convert.ToString((Convert.ToString("/path:""") & location) + """ /port:") & availablePort,
					Key .UseShellExecute = False,
					Key .CreateNoWindow = True
				}
				iisExpressProcess.Start()

				Return availablePort
			End If
		Catch e As Exception
			If e.HResult = -2147467259 Then
				MessageBox.Show("IIS Express file is not found", "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
			Else
				MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
			End If
		End Try
		Return String.Empty
	End Function

	Private Shared Function GetAvailablePort() As String
		Dim startIndex As Integer = 3002, endIndex As Integer = 9000, unusedPort As Integer = 0
		Dim properties As IPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties()
		Dim tcpEndpoints As IPEndPoint() = properties.GetActiveTcpListeners()
		Dim usedPorts As List(Of Integer) = tcpEndpoints.[Select](Function(p) p.Port).ToList()
		For port As Integer = startIndex To endIndex - 1
			If Not usedPorts.Contains(port) Then
				unusedPort = port
				Exit For
			End If
		Next
		Return unusedPort.ToString(CultureInfo.InvariantCulture)
	End Function

	Private Shared Function GetIISExpressInstalledPath() As String
		Return Environment.GetEnvironmentVariable("PROGRAMFILES") + "\IIS Express\"
	End Function
	Friend Shared Function IsRunning(process__1 As Process) As Boolean
		Try
			Process.GetProcessById(process__1.Id)
		Catch generatedExceptionName As InvalidOperationException
			Return False
		Catch generatedExceptionName As ArgumentException
			Return False
		End Try
		Return True
	End Function
End Class

Finally set the serviceDirectory property value in Form1.cs file. service which is shipped along with the SDK build. you can find the service directory in below location in your machine.

%localappdata%\Syncfusion\Dashboard Platform SDK\Service

for example,replace the serviceDirectory property value as below in your project’s Form1.cs file,

private string serviceDirectory = "%localappdata%\Syncfusion\Dashboard Platform SDK\Service";
Private serviceDirectory As String = "%localappdata%\Syncfusion\Dashboard Platform SDK\Service"

Adding URL to Forms

Include the following code under `Form1` class in `Form1.Designer.cs` file to render the generated URL in Windows Form.
private void InitializeComponent()
    {
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
        this.panel1 = new System.Windows.Forms.Panel();

        this.WindowBrowser = new CefSharp.WinForms.ChromiumWebBrowser(Url);
        this.panel1.SuspendLayout();
        this.SuspendLayout();
        // 
        // panel1
        // 
        this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
        | System.Windows.Forms.AnchorStyles.Left)
        | System.Windows.Forms.AnchorStyles.Right)));
        this.panel1.BackColor = System.Drawing.Color.White;
        this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
        this.panel1.Controls.Add(this.WindowBrowser);
        this.panel1.Location = new System.Drawing.Point(4, 12);
        this.panel1.Name = "panel1";
        this.panel1.Padding = new System.Windows.Forms.Padding(5);
        this.panel1.Size = new System.Drawing.Size(966, 468);
        this.panel1.TabIndex = 0;
        // 
        // WindowBrowser
        // 
        this.WindowBrowser.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
        | System.Windows.Forms.AnchorStyles.Left)
        | System.Windows.Forms.AnchorStyles.Right)));
        this.WindowBrowser.Location = new System.Drawing.Point(8, 8);
        this.WindowBrowser.MinimumSize = new System.Drawing.Size(20, 20);
        this.WindowBrowser.Name = "WindowBrowser";
        this.WindowBrowser.Size = new System.Drawing.Size(948, 451);
        this.WindowBrowser.TabIndex = 0;

        // 
        // DashboardWindow
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(974, 484);
        this.Controls.Add(this.panel1);
        this.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(96)))), ((int)(((byte)(96)))), ((int)(((byte)(96)))));
        this.Margin = new System.Windows.Forms.Padding(4);
        this.Name = "Form1";
        this.Text = "Dashboard Preview Window";
        this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        this.panel1.ResumeLayout(false);
        this.ResumeLayout(false);

    }

    private System.Windows.Forms.Panel panel1;
    private CefSharp.WinForms.ChromiumWebBrowser WindowBrowser;
Private Sub InitializeComponent()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form1))
        Me.panel1 = New System.Windows.Forms.Panel()
        Me.WindowBrowser = New CefSharp.WinForms.ChromiumWebBrowser(Url)
        Me.panel1.SuspendLayout()
        Me.SuspendLayout()
        Me.panel1.Anchor = (CType(((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right)), System.Windows.Forms.AnchorStyles))
        Me.panel1.BackColor = System.Drawing.Color.White
        Me.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.panel1.Controls.Add(Me.WindowBrowser)
        Me.panel1.Location = New System.Drawing.Point(4, 12)
        Me.panel1.Name = "panel1"
        Me.panel1.Padding = New System.Windows.Forms.Padding(5)
        Me.panel1.Size = New System.Drawing.Size(966, 468)
        Me.panel1.TabIndex = 0
        Me.WindowBrowser.Anchor = (CType(((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right)), System.Windows.Forms.AnchorStyles))
        Me.WindowBrowser.Location = New System.Drawing.Point(8, 8)
        Me.WindowBrowser.MinimumSize = New System.Drawing.Size(20, 20)
        Me.WindowBrowser.Name = "WindowBrowser"
        Me.WindowBrowser.Size = New System.Drawing.Size(948, 451)
        Me.WindowBrowser.TabIndex = 0
        Me.AutoScaleDimensions = New System.Drawing.SizeF(9F, 18F)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(974, 484)
        Me.Controls.Add(Me.panel1)
        Me.Font = New System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (CByte((0))))
        Me.ForeColor = System.Drawing.Color.FromArgb((CInt(((CByte((96)))))), (CInt(((CByte((96)))))), (CInt(((CByte((96)))))))
        Me.Margin = New System.Windows.Forms.Padding(4)
        Me.Name = "Form1"
        Me.Text = "Dashboard Preview Window"
        Me.WindowState = System.Windows.Forms.FormWindowState.Maximized
        Me.panel1.ResumeLayout(False)
        Me.ResumeLayout(False)
    End Sub

    Private panel1 As System.Windows.Forms.Panel
    Private WindowBrowser As CefSharp.WinForms.ChromiumWebBrowser

Run the application to view the dashboard.

This image represents Dashboard in Windows Forms sample.