Home > Articles > Programming > ASP .NET

This chapter is from the book

This chapter is from the book

Understanding Your Hosting Options

Silverlight exposes a number of properties and events that customize the appearance of the Silverlight content and the way it interacts with the HTML document it lives inside. In addition, the source parameter exposed by the Silverlight add-on supports more functionality than previously described. This section examines the extra functionality of source, and then looks at all the properties and events that the add-on directly exposes.

source

Previous listings have demonstrated the most common usage of source setting it to the name (and path, if applicable) of a XAML file on the web server. However, you can alternatively place your XAML inline in the HTML document. There are two steps for doing this:

  1. Place your XAML content within a SCRIPT element with type text/xaml somewhere in the document before the HTML element that will contain the Silverlight control, and give it a unique id.
  2. Use the SCRIPT element's id preceded by a # as the source value given to the Silverlight add-on. The # prefix is what distinguishes an id from a filename.

Listings 1.6 and 1.7 are updates to Listings 1.4 and 1.5 that remove the dependency on the separate Chapter1.xaml file.

Listing 1.6. Placing Inline XAML Inside HTML

<html>
  <head>
    <title>Great Estates</title>
    <script type="text/javascript" src="Silverlight.js"></script>
    <script type="text/javascript" src="CreateSilverlight.js"></script>
  </head>
  <body style="background:blue">
    <!-- A Silverlight-based logo: -->
    <script id="xaml" type="text/xaml">
      <Canvas xmlns="http://schemas.microsoft.com/client/2007">
        <MediaElement Name="video" Source="Lake.wmv" Opacity="0" IsMuted="true"/>
        <!-- A circle containing a live video: -->
        <Ellipse Width="100" Height="100">
          <Ellipse.Fill>
            <VideoBrush SourceName="video"/>
          </Ellipse.Fill>
        </Ellipse>
        <!-- Two pieces of text: -->
        <TextBlock FontFamily="Georgia" Foreground="Blue" FontStyle="Italic"
          FontSize="40" Canvas.Left="125" Canvas.Top="20" Text="Great Estates"/>
        <TextBlock Foreground="Blue" Canvas.Left="110" Canvas.Top="70"
          Text="Luxurious Living at an Affordable Price"/>
        <!-- Curves and a line: -->
         <Path Stroke="Red" StrokeThickness="4">
           <Path.Data>
             <PathGeometry>
               <PathFigure StartPoint="0,65">
                 <ArcSegment SweepDirection="Clockwise" Size="2,2" Point="25,65"/>
                 <ArcSegment SweepDirection="Clockwise" Size="2,2" Point="50,65"/>
                 <ArcSegment SweepDirection="Clockwise" Size="2,2" Point="75,65"/>
                 <ArcSegment SweepDirection="Clockwise" Size="2,2" Point="100,65"/>
                 <LineSegment Point="390,65"/>
               </PathFigure>
             </PathGeometry>
           </Path.Data>
         </Path>
       </Canvas>
     </script>
    <div id="placeholder">
      <script type="text/javascript">createSilverlight();</script>
    </div>
    <p style="font-family:Tahoma; color:white">
      An idyllic new community located high on a hill and offering captivating
      waterfront views. Tailored to meet both the needs of upsizing and
      downsizing buyers, Great Estates offers custom quality architecture and
      design at an affordable price point.
    </p>
  </body>
</html>

Listing 1.7. CreateSilverlight.js—Using Inline XAML as the source

function createSilverlight()
{
  Silverlight.createObjectEx(
    {
      source: "#xaml",
      parentElement: document.getElementById("placeholder"),
      id: "silverlightControl",
      properties:
        { width: "390", height: "100", version: "1.0", background: "Yellow" },
      events: {}
    }
  );
}

This #id syntax is supported anywhere the source might be specified: createObject, createObjectEx, directly on an EMBED element, or as a PARAM inside an OBJECT element. This functionality is a handy way to combine what would ordinarily be two web requests into one. But in addition to efficiency considerations, removing the dependency on a custom external file enables server-side code (in technologies such as ASP.NET or PHP) to emit Silverlight content in a completely encapsulated way.

Properties

The width, height, and version properties exposed by Silverlight are straightforward, but the background property could use a little more explanation. In addition, the Silverlight add-on supports more properties that haven't been discussed yet.

background

The background property—which can be set via createObject, createObjectEx, or directly on an OBJECT/EMBED element—is more powerful than a normal HTML color value. Besides named colors—such as Red or Yellow—and RGB values—such as #F1F1F1 or #456, background can be given an alpha channel for creating transparent or translucent background colors. The syntax is #AARRGGBB (or #ARGB), so a translucent red color would be #77FF0000 (or #7F00). background can also be set to the named value Transparent, which is the same as any color with an alpha channel value of zero. If you omit background altogether, the control will be given a white background.

isWindowless

By default, an instance of the Silverlight control is known as windowed, but by setting isWindowless to true (which can be done via createObject, createObjectEx, or directly on an OBJECT/EMBED element), you can change it to be a windowless control. The distinction of windowed versus windowless isn't specific to Silverlight, but rather refers to a low-level implementation detail on Windows (whether the control has its own window handle, or HWND).

The important thing to understand is the two different behaviors of a windowless control:

  • A windowless control respects HTML z-indexing, so you can overlay and overlap HTML content on top of Silverlight and vice versa. A windowed control, on the other hand, is always rendered on top.
  • A windowless control supports transparency, so it can be given a transparent or translucent background, and content inside it can be transparent or translucent.

Figure 1.5 shows a potential way that the Great Estates website might take advantage of windowless Silverlight content—placing an HTML SELECT element on top of the Silverlight logo.

Figure 1.5

Figure 1.5 A windowless Silverlight control allows HTML to appear on top of it.

To create the result in Figure 1.5, Listing 1.8 adds a SELECT element to the page from Listing 1.4 and uses CSS to give it an absolute position and a z-index to ensure that it is placed on top of the Silverlight content.

Listing 1.8. Placing an HTML SELECT Element in Front of the Silverlight Control

<html>
  <head>
    <title>Great Estates</title>
    <script type="text/javascript" src="Silverlight.js"></script>
    <script type="text/javascript" src="CreateSilverlight.js"></script>
  </head>
  <body style="background:blue">
    <!-- A Silverlight-based logo: -->
    <div id="placeholder">
      <script type="text/javascript">createSilverlight();</script>
    </div>
    <select style="position:absolute; left:289px; top:18px; z-index:1">
      <option>California</option>
      <option>Pennsylvania</option>
      <option>Washington</option>
    </select>
    <p style="font-family:Tahoma; color:white">
      An idyllic new community located high on a hill and offering captivating
      waterfront views. Tailored to meet both the needs of upsizing and
      downsizing buyers, Great Estates offers custom quality architecture and
      design at an affordable price point.
    </p>
  </body>
</html>

Listing 1.8 only produces the desired result because the corresponding CreateSilverlight.js file sets isWindowless to true, as shown in Listing 1.9.

Listing 1.9. CreateSilverlight.js—Hosting Familiar Silverlight Content in a Windowless Control

function createSilverlight()
{
  Silverlight.createObjectEx(
    {
      source: "Chapter1.xaml",
      parentElement: document.getElementById("placeholder"),
      id: "silverlightControl",
      properties:
        { width: "390", height: "100", version: "1.0", background: "Yellow",
          isWindowless: "true" },
      events: {}
    }
  );
}

inplaceInstallPrompt

The inplaceInstallPrompt property, which can only be used with createObject or createObjectEx, controls the look and behavior of the Silverlight installation graphic that gets displayed when the viewer doesn't have the appropriate version of Silverlight. Figure 1.6 shows the appearance of the two options. Setting inplaceInstallPrompt to false (the default behavior) gives a small graphic that links to the official download page with more information. Setting it to true gives additional text, but the link now points directly to the file to download rather than an intermediate page.

Figure 1.6

Figure 1.6 The two different install prompts supported by Silverlight.js.

maxFramerate

The maxFramerate parameter, which can be set via createObject, createObjectEx, or directly on an OBJECT/EMBED element, customizes the maximum frame rate that the Silverlight control renders content, measured in frames per second. (The actual frame rate is dependent on the client computer and its current load.) The default value for maxFramerate is 24. If you decide to customize maxFramerate, you should select the lowest number possible that gives you the results you need.

The frame rate controls all content inside the Silverlight control—animations and even video—except for audio. You can see this with the Great Estates logo by setting its maxFramerate to 1 and changing IsMuted to false instead of true in the XAML file. This causes the video to progress in an extremely choppy fashion, yet the corresponding audio plays smoothly.

Events

The Silverlight control supports two events that can be set directly on the OBJECT or EMBED element: onLoad and onError. You can assign either event the name of a JavaScript function to be called. For example:

<object type="application/x-silverlight" id="silverlightControl"
  width="390" height="100">
  <param name="background" value="Yellow"/>
  <param name="source" value="Chapter1.xaml"/>
  <param name="onLoad" value="myFunction"/>
</object>

However, because handling either of these events requires the use of JavaScript, you might as well take advantage of createObject or createObjectEx rather than attaching these handlers the "raw" way.

onLoad

The onLoad event is raised as soon as the XAML content has been loaded. Handling this event is useful for performing custom initialization of Silverlight content, such as initiating animations or dynamic positioning/sizing of the control based on document dimensions. These specific kinds of activities are covered in later chapters, but Listing 1.10 at least demonstrates how to designate a function as a handler for the onLoad event.

Listing 1.10. CreateSilverlight.js—Assigning an onLoad Handler

function createSilverlight()
{
  Silverlight.createObjectEx(
    {
      source: "Chapter1.xaml",
      parentElement: document.getElementById("placeholder"),
      id: "silverlightControl",
      properties:
        { width: "390", height: "100", version: "1.0", background: "Yellow" },
      events: { onLoad: myFunction }
    }
  );
}
function myFunction(control, context, rootElement)
{
  // Perform custom initialization
}

The purpose of Silverlight's onLoad event is similar to the HTML DOM's onload event. However, to avoid timing issues, you should stick to the HTML onload event for manipulating HTML content and Silverlight's onLoad event for manipulating Silverlight content.

Handlers for the onLoad event are passed three parameters:

  • control, which is the instance of the Silverlight control. The next section, "Interacting with the Silverlight Control Programmatically," describes some of the things you can do with this object.
  • context, which is simply whatever custom context value was given to createObject or createObjectEx (if one was given).
  • rootElement, which is the instance of the root element in the source XAML content. The next chapter explains how you can programmatically interact with Silverlight elements declared in XAML.

onError

The onError event is raised whenever Silverlight throws an exception not already handled by your JavaScript code. (For an exception thrown from a synchronous function call, this means that no corresponding try/catch block exists. For an exception thrown from an asynchronous function call, this means that no event handler is attached for that specific failure case.) Exceptions can be raised by Silverlight for XAML parsing errors or for any number of runtime errors.

If you don't specify a handler for onError when directly using an OBJECT or EMBED element, unhandled Silverlight errors are swallowed. But when you use createObject or createObjectEx, a function called default_error_handler is automatically set as the handler for onError unless you provide your own. The default handler calls JavaScript's alert function to display a simple dialog, such as the one shown in Figure 1.7.

Figure 1.7

Figure 1.7 When good content goes bad.

To understand how to create your own onError handler, it is instructive to look at the implementation of default_error_handler inside Silverlight.js. It is effectively implemented as follows:

function default_error_handler(sender, args)
{
  var errMsg = "\nSilverlight error message\n";
  // All errors have a numeric code, a type, and a message
  errMsg += "ErrorCode: " + args.errorCode + "\n";
  errMsg += "ErrorType: " + args.errorType + "\n";
  errMsg += "Message: " + args.errorMessage + "\n";
  if (args.errorType == "ParserError")
  {
    // A parser error gives the location in the XAML content
    errMsg += "XamlFile: " + args.xamlFile + "\n";
    errMsg += "Line: " + args.lineNumber + "\n";
    errMsg += "Position: " + args.charPosition + "\n";
  }
  else if (args.errorType == "RuntimeError")
  {
    if (args.lineNumber != 0)
    {
      // Display the line number and character, if the information exists
      errMsg += "Line: " + args.lineNumber + "\n";
      errMsg += "Position: " + args.charPosition + "\n";
    }
    // The name of the function that failed
    errMsg += "MethodName: " + args.methodName + "\n";
  }
  // Display the message in a simple alert box:
  alert(errMsg);
}

The sender is the object on which the error occurred, if applicable. For parser errors, such as the one shown in Figure 1.6, sender is null. The args object provides a number of pieces of information that depend on the type of error raised, as seen in the implementation of default_error_handler.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020