Silverlight – Browser Integration


Silverlight – Browser Integration


”;


In this chapter, we are going to see how a Silverlight application can work in conjunction with a web page using the browser integration support.

We can explore Silverlight integration with the browser in the following two ways −

  • JavaScript code running in the browser can access features within your Silverlight application.

  • Silverlight has the ability to provide JavaScript wrappers for objects. Your .NET code running inside the Silverlight plug-in has access to the HTML DOM and other browser scripting features because of Silverlight .NET wrappers for JavaScript objects.

We will see how a browser based software application can store information persistently on the client.

Silverlight and HTML

As far as the world of HTML is concerned, Silverlight content is just a single element. This is true for layout. The whole of the Silverlight plug-in and all its content looks like just a single object element.

You must keep in mind that −

  • Silverlight was not a replacement for HTML, it was designed to complement it. Therefore, the ability to access just another element in the DOM is important.

  • It enables you to use Silverlight where appropriate.

  • On a page, that mainly uses HTML, Silverlight integration with the world of the browser goes beyond merely existing as a DOM element, subject to normal HTML Layout.

Accessing DOM

The Silverlight content must able to participate fully in a web page. Therfore, it should be able to access the HTML DOM. Silverlight provides the bridge objects that wrap browser script objects as Dot Net objects, the Script object class in the system. The browser namespace provides methods that let you read and write properties and devote functions on the browser script object.

You need a way to get hold of a Script object in the first place. Silverlight provides an HTML page class that gives you access to various pages of the features such as the Script objects.

Let us have a look at a simple example in which we have a simple script that creates an object with a few attributes. Some of them are just values and a couple of them are functions.

<script type = "text/javascript">  
   myJsObject = { 
      answer: 42, 
      message: "Hello, world", 
      modifyHeading: function(title) 
         { document.getElementById(''heading'').innerHTML = title; }, 
      performReallyComplexCalculation: function(x, y) { return x + y; } 
   }; 
     
</script>

Given below is the XAML code in which a button is added.

<UserControl x:Class = "DomAccess.Page" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"  
   Width = "400" Height = "300"> 
   
   <Grid x:Name = "LayoutRoot" Background = "White"> 
      <Button x:Name = "useDomButton" Content = "Use DOM" Width = "75" Height = "30" 
         Click = "useDomButton_Click" /> 
   </Grid>
	
</UserControl>

Here is the button click implementation in which a script is called which is created in HTML file.

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;
using System.Windows.Browser; 

using System.Diagnostics; 
 
namespace DomAccess { 

   public partial class Page : UserControl { 
	
      public Page() { 
         InitializeComponent(); 
      } 
   
      private void useDomButton_Click(object sender, RoutedEventArgs e) { 
         ScriptObject myJsObject = HtmlPage.Window.GetProperty("myJsObject") as ScriptObject;  
         string[] propertyNames = { "answer", "message", "modifyHeading", 
            "performReallyComplexCalculation" }; 
				
         foreach (string propertyName in propertyNames) { 
            object value = myJsObject.GetProperty(propertyName); 
            Debug.WriteLine("{0}: {1} ({2})", propertyName, value, value.GetType()); 
         }
			
         object result = myJsObject.Invoke("performReallyComplexCalculation", 11, 31);  
         HtmlElement h1 = HtmlPage.Document.GetElementById("heading"); 
         h1.SetProperty("innerHTML", "Text from C# (without JavaScript''s help)"); 
         h1.SetStyleAttribute("height", "200px"); 
      } 
   } 
} 

Given below is the complete HTML file.

<!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" > 
   <!-- saved from url = (0014)about:internet --> 
	
   <head> 
      <title>DomAccess</title>  
		
      <script type = "text/javascript">  
		
         myJsObject = { 
            answer: 42, 
            message: "Hello, world", 
            modifyHeading: function(title) { 
               document.getElementById(''heading'').innerHTML = title; }, 
            performReallyComplexCalculation: function(x, y) { return x + y; } 
         }; 
     
      </script> 
     
      <style type = "text/css"> 
		
         html, body { 
            height: 100%; 
            overflow: auto; 
         } 
			
         body { 
            padding: 0; 
            margin: 0; 
         } 
			
         #silverlightControlHost { 
            height: 100%; 
         }
			
      </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; 
             
            var errMsg = "Unhandled Error in Silverlight 2 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> 
	
      <!-- Runtime errors from Silverlight will be displayed here. 
         This will contain debugging information and should be removed or hidden when 
         debugging is completed -->
			
      <div id = ''errorLocation'' style = "font-size: small;color: Gray;"></div> 
		
      <h1 id = ''heading''></h1>
		
      <div id = "silverlightControlHost"> 
		
         <object data = "data:application/x-silverlight-2," 
            type = "application/x-silverlight-2" width = "100%" height = "100%"> 
				
            <param name = "source" value = "ClientBin/DomAccess.xap"/> 
            <param name = "onerror" value = "onSilverlightError" /> 
            <param name = "background" value = "white" /> 
            <param name = "minRuntimeVersion" value = "2.0.30923.0" /> 
            <param name = "autoUpgrade" value = "true" /> 
				
            <a href = "http://go.microsoft.com/fwlink/?LinkID=124807" 
               style = "text-decoration: none;"> 
               <img src = "http://go.microsoft.com/fwlink/?LinkId=108181" 
               alt = "Get Microsoft Silverlight" style = "border-style: none"/> 
            </a> 
				
         </object>
			
         <iframe style = ''visibility:hidden;height:0;width:0;border:0px''></iframe> 
			
      </div> 
		
   </body> 
	
</html> 

When the above code is compiled and executed, you will see all the values in the output window, which are fetched from the HTML file.

Accessing DOM

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *