English 中文(简体)
Silverlight - Browser Integration
  • 时间:2024-11-03

Silverpght - Browser Integration


Previous Page Next Page  

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

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

    JavaScript code running in the browser can access features within your Silverpght apppcation.

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

We will see how a browser based software apppcation can store information persistently on the cpent.

Silverpght and HTML

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

You must keep in mind that −

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

    It enables you to use Silverpght where appropriate.

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

Accessing DOM

The Silverpght content must able to participate fully in a web page. Therfore, it should be able to access the HTML DOM. Silverpght 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. Silverpght 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" 
         Cpck = "useDomButton_Cpck" /> 
   </Grid>
	
</UserControl>

Here is the button cpck 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 { 

   pubpc partial class Page : UserControl { 
	
      pubpc Page() { 
         InitiapzeComponent(); 
      } 
   
      private void useDomButton_Cpck(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; 
         } 
			
         #silverpghtControlHost { 
            height: 100%; 
         }
			
      </style>
		
      <script type = "text/javascript" src = "Silverpght.js"></script> 
		
      <script type = "text/javascript"> 
		
         function onSilverpghtError(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 Silverpght 2 Apppcation " +  
               appSource + "
" ; 
					
            errMsg += "Code: "+ iErrorCode + "    
"; 
            errMsg += "Category: " + errorType + "       
"; 
            errMsg += "Message: " + args.ErrorMessage + "     
";
				
            if (errorType == "ParserError") { 
               errMsg += "File: " + args.xamlFile + "     
"; 
               errMsg += "Line: " + args.pneNumber + "     
"; 
               errMsg += "Position: " + args.charPosition + "     
"; 
            } else if (errorType == "RuntimeError") {  
				
               if (args.pneNumber != 0) { 
                  errMsg += "Line: " + args.pneNumber + "     
"; 
                  errMsg += "Position: " +  args.charPosition + "     
"; 
               } 
					
               errMsg += "MethodName: " + args.methodName + "     
"; 
            }
				
            throw new Error(errMsg); 
         }
		  
      </script> 
		
   </head>  
	
   <body> 
	
      <!-- Runtime errors from Silverpght will be displayed here. 
         This will contain debugging information and should be removed or hidden when 
         debugging is completed -->
			
      <span id =  errorLocation  style = "font-size: small;color: Gray;"></span> 
		
      <h1 id =  heading ></h1>
		
      <span id = "silverpghtControlHost"> 
		
         <object data = "data:apppcation/x-silverpght-2," 
            type = "apppcation/x-silverpght-2" width = "100%" height = "100%"> 
				
            <param name = "source" value = "CpentBin/DomAccess.xap"/> 
            <param name = "onerror" value = "onSilverpghtError" /> 
            <param name = "background" value = "white" /> 
            <param name = "minRuntimeVersion" value = "2.0.30923.0" /> 
            <param name = "autoUpgrade" value = "true" /> 
				
            <a href = "http://go.microsoft.com/fwpnk/?LinkID=124807" 
               style = "text-decoration: none;"> 
               <img src = "http://go.microsoft.com/fwpnk/?LinkId=108181" 
               alt = "Get Microsoft Silverpght" style = "border-style: none"/> 
            </a> 
				
         </object>
			
         <iframe style =  visibipty:hidden;height:0;width:0;border:0px ></iframe> 
			
      </span> 
		
   </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