- Project Creation
- Adding files and references
- Adding Dashboard Viewer Assembly References
- Control Initialization
Contact Support
Getting Started with WPF Application
This section describes how to create a WPF application with embedded dashboard viewer.
Project Creation
Create a new WPF 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.
%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 image.
`%localappdata%\Syncfusion\Dashboard Platform SDK\Getting Started Samples\Common\Dashboards`
Include the below mentioned files into project from the SDK build installed location as shown in figure below.
⦁ 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
for all added files as shown in the following image.
Adding Dashboard Viewer Assembly References
Right-click the project and add the following assembly references through choosing Add > Reference...
as shown below,
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.Wpf.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
Control Initialization
Add the below code under constructor method of App.xaml
class file so it will execute before initializing the ChromiumWebBrowser control.
var settings = new CefSettings();
settings.PackLoadingDisabled = true;
settings.LogSeverity = LogSeverity.Disable;
if (!Cef.Initialize(settings))
{
if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
{
Environment.Exit(0);
}
else
{
return;
}
}
Dim settings = New CefSettings()
settings.PackLoadingDisabled = True
settings.LogSeverity = LogSeverity.Disable
If Not CefSharp.Cef.Initialize(settings) Then
If Environment.GetCommandLineArgs().Contains("--type=renderer") Then
Environment.Exit(0)
Else
Return
End If
End If
Add the below code under the DashboardWindow.xaml class file.
using CefSharp;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.ComponentModel;
/// <summary>
/// Interaction logic for DashboardWindow.xaml
/// </summary>
public partial class DashboardWindow : Window
{
private string _sydxFileName = "WorldWideCarSalesDashboard.sydx";
private string url = string.Empty;
public string SydxFileName
{
get { return _sydxFileName; }
set { _sydxFileName = value; }
}
public class DownloadHandler : IDownloadHandler
{
public bool OnBeforeDownload(DownloadItem downloadItem, out string downloadPath, out bool showDialog)
{
downloadPath = downloadItem.SuggestedFileName;
showDialog = true;
return true;
}
public bool OnDownloadUpdated(DownloadItem downloadItem)
{
return false;
}
}
internal static Process dashboardServiceProcess = new Process();
public string Url { get; set; }
// Get the service from Common Folder
private string serviceDirectory = Path.GetFullPath(Path.Combine(@"..\..\..\..\..\")) + "Service";
/// <summary>
/// Initializing Dashboard on window and closing IIS Express while closing dashboard window.
/// </summary>
public DashboardWindow()
{
this.Closing += DashboardWindow_closing;
InitializeComponent();
this.Loaded += DashboardWindow_Loaded;
WindowBrowser.DownloadHandler = new DownloadHandler();
Navigate();
}
/// <summary>
/// Close IIS Express Process while closing Window.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DashboardWindow_closing(object sender, CancelEventArgs e)
{
DashboardWindowsServiceInfo.ClearIISExpressProcess(dashboardServiceProcess);
}
void DashboardWindow_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(url))
this.Close();
}
private void Navigate()
{
DashboardWindowsServiceInfo dashboardViewer = new DashboardWindowsServiceInfo(dashboardServiceProcess, serviceDirectory);
url = dashboardViewer.GetUrlOfHtmlPage(SydxFileName);
if (!string.IsNullOrWhiteSpace(url))
WindowBrowser.Address = url;
}
/// <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.Diagnostics
Imports System.IO
Imports System.Windows
Imports System.ComponentModel
''' <summary>
''' Interaction logic for DashboardWindow.xaml
''' </summary>
Public Partial Class DashboardWindow
Inherits Window
Private _sydxFileName As String = "WorldWideCarSalesDashboard.sydx"
Private m_url As String = String.Empty
Public Property SydxFileName() As String
Get
Return _sydxFileName
End Get
Set
_sydxFileName = value
End Set
End Property
Public Class DownloadHandler
Implements IDownloadHandler
Public Function OnBeforeDownload(downloadItem As DownloadItem, ByRef downloadPath As String, ByRef showDialog As Boolean) As Boolean
downloadPath = downloadItem.SuggestedFileName
showDialog = True
Return True
End Function
Public Function OnDownloadUpdated(downloadItem As DownloadItem) As Boolean
Return False
End Function
End Class
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
' Get the service from Common Folder
Private serviceDirectory As String = Path.GetFullPath(Path.Combine("..\..\..\..\")) + "Common\Service"
''' <summary>
''' Initializing Dashboard on window and closing IIS Express while closing dashboard window.
''' </summary>
Public Sub New()
AddHandler Me.Closing, AddressOf DashboardWindow_closing
InitializeComponent()
AddHandler Me.Loaded, AddressOf DashboardWindow_Loaded
WindowBrowser.DownloadHandler = New DownloadHandler()
Navigate()
End Sub
''' <summary>
''' Close IIS Express Process while closing Window.
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub DashboardWindow_closing(sender As Object, e As CancelEventArgs)
DashboardWindowsServiceInfo.ClearIISExpressProcess(dashboardServiceProcess)
End Sub
Private Sub DashboardWindow_Loaded(sender As Object, e As System.Windows.RoutedEventArgs)
If String.IsNullOrWhiteSpace(m_url) Then
Me.Close()
End If
End Sub
Private Sub Navigate()
Dim dashboardViewer As New DashboardWindowsServiceInfo(dashboardServiceProcess, serviceDirectory)
m_url = dashboardViewer.GetUrlOfHtmlPage(SydxFileName)
If Not String.IsNullOrWhiteSpace(m_url) Then
WindowBrowser.Address = m_url
End If
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.Diagnostics;
using System.Net.NetworkInformation;
using System.Net;
using System.Linq;
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>
/// <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;
}
public Process DashboardServiceProcess { get; set; }
/// <summary>
/// Get Url string for the generated HTML page
/// </summary>
/// <param name="sydxFileName">SYDX file name</param>
/// <returns></returns>
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", MessageBoxButton.OK, MessageBoxImage.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 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.Diagnostics
Imports System.Net.NetworkInformation
Imports System.Net
Imports System.Linq
Imports System.Globalization
''' <summary>
''' Class for Dashboard Viewer
''' </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>
''' <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
Public Property DashboardServiceProcess() As Process
Get
Return m_DashboardServiceProcess
End Get
Set
m_DashboardServiceProcess = Value
End Set
End Property
Private m_DashboardServiceProcess As Process
''' <summary>
''' Get Url string for the generated HTML page
''' </summary>
''' <param name="sydxFileName">SYDX file name</param>
''' <returns></returns>
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", MessageBoxButton.OK, MessageBoxImage.[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 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
Create a class named DashboardServiceSerialization
and add the below code within the class.
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;
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", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.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
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", MessageBoxButton.OK, MessageBoxImage.[Error])
Else
MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.[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 DashboardWindow.xaml 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 DashboardWindow.xaml file,
private string serviceDirectory = "%localappdata%\Syncfusion\Dashboard Platform SDK\Service";
Private serviceDirectory As String = "%localappdata%\Syncfusion\Dashboard Platform SDK\Service"
Build the application and run it to view the dashboard.