title: Call Silverlight with Javascript
body: <p>I'm trying to call a public method of a silverlight app via javascript that simply sets a private variable.  When I attempt to set the file name, I get a javascript error.  fu.Content.myObject is undefined.  Can anyone spot the error?  <a href="http://www.devicity.com/fileuploadertestpage.aspx" rel="nofollow">http://www.devicity.com/fileuploadertestpage.aspx</a> </p>
  
  <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org    /TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt;
  &lt;head runat="server"&gt;
  &lt;title&gt;FileUploader&lt;/title&gt;
  &lt;style type="text/css"&gt;
  html, body {
      height: 100%;
      overflow: auto;
  }
  body {
      padding: 0;
      margin: 0;
  }
  #silverlightControlHost {
      height: 100%;
      text-align:center;
  }
  &lt;/style&gt;
      &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"&gt;&lt;/script&gt;
  
  &lt;script type="text/javascript" src="Silverlight.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
      function onSilverlightError(sender, args) {
          var appSource = "";
          if (sender != null &amp;&amp; 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);
      }
  &lt;/script&gt;
  &lt;script language="javascript" type="text/javascript"&gt;
      function SetFileName() {
          var fu = document.getElementById("FileUpload1");
          fu.Content.myObject.SetFileName("10");
      }
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;form id="form1" runat="server" style="height:100%"&gt;
  &lt;div id="silverlightControlHost"&gt;
      &lt;object data="data:application/x-silverlight-2," id="FileUpload1" type="application/x-silverlight-2" width="600" height="600"&gt;
        &lt;param name="source" value="ClientBin/FileUploader.xap"/&gt;
        &lt;param name="onError" value="onSilverlightError" /&gt;
        &lt;param name="background" value="white" /&gt;
        &lt;param name="minRuntimeVersion" value="3.0.40818.0" /&gt;
        &lt;param name="autoUpgrade" value="true" /&gt;
        &lt;a href="http://go.microsoft.com/fwlink/?LinkID=149156&amp;v=3.0.40818.0" style="text-decoration:none"&gt;
            &lt;img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/&gt;
        &lt;/a&gt;
      &lt;/object&gt;&lt;iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"&gt;&lt;/iframe&gt;&lt;/div&gt;
      &lt;input type="button" onclick="SetFileName();" value="SetFileName" /&gt;
  &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>``</p>
  
  <pre><code>[ScriptableType]
  public partial class MainPage : UserControl
  {
      public MainPage()
      {
          InitializeComponent();
      }
  
      private void UserControl_Loaded(object sender, RoutedEventArgs e)
      {
  
          HtmlPage.RegisterScriptableObject("myObject", this);
  
      }
  
      private string m_FileName = "setthis";
  
      [ScriptableMember]
      public void SetFileName(string fileName)
      {
          m_FileName = fileName;
      }
  
      private OpenFileDialog dlg = new OpenFileDialog();
      private void Browse_Click(object sender, RoutedEventArgs e)
      {
  
          dlg.Multiselect = false;
          dlg.Filter = "MP3s (*.mp3)|*.mp3|All files (*.*)|*.*";
  
          bool? retval = dlg.ShowDialog();
  
          if (retval != null &amp;&amp; retval == true)
          {
  
              StatusText.Text = dlg.File.Name;
          }
          else
          {
              StatusText.Text = "No file selected...";
          }
      }
  
      private void UploadFile(string fileName, Stream data)
      {
          UriBuilder ub = new UriBuilder("http://localhost:43439/uploadfile.aspx");
          ub.Query = string.Format("filename={0}", m_FileName);
  
          WebClient c = new WebClient();
          c.OpenWriteCompleted += (sender, e) =&gt;
          {
              PushData(data, e.Result);
              e.Result.Close();
              data.Close();
          };
          c.OpenWriteAsync(ub.Uri);
      }
  
      private void Upload_Click(object sender, RoutedEventArgs e)
      {
  
          try
          {
              UploadFile(StatusText.Text, dlg.File.OpenRead());
          }
          catch (Exception ex)
          {
              StatusText.Text = ex.ToString();
          }
  
      }
  
  
  
      private void PushData(Stream input, Stream output)
      {
          byte[] buffer = new byte[4096];
          int bytesRead;
          int totalBytesRead = 0;
  
          while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
          {
              totalBytesRead += bytesRead;
              StatusText.Text = ((int)(totalBytesRead / input.Length)).ToString("P");
              output.Write(buffer, 0, bytesRead);
  
          }
      }
  }
  </code></pre>