Silverlight Initialization Parameters PRO

We can easily pass initialization parameters from the HTML code that invokes the Silverlight application to the Silverlight application itself. The parameters should be placed as key value pairs, while the keys are their names and the values are the values of each one of them, as a string which is the value of a parameter placed as a child element of the Silverlight application object element. The name of that parameter should be initParams.

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>SilverlightApplication19</title>
    <style type="text/css">
    html, body {
	    height: 100%;
	    overflow: auto;
    }
    body {
	    padding: 0;
	    margin: 0;
    }
    #silverlightControlHost {
	    height: 100%;
	    text-align:center;
    }
    </style>
    <script type="text/javascript" src="Silverlight.js"></script>
    <script type="text/javascript">
        function onSilverlightError(sender, args) {
            var appSource = "";
            if (sender != null && sender != 0) {
              appSource = sender.getHost().Source;
            }

            var errorType = args.ErrorType;
            var iErrorCode = args.ErrorCode;

            if (errorType == "ImageError" || errorType == "MediaError") {
              return;
            }

            var errMsg = "Unhandled Error in Silverlight Application " +  appSource + "\n" ;

            errMsg += "Code: "+ iErrorCode + "    \n";
            errMsg += "Category: " + errorType + "       \n";
            errMsg += "Message: " + args.ErrorMessage + "     \n";

            if (errorType == "ParserError") {
                errMsg += "File: " + args.xamlFile + "     \n";
                errMsg += "Line: " + args.lineNumber + "     \n";
                errMsg += "Position: " + args.charPosition + "     \n";
            }
            else if (errorType == "RuntimeError") {           
                if (args.lineNumber != 0) {
                    errMsg += "Line: " + args.lineNumber + "     \n";
                    errMsg += "Position: " +  args.charPosition + "     \n";
                }
                errMsg += "MethodName: " + args.methodName + "     \n";
            }

            throw new Error(errMsg);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server" style="height:100%">
    <div id="silverlightControlHost">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
		  <param name="source" value="ClientBin/SilverlightApplication19.xap"/>
		  <param name="onError" value="onSilverlightError" />
		  <param name="background" value="white" />
		  <param name="minRuntimeVersion" value="4.0.50826.0" />
		  <param name="autoUpgrade" value="true" />
          <param name="initParams" value="lang=hebrew,country=israel" />
		  <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" 
                style="text-decoration:none">
 			    <img src="http://go.microsoft.com/fwlink/?LinkId=161376" 
                alt="Get Microsoft Silverlight" style="border-style:none"/>
		  </a>
	    </object>
        <iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px">
        </iframe>
    </div>
    </form>
</body>
</html>

In our Silverlight application we can access the value of the initParams parameter from within the scope of the App class definition.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication19
{
    public partial class App : Application
    {
        public string Language { get; set; }
        public string Country { get; set; }
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;
            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new MainPage();
            if (e.InitParams.ContainsKey("country"))
            {
                this.Country = e.InitParams["country"];
            }
            else
            {
                this.Country = "Unknown Country";
            }
            if (e.InitParams.ContainsKey("lang"))
            {
                this.Language = e.InitParams["lang"];
            }
            else
            {
                this.Language = "Unknown Language";
            }            
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(
                    delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");
                System.Windows.Browser.HtmlPage.Window.Eval(
                    "throw new Error(\"Unhandled Error in Silverlight Application " + 
                    errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}

Once we took care of placing the values of the initialization parameters within properties accessible from within our code we can now access from every page in our Silverlight application. Referring Application.Current returns the reference for the App object currently running.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication19
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Button1Click(object sender, RoutedEventArgs e)
        {
            CountryTextBox.Text = ((App)Application.Current).Country;
            LangTextBox.Text = ((App)Application.Current).Language;
        }
    }
}

The following video clip shows how does it work.

Share:

The Visitor Design Pattern

The Visitor Design Pattern

The visitor design pattern allows us to add operations to objects that already exist without modifying their classes and without extending them.

What are Anti Patterns?

Anti Patterns

Unlike design patterns, anti patterns just seem to be a solution. However, they are not a solution and they cause additional costs.

Virtual Threads in Java Professional Seminar

Virtual Threads in Java

The use of virtual threads can assist us with improving the performance of our code. Learn how to use virtual threads effectively.

NoSQL Databases Courses, Seminars, Consulting, and Development

MongoDB Design Patterns Meetup

The use of MongoDB involves with various cases in which we can overcome performance issues by implementing specific design patterns.

image of woman and database

Record Classes in Java

Learn how to define record classes in Java, and when to use record classes in your code. Stay up to date with the new Java features.

Accessibility | Career | Conferences | Design Patterns | JavaScript | Meetups | PHP | Podcasts | Python | Self Learning

Teaching Methodologies | Fullstack | C++ | C# | CSS | Node.js | Angular | Java | Go | Android | Kotlin | Swift | Academy

Front End Development | Scala | Architectures | Cloud | Big Data | Internet of Things | Kids Learn Programming

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Skip to content Update cookies preferences