Getting Started with ASP.NET Web Forms Application

This section describes how to create an ASP.NET Web Forms application with embedded dashboard viewer.

Project Creation

Create a new ASP.NET Web application project using Microsoft Visual Studio IDE 2012 or higher. Refer here for more details.

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) into the project.

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.

Asp build action

Adding Dashboard Viewer Assembly References

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

Dll reference

selecting the below mentioned assembly in dialog shown, which allows you to use any of the Syncfusion Dashboard components within it.

⦁ Syncfusion.EJ.DashboardViewer

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

%localappdata%\Syncfusion\Dashboard Platform SDK\Getting Started Samples\Common\Precompiled Assemblies

Dll reference

Registering Syncfusion Assemblies within the Web.config

In your application’s web.config file, add the below assembly information within the tag.

  • html
  • <system.web>
        <compilation debug="true" targetFramework="4.5" >
          <assemblies>
            <add assembly="Syncfusion.Dashboard.EJ"/>
            <add assembly="Syncfusion.Dashboard.EJ.Web"/>
            <add assembly="Syncfusion.EJ.DashboardViewer"/>
          </assemblies>
        </compilation>
    </system.web>

    Adding Dashboard Viewer Resources

    Select any one of the way to add the resources for Dashboard Viewer:

    ⦁ External Resources

    ⦁ Embedded Resources

    External Resources:

    Add the below script references in the Site.Master file.

  • aspx-cs
  • <%@ Master Language="C#" %>
    
    <!DOCTYPE html>
    <html lang="en">
    <head id="Head1" runat="server">
        <meta charset="utf-8" />
        <title>Getting Started</title>
        <link href="themes/default-theme/ej.dashboardViewer.all.min.css" rel="stylesheet" />
        <script src='<%= Page.ResolveClientUrl("scripts/jquery-1.10.2.min.js")%>' type="text/javascript"></script>
        <script src='<%= Page.ResolveClientUrl("scripts/jquery.easing.1.3.min.js")%>' type="text/javascript"></script>
        <script src='<%= Page.ResolveClientUrl("scripts/ej.dashboardViewer.all.min.js")%>' type="text/javascript"></script>
    	<script src='<%= Page.ResolveClientUrl("scripts/ej.dashboard.webform.min.js")%>' type="text/javascript"></script>
    </head>
    <body style="height:100%;width:100%;">
       <form id="Form1" runat="server" style="height:100%;width:100%;">
       <asp:ScriptManager runat="server" ID="scriptmgr"  ></asp:ScriptManager>
       <div id="body" style="height:100%;width:100%;">
       <asp:ContentPlaceHolder runat="server" ID="MainContent" />
       </div>
       </form>
    </body>
    </html>

    Embedded Resources:

    Dashboard Viewer will load the resources from its assembly. Refer Embedded Resources for more detail.

    Control Initialization

    To create the Dashboard Viewer instance, use the below code snippet inside Default.aspx page.

  • aspx-cs
  • <%@ Register Assembly="Syncfusion.EJ.DashboardViewer" Namespace="Syncfusion.Dashboard.JavaScript.Web" TagPrefix="ej" %> <asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent"> 
        <ej:DashboardViewer ID="dashboard" runat="server" Size-Height="100%" Size-Width="100%">
        </ej:DashboardViewer>
    </asp:Content>

    Binding Dashboard Service and Dashboard File

    To initiate the dashboard service instance you can follow anyone of the below methods

    1. Hosting Dashboard Service in IIS

    2. Hosting Dashboard Service in IIS Express

    3. Hosting Dashboard Service as Windows Service Background Process

    IMPORTANT

    Hosting dashboard service at IIS is recommended for the production environment for object management and other memory management features.

    Create a global application class file named Global.asax.

    Define the properties with public access level for handling dashboard path and service URL through the following code definitions under Global class in Global.asax file.

    public static string DashboardPath;
       public static string ServiceUrl;
    Public Shared DashboardPath As String
       Public Shared ServiceUrl As String

    Set the dashboard path and service URL using the following code under Application_Start method in Global.asax file.

    DashboardPath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "\\\\") + "bin\\\\WorldWideCarSalesDashboard.sydx"; // Or use the remote (online) Dashboard Path. For example, https://dashboardsdk.syncfusion.com//Dashboards//WorldWideCarSalesDashboard.sydx
          ServiceUrl = "http://localhost:3002/DashboardService.svc"; // Or use the remote (online) Dashboard Service. For example, https://dashboardsdk.syncfusion.com/DashboardService/DashboardService.svc
    DashboardPath = AppDomain.CurrentDomain.BaseDirectory.Replace("\", "\\") & "bin\\WorldWideCarSalesDashboard.sydx" '// Or use the remote (online) Dashboard Path. For example, https://dashboardsdk.syncfusion.com//Dashboards//WorldWideCarSalesDashboard.sydx
    	  ServiceUrl = "http://localhost:3002/DashboardService.svc" '// Or use the remote (online) Dashboard Service. For example, https://dashboardsdk.syncfusion.com/DashboardService/DashboardService.svc

    NOTE

    Make sure the given dashboard path should be accessible with the given Dashboard Service URL.
    Provided online Dashboard Service URL above, only for demo purpose.

    Build and run the application to view the dashboard.

    ASP output

    How to Use the Windows Service as Dashboard Service

    To use the window service as a background process refer,
    Run Windows Dashboard Service as a background process

    Refer the below code snippet to configure the Dashboard Viewer with Windows Dashboard Service:

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

    using System;
        using System.IO;
        using System.Net;
        using Microsoft.Win32;
        public class DashboardWindowsServiceInfo
        {
            private readonly string _environmentFolder = AppDomain.CurrentDomain.BaseDirectory;
            string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            public string ServiceUrl;
            public string ErrorMessage;
            public DashboardWindowsServiceInfo()
            {
                #region Pick Windows Dashboard Service Url
                ServiceUrl = GetWindowsServiceUrl();
                #endregion
                #region Pick IISExpress or IIS  Dashboard Service Url if Windows Dashboard Service is not running
                if (ValidateDashboardService(ServiceUrl))
                {
                    DashboardServiceSerialization serializer = new DashboardServiceSerialization();
                    DashboardServicePreviewSettings settings = new DashboardServicePreviewSettings();
                    string dashboardServiceSettingPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Syncfusion\Dashboard Platform SDK\" + version + @"\DashboardServiceSetting.xml";
                    if (File.Exists(dashboardServiceSettingPath))
                    {
                        settings = serializer.Deserialize(dashboardServiceSettingPath);
                        if (!ValidateDashboardService(settings.ServiceURL))
                            ServiceUrl = settings.ServiceURL;
                        else
                        {
                            ServiceUrl = string.Empty;
                            ErrorMessage; = "Dashboard Service is not running. Run DashboardServiceInstaller.exe file to start Dashboard Service in IIS Express";
                        }
                    }
                    else
                    {
                        ErrorMessage; = "Dashboard Service is not running. Run DashboardServiceInstaller.exe file to start Dashboard Service in IIS Express";
                        ServiceUrl = string.Empty;
                    }
                }
                #endregion
            }
    		
            /// <summary>
            /// Used to pick the Windows Dashboard Service URL 
            /// </summary>
            /// <returns>ServiceURL of Windows Dashboard Service</returns>
            private string GetWindowsServiceUrl()
            {
                string url = string.Empty;
                try
                {
                    RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\SyncfusionDashboard\Syncfusion Dashboard Service");
                    if (key == null)
                        key = Registry.LocalMachine.OpenSubKey(@"Software\Wow6432Node\SyncfusionDashboard\Syncfusion Dashboard Service");
                    if (key != null)
                    {
                        url = (string)key.GetValue("ServiceURL");
                        key.Close();
                    }
                }
                catch (Exception)
                {
    
                }
                return url;
            }
    
            /// <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;
            }
        }
    Imports System
         Imports System.IO
         Imports System.Net
         Imports Microsoft.Win32
         Public Class DashboardWindowsServiceInfo
    		Private ReadOnly _environmentFolder As String = AppDomain.CurrentDomain.BaseDirectory
    		Private version As String = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
    		Public ServiceUrl As String
    		Public ErrorMessage; As String
    		
    		Public Sub New()
    			'Pick Dashboard Windows Service URL
    			ServiceUrl = GetWindowsServiceUrl()
    			'Pick IISExpress or IIS  Dashboard Service Url if Windows Dashboard Service is not running
    			If ValidateDashboardService(ServiceUrl) Then
    				Dim serializer As New DashboardServiceSerialization()
    				Dim settings As New DashboardServicePreviewSettings()
    				Dim dashboardServiceSettingPath As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Syncfusion\Dashboard Platform SDK\" & version & "\DashboardServiceSetting.xml"
    				If File.Exists(dashboardServiceSettingPath) Then
    					settings = serializer.Deserialize(dashboardServiceSettingPath)
    					If Not ValidateDashboardService(settings.ServiceURL) Then
    						ServiceUrl = settings.ServiceURL
    					Else
    						ServiceUrl = String.Empty
    						ErrorMessage; = "Dashboard Service is not running. Run DashboardServiceInstaller.exe file to start Dashboard Service in IIS Express"
    					End If
    				Else
    					ErrorMessage; = "Dashboard Service is not running. Run DashboardServiceInstaller.exe file to start Dashboard Service in IIS Express"
    					ServiceUrl = String.Empty
    				End If
    			End If
    		End Sub
    		
    		''' <summary>
    		''' Used to pick the Windows Dashboard Service URL 
    		''' </summary>
    		''' <returns>ServiceURL of Windows Dashboard Service</returns>
    		Private Function GetWindowsServiceUrl() As String
    			Dim url As String = String.Empty
    			Try
    				Dim key As RegistryKey = Registry.LocalMachine.OpenSubKey("Software\SyncfusionDashboard\Syncfusion Dashboard Service")
    				If key Is Nothing Then
    					key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\SyncfusionDashboard\Syncfusion Dashboard Service")
    				End If
    				If key IsNot Nothing Then
    					url = CStr(key.GetValue("ServiceURL"))
    					key.Close()
    				End If
    			Catch e1 As Exception
    
    			End Try
    			Return url
                    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 or not.</returns>
    		Private Shared Function ValidateDashboardService(ByVal 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 = "http://" & dashboardServiceUrl & "/IsServiceExists"
    				Else
    					dashboardServiceUrl = dashboardServiceUrl & "/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
        End Class

    Add a class named DashboardServicePreviewSettings and add the below code within the class.

    using System;
        using System.Collections.Generic;
        public class DashboardServicePreviewSettings
        {
            public string ServiceURL { get; set; }
            public List<Guid> DashboardServiceInstances { get; set; }
            public DashboardServicePreviewSettings()
            {
                DashboardServiceInstances = new List<Guid>();
            }
       }
    Imports System
       Imports System.Collections.Generic
       Public Class DashboardServicePreviewSettings
    		Public Property ServiceURL() As String
    		Public Property DashboardServiceInstances() As List(Of Guid)
    		Public Sub New()
    			DashboardServiceInstances = New List(Of Guid)()
    		End Sub
       End Class

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

    using System;
        using System.IO;
        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;
            }
        }
    Imports System
        Imports System.IO
        Imports System.Xml.Serialization
        Public Class DashboardServiceSerialization
    		Private Shared ReadOnly previewSerializer As New XmlSerializer(GetType(DashboardServicePreviewSettings))
    		Public Sub Serialize(ByVal settings As DashboardServicePreviewSettings, ByVal path As String)
    			Try
    				Using writer As New StreamWriter(path)
    					previewSerializer.Serialize(writer, settings)
    				End Using
    			Catch e1 As Exception
    
    			End Try
    
    		End Sub
    		Public Function Deserialize(ByVal path As String) As DashboardServicePreviewSettings
    			Dim settings As New DashboardServicePreviewSettings()
    			Try
    				Using reader As New StreamReader(path)
    					settings = CType(previewSerializer.Deserialize(reader), DashboardServicePreviewSettings)
    				End Using
    			Catch e1 As Exception
    
    			End Try
    			Return settings
    		End Function
        End Class