• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3059
  • Last Modified:

How to call JavaScript from a embedded c# dll in object tag in a web page

I would like to call JavaScript from a c# component (dll) embedded in an html page with the  object tag.

So far I have got the following sample code that I have taken from other forums and google searches.

In the HTML page I have:

<OBJECT id="myControl" name="myControl" style="WIDTH: 208px; HEIGHT: 176px" height="176" width="208" classid="dll/ActiveXControl.dll#ActiveXControl.ButtonControl" VIEWASTEXT>
</OBJECT>

and:

<script type="text/javascript" for="myControl" event="objectClicked(sender)" >
{
    alert("message");
}
</script>


In my c# windows control project I have the following code:

public delegate void SelectClickEventHandler(object sender);

public class ButtonControl : System.Windows.Forms.UserControl
  {
         public event SelectClickEventHandler objectClicked;


// the rest of the component code follows

// then when I want to raise the event I call

private void ButtonControl_Click(object sender, System.EventArgs e)
{
      if (objectClicked != null)
             objectClicked(this);
}


Am I on the right track and if so any suggestions on how to get it to work or is there another method I could use?

0
JohanGrundling
Asked:
JohanGrundling
1 Solution
 
vilimedCommented:
see this sample code
<HTML>

<HEAD>

<SCRIPT>

function load()
{
}

function fileUpload()
{
      if (true == upload1.FilesPending)
      {
            upload1.UploadFiles();
      }
}

function incrementWait()
{
      window.status += ".";
}

</SCRIPT>

<SCRIPT FOR="upload1" EVENT="BeginUpload">

window.status = "uploading files...please wait";

</SCRIPT>

<SCRIPT FOR="upload1" EVENT="UploadComplete">

window.alert("Upload complete");

</SCRIPT>


</HEAD>

<BODY onload="load();">

<OBJECT id="upload1" classid="Upload.dll#TestCorp.ClientControls.MultiUploadCtrl" width=800 height=300 style="font-size:12;">
      <PARAM Name="FileUploadURL" Value="http://localhost/ServerFileUpload/UploadFile.aspx">
      <PARAM Name="MaxSessionUpload" Value="10646">
</OBJECT><p>

<button id="btnUpload" onclick="fileUpload();">
Upload Files
</button>

</BODY>


</HTML>
C#
using System;
using System.Threading;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.IO;

namespace TestCorp.ClientControls
{
      /// <summary>
      /// Upload multiple files to a server-side web app using an
      /// intuitive interface.
      /// </summary>
      [ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(IMultiUploadCtrlCOMEvents))]
      public class MultiUploadCtrl : System.Windows.Forms.UserControl, IMultiUploadCtrlCOMIncoming
      {
            private System.Windows.Forms.Label lbl1;
            private System.Windows.Forms.Button selectDir;

            /// Required designer variable.
            private System.ComponentModel.Container components = null;

            // URL supplied by user.
            private string uploadURL;

            // The current upload size for all selected files.
            private long totalUploadSize;

            // The max upload size per session. -1 signifies
            // unlimited upload.
            private int maxUpload;

            // The number of bytes already uploaded.
            private long bytesUploaded;

            // An event signaling the end of our current upload batch.
            public delegate void UploadCompleteHandler();
            public event UploadCompleteHandler UploadComplete;

            public delegate void BeginUploadHandler();
            public event BeginUploadHandler BeginUpload;

            // Hashtable of selected files.
            // We use this to cache information about the file that
            // we only need to retrieve once, such as file size.
            protected Hashtable fileTable;

            // The thread we use to upload files to the
            // web server.
            protected Thread uploadThread;

            private System.Windows.Forms.Label label1;
            private System.Windows.Forms.Label lblUploadByteAmount;
            private System.Windows.Forms.Button btnRemove;
            private System.Windows.Forms.Button btnUpload;
            private System.Timers.Timer timer1;
            private System.Windows.Forms.ListBox fileListBox;

            public MultiUploadCtrl()
            {
                  // This call is required by the Windows.Forms Form Designer.
                  InitializeComponent();

                  // TODO: Add any initialization after the InitForm call
                  totalUploadSize = 0;
                  maxUpload = -1;
                  bytesUploaded = 0;
                  fileTable = new Hashtable();
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if(components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Component Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.label1 = new System.Windows.Forms.Label();
                  this.selectDir = new System.Windows.Forms.Button();
                  this.lbl1 = new System.Windows.Forms.Label();
                  this.timer1 = new System.Timers.Timer();
                  this.btnRemove = new System.Windows.Forms.Button();
                  this.lblUploadByteAmount = new System.Windows.Forms.Label();
                  this.btnUpload = new System.Windows.Forms.Button();
                  this.fileListBox = new System.Windows.Forms.ListBox();
                  ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
                  this.SuspendLayout();
                  //
                  // label1
                  //
                  this.label1.Location = new System.Drawing.Point(16, 192);
                  this.label1.Name = "label1";
                  this.label1.Size = new System.Drawing.Size(152, 24);
                  this.label1.TabIndex = 4;
                  this.label1.Text = "Total Bytes to Upload:";
                  //
                  // selectDir
                  //
                  this.selectDir.Location = new System.Drawing.Point(312, 48);
                  this.selectDir.Name = "selectDir";
                  this.selectDir.Size = new System.Drawing.Size(76, 21);
                  this.selectDir.TabIndex = 2;
                  this.selectDir.Text = "Browse...";
                  this.selectDir.Click += new System.EventHandler(this.selectDir_Click);
                  //
                  // lbl1
                  //
                  this.lbl1.Location = new System.Drawing.Point(16, 16);
                  this.lbl1.Name = "lbl1";
                  this.lbl1.Size = new System.Drawing.Size(256, 32);
                  this.lbl1.TabIndex = 0;
                  this.lbl1.Text = "Files to Upload:";
                  //
                  // timer1
                  //
                  this.timer1.Enabled = true;
                  this.timer1.SynchronizingObject = this;
                  this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
                  //
                  // btnRemove
                  //
                  this.btnRemove.Enabled = false;
                  this.btnRemove.Location = new System.Drawing.Point(312, 78);
                  this.btnRemove.Name = "btnRemove";
                  this.btnRemove.Size = new System.Drawing.Size(76, 21);
                  this.btnRemove.TabIndex = 2;
                  this.btnRemove.Text = "Remove";
                  this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
                  //
                  // lblUploadByteAmount
                  //
                  this.lblUploadByteAmount.Location = new System.Drawing.Point(219, 192);
                  this.lblUploadByteAmount.Name = "lblUploadByteAmount";
                  this.lblUploadByteAmount.Size = new System.Drawing.Size(77, 24);
                  this.lblUploadByteAmount.TabIndex = 5;
                  //
                  // btnUpload
                  //
                  this.btnUpload.Enabled = false;
                  this.btnUpload.Location = new System.Drawing.Point(312, 160);
                  this.btnUpload.Name = "btnUpload";
                  this.btnUpload.Size = new System.Drawing.Size(76, 21);
                  this.btnUpload.TabIndex = 2;
                  this.btnUpload.Text = "Upload";
                  this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
                  //
                  // fileListBox
                  //
                  this.fileListBox.Location = new System.Drawing.Point(16, 48);
                  this.fileListBox.Name = "fileListBox";
                  this.fileListBox.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
                  this.fileListBox.Size = new System.Drawing.Size(280, 134);
                  this.fileListBox.TabIndex = 3;
                  //
                  // MultiUploadCtrl
                  //
                  this.BackColor = System.Drawing.Color.White;
                  this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                                                              this.btnUpload,
                                                                                                              this.lblUploadByteAmount,
                                                                                                              this.label1,
                                                                                                              this.btnRemove,
                                                                                                              this.fileListBox,
                                                                                                              this.selectDir,
                                                                                                              this.lbl1});
                  this.Name = "MultiUploadCtrl";
                  this.Size = new System.Drawing.Size(400, 264);
                  this.Load += new System.EventHandler(this.MultiUploadCtrl_Load);
                  ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
                  this.ResumeLayout(false);

            }
            #endregion

            private void selectDir_Click(object sender, System.EventArgs e)
            {
                  if (!IsValidUrl(uploadURL))
                  {
                        throw(new WebException("URL supplied is " + uploadURL + ". URLs for this control must start with either 'http' or 'https'."));
                  }

                  OpenFileDialog dirDialog = new OpenFileDialog();
                  dirDialog.Multiselect = true;
                  dirDialog.ShowDialog();

                  // Add to list.
                  new FileIOPermission(PermissionState.Unrestricted).Assert();
                  foreach (string fileListItem in dirDialog.FileNames)
                  {
                        // Has the user already selected this file?
                        // If so, don't add it again.
                        // !TODO - user notification of dupes?
                        if (!fileTable.Contains(fileListItem))
                        {
                              AddFile(fileListItem);
                        }
                  }
                  CodeAccessPermission.RevertAssert();
                  UpdateFileSizeDescription();
            }

            /// <summary>
            /// Upload all selected files to the server.
            /// </summary>
            /// <permission cref="">
            /// Unrestricted FileIOPermission required for
            /// access to entire disk and all shares.
            /// </permission>
            public void UploadFiles()
            {
                  // Do not start the upload thread if one is
                  // already running.
                  if (null != uploadThread && uploadThread.IsAlive)
                  {
                        throw(new Exception("Cannot start a new upload - a previously requested upload is still executing."));
                  }
                  DoBeginUpload();
                   uploadThread = new Thread(new ThreadStart(UploadFilesThread));
                  uploadThread.Start();
            }

            /// <summary>
            /// Worker thread that uploads all items to the
            /// server script named by FileUploadUrl.
            /// </summary>
            /// <remarks>
            /// Need to figure out how to throw multiple events
            /// from a thread - the Timer technique is quite weak.
            /// If this throws an error (and it does if we upload
            /// in excess of 15MB of files), we'll never
            /// see it.
            /// </remarks>
            protected void UploadFilesThread()
            {
                  WebClient UploadObj = new WebClient();
                  object[] itemsCache = new object[fileListBox.Items.Count];

                  // Error out if we're asked to upload files that don't exist.
                  if (0 == fileListBox.Items.Count)
                  {
                        // !TODO: Error mechanism needed.
                        throw(new Exception("You must browse for files before attempting an upload."));
                  }

                  // !TODO: Grant the ability to upload all files batch. WebClient doesn't support
                  // multiple files in the same upload txn, even though the standard
                  // does, so we'll roll our own classes later to handle this.
                  new FileIOPermission(PermissionState.Unrestricted).Assert();
                  fileListBox.Items.CopyTo(itemsCache, 0);
                  for (int i = 0; i < itemsCache.Length; i++)
                  {      
                        // Trap any failures.
                        try
                        {
                              string item = (string)itemsCache[i]; // cast once
                              UploadObj.UploadFile(uploadURL, item);
                              // Remove from the list individually, in case
                              RemoveFile(item);
                              UpdateFileSizeDescription();
                        }
                        catch (WebException e)
                        {      
                              throw(new WebException("Could not upload all of the files.", e));
                        }
                  }
                  CodeAccessPermission.RevertAssert();

                  // We can't call a COM event from a thread other than the one on which the sinking
                  // occurred, or we'll generate an obscure exception. So set a timer in the main thread
                  // and force this event to occur elsewhere.
                  timer1.Interval = 1;
                  timer1.Start();
                  btnRemove.Enabled = false;
            }

            ///<summary>
            // Marks whether or not any files are waiting to be uploaded.
            ///</summary>
            public bool FilesPending
            {
                  get
                  {
                        return(fileListBox.Items.Count > 0);
                  }
            }

            /// <summary>
            /// The maximum number of files that can be uploaded in
            /// this session, in bytes.
            /// </summary>
            public int MaxSessionUpload
            {
                  get
                  {
                        if (-1 == maxUpload)
                        {
                        }
                        
                        return(maxUpload);
                  }
                  set
                  {
                        if (maxUpload < 0)
                        {
                              maxUpload = -1;
                        }
                        else
                        {
                              maxUpload = Convert.ToInt32(value.ToString());
                        }
                  }
            }

            /// <summary>
            /// The number of bytes already uploaded.
            /// </summary>
            public int BytesUploaded
            {
                  get
                  {
                        return((int)bytesUploaded);
                  }
            }

            public string FileUploadURL
            {
                  get
                  {
                        return(uploadURL);
                  }
                  set
                  {
                        // IE suppresses any exceptions (IErrorInfo in COM parlance) thrown during
                        // IPersistPropertyBag:Load(). Check the integrity of this string later during
                        // control use instead of now.
                        if (null != value)
                        {
                              uploadURL = value.ToString();
                        }
                  }
            }

            private void MultiUploadCtrl_Load(object sender, System.EventArgs e)
            {
                  fileListBox.SelectedIndexChanged += new System.EventHandler(this.fileListBox_SelectedIndexChanged);
                  UpdateFileSizeDescription();
            }

            

            private bool IsValidUrl(string url)
            {
                  string urlTmp = url.ToLower();
                  // Note: covers both "http" and "https".
                  if (false == urlTmp.StartsWith("http"))
                  {
                        return false;
                  }
                  else
                  {
                        return true;
                  }
            }

            /// <summary>
            /// Encapsulate all the updating required when a file
            /// is added to the file list. For security reasons,
            /// this method is never exposed via our public API.
            /// </summary>
            /// <param name="fileFullName">The file to add.</param>
            protected void AddFile(string fileFullName)
            {
                  CachedFileInfo cachedInfo;
                  FileInfo fInfo;

                  // Get file size from file system.
                  fInfo = new FileInfo(fileFullName);
                  cachedInfo.FileSizeBytes = fInfo.Length;
                  // Are we within our quota?
                  if (maxUpload > -1)
                  {
                        if (totalUploadSize + cachedInfo.FileSizeBytes > maxUpload)
                        {
                              throw(new Exception("The file " + fileFullName + "is " + cachedInfo.FileSizeBytes + " bytes. Adding this to your upload queue would violate your maximum quota for this upload session."));
                        }
                  }

                  fileListBox.Items.Add((object)fileFullName);

                  totalUploadSize += fInfo.Length;
                  fileTable.Add(fileFullName, cachedInfo);
                  btnUpload.Enabled = true;
            }

            /// <summary>
            /// Encapsulate all the updating required when a file
            /// is removed from the file list.
            /// </summary>
            /// <param name="fileFullName">The file to remove.</param>
            protected void RemoveFile(string fileFullName)
            {
                  fileListBox.Items.Remove(fileFullName);

                  // Decrement size from file size total.
                  CachedFileInfo cfi = (CachedFileInfo)fileTable[fileFullName];
                  totalUploadSize -= cfi.FileSizeBytes;
                  fileTable.Remove(fileFullName);
                  if (0 == fileListBox.Items.Count)
                  {
                        btnUpload.Enabled = false;
                  }
            }

            private void UpdateFileSizeDescription()
            {
                  lblUploadByteAmount.Text = Convert.ToString(totalUploadSize/1024) + "KB";
            }

            private void fileListBox_SelectedIndexChanged(object sender, System.EventArgs e)
            {
                  if (0 == fileListBox.SelectedIndices.Count)
                  {
                        btnRemove.Enabled = false;                        
                  }
                  else
                  {
                        btnRemove.Enabled = true;
                  }
            }

            private void btnRemove_Click(object sender, System.EventArgs e)
            {
                  int SelectedCount = fileListBox.SelectedItems.Count;
                  object[] selItemsCache = new object[SelectedCount];

                  // use CopyTo() to prevent state problems w/ delete during foreach.
                  fileListBox.SelectedItems.CopyTo(selItemsCache, 0);
                  foreach (object o in selItemsCache)
                  {
                        RemoveFile((string)o);
                  }
                  UpdateFileSizeDescription();
                  // The operation throws focus off the listbox, so
                  // disable the Remove button.
                  btnRemove.Enabled = false;
            }

            protected void DoBeginUpload()
            {
                  if (BeginUpload != null)
                  {
                        // Assert ability to call unmanaged code.
                        new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
                        BeginUpload();
                        CodeAccessPermission.RevertAssert();
                  }                                                              
            }

            protected void DoUploadComplete()
            {
                  if (UploadComplete != null)
                  {
                        // Assert ability to call unmanaged code.
                        new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
                        UploadComplete();
                        CodeAccessPermission.RevertAssert();
                  }                                           
            }

            private void btnUpload_Click(object sender, System.EventArgs e)
            {
                  UploadFiles();
            }

            // Fire the DoUploadComplete event after the secondary thread has finished its labors.
            private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                  timer1.Stop();
                  // Even necessary??
                  if (uploadThread.IsAlive)
                  {
                        uploadThread.Abort();
                  }
                  DoUploadComplete();
            }
      }

      /// <summary>
      /// Cache file information that might have been expensive to
      /// retrieve, such as file size.
      /// </summary>
      internal struct CachedFileInfo
      {
            public long FileSizeBytes;
      }

      /// <summary>
      /// Source interface for hooking up to COM events so that JScript/VBScript can sink event
      /// handlers with us. Disgusting, but it works.
      /// </summary>
      [Guid("A59B958D-B363-454b-88AA-BE8626A131FB")]
      [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
      public interface IMultiUploadCtrlCOMEvents
      {
            [DispId(0x60020000)]
            void UploadComplete();

            [DispId(0x60020001)]
            void BeginUpload();
      }

      /// <summary>
      /// Default incoming interface for our control. Required when using COM-style events,
      /// otherwise IE will no longer be able to access our public properties and methods.
      /// </summary>
      public interface IMultiUploadCtrlCOMIncoming
      {
            void UploadFiles();
            bool FilesPending {get;}
            int MaxSessionUpload {get; set; }
            int BytesUploaded {get;}
            string FileUploadURL {get; set; }
      }
}
0

Featured Post

Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

Tackle projects and never again get stuck behind a technical roadblock.
Join Now