IE Hosted UserControl - javascript interaction not working.

G

Guest

I am trying to get a UserControl hosted in IE working. Having read some
articles on this and followed the examples (Jay Allen’s article at
http://msdn.microsoft.com/msdnmag/issues/02/01/UserCtrl/
was a great source, especially for the security side of things), I have
been able to use params to set properties, use the local filesystem and
access the web from with the control.

What I really need to get working is interaction with the hosting page, in
other words calling methods / setting properties / handling events via
javascript.

I have seen that many others are having the same problems as I am when
trying to do this. In my sample I have a simple control with a single button
and textbox; clicking the button calls a method that gets the machines
hostname (using System.Net.Dns.GetHostName) before displaying this in the
textbox.
I also have a public method on the control that should do the same – it is
this method that I would like to call from javascript.
Within this method an event is raised once the hostname has been obtained,
again I would like to handle this event in javascript.

I believe I have followed the requirements as shown in the articles
(however, I am using .NET 2.0 and think those articles were for 1.0/1.1) to
both expose properties and methods and raise events.

The code for my control is as follows:

using ...;

namespace ClientSideControl
{
[ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(IMyControlCOMEvents))]
public partial class MyControl2 : UserControl, IMyControlCOMIncoming
{

public MyControl2()
{
InitializeComponent();
}

#region Private Properties

private string _hostname = "";

#endregion

#region Private methods

private void DoHostIdentificationComplete()
{
if (HostIdentificationComplete != null)
{
new
SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
HostIdentificationComplete();
CodeAccessPermission.RevertAssert();
}
}

private void button1_Click(object sender, EventArgs e)
{
this.GetHostName();
}



#endregion

#region IMyControlCOMEvents

public delegate void HostIdentificationCompleteHandler();
public event HostIdentificationCompleteHandler
HostIdentificationComplete;

#endregion

#region IMyControlCOMIncoming

public void GetHostName()
{
_hostname = Dns.GetHostName();
textBox1.Text = _hostname;
this.DoHostIdentificationComplete();
}

public string HostName
{
get { return _hostname; }
}

#endregion

}


/// <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("E85219FB-04F2-4230-A579-CD7ACF0CAACB")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IMyControlCOMEvents
{
[DispId(0x60020000)]
void HostIdentificationComplete();
}


/// <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 IMyControlCOMIncoming
{
void GetHostName();
string HostName { get; }
}

}


And the hosting page:

<html>
<head>
<title>IE Hosted UserControl</title>

<script for="myControl2" event="HostNameObtained">

var hostname = myControl2.HostName;
window.status = "HostName obtained : " + hostname;

</script>

<script language="javascript" type="text/javascript">

function GetHostName()
{
myControl2.GetHostName();
}

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<object id="myControl2" name="myControl2" width="400"
height="80" classid="ClientSideControl2.dll#ClientSideControl.MyControl2">
</object>
<br />
<br />
<input type="button" id="btn1" onclick="GetHostName();"
value="get hostname" name="btn1">
</div>
<br />
</form>
</body>
</html>


This is the final step to getting things working and being able to use this
technique for a host of things we’re looking at internally.

What happens right now is that when I click on the “get hostname†button the
following error appears:

---------------------------
Error
---------------------------
A Runtime Error has occurred.
Do you wish to Debug?

Line: 15
Error: 'myControl2' is undefined
---------------------------
Yes No
---------------------------



What I would like to happen here is that the javascript calls the controls
GetHostName method, which raises the event “HostIdentificationComplete†and
displays the hostname on the status bar of the browser.

I have set things up so Full Access is available to the control.

Please help! (if this is the wrong group then please can you let me know
which one this cross group question should go to - thanks!)
 
L

Linda Liu [MSFT]

Hi Shaun,

I noticed that you have embedded the object myControl2 in a form in the
hosting page. So you should access it by 'form1.myControl2' in the scripts.

Hope this helps.

Sincerely,
Linda Liu
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 
G

Guest

Sorry, was a bit mixed up there as have been trying all sorts of samples to
get this working. I've update my html to be:

<html>
<head>
<title>IE Hosted UserControl</title>

<script for="myControl2" event="HostIdentificationComplete">

var hostname = form1.myControl2.HostName;
window.status = "HostName obtained : " + hostname;

</script>

<script language="javascript" type="text/javascript">

function GetHostName()
{
form1.myControl2.GetHostName();
}

function ShowHostName()
{
alert(form1.myControl2.HostName());
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<object id="myControl2" name="myControl2" width="400"
height="80" classid="ClientSideControl2.dll#ClientSideControl.MyControl2">
</object>
<br />
<br />
<input type="button" id="btn1" onclick="GetHostName();"
value="get hostname" name="btn1"><br />
<input type="button" id="btn2" onclick="ShowHostName();"
value="show hostname" name="btn2"><br />
</div>
<br />


</form>
</body>
</html>

However, I now get the error:


---------------------------
Error
---------------------------
A Runtime Error has occurred.
Do you wish to Debug?

Line: 15
Error: Object doesn't support this property or method
---------------------------
Yes No
---------------------------

This seems to indicate that it is not finding the interface as expected -
this appears to be a common problem having trawled the web looking for an
answer.

I using Visual Studio 2005, Windows XP Pro SP2 and IE 6.

Do you know of a working example that I can try (and then modify for my
purposes).

Thanks,

Shaun
 
G

Guest

Just to complete the picture a little more, here is what I am trying to do:

Embed a control on the page which has one method, one property and one event.

Whent the page loads the controls method should be invoked from javascript,
this method does some work and then raises the event, which is handled by the
javascript of the page. The event handler code will read the property value
and use it to some some stuff on the page.

So, nothing too crazy there I think - certainly many people claim it is
possible, but it just will not work for me!?

Any help you can give me on this would be mucho appreciated and any working
samples would be great.

Thanks,
 
L

Linda Liu [MSFT]

Hi Shaun,

Thank you for your update.

I can understand what you mean. I am doing research on this issue and will
get it back to you as soon as possible.

I appreciate your patience.

Sincerely,
Linda Liu
Microsoft Online Community Support
 
L

Linda Liu [MSFT]

Hi Shaun,

To access public properties or invoke public methods of the control from
javascript in the web page, all we need to do is to build the control as a
COM class. To do this, right-click the project in the Solution Explorer and
choose Properties. In the Project Designer, select the Application tab and
click the 'Assembly Information' button on the right panel. In the Assembly
Information window, select the checkbox before the 'Make assembly
COM-Visible' option and press OK.

To expose events in the control to web pages and handle the events in the
web pages, we need to do more work. The following is the walkthrough.

1. Pack the events to be exposed into an interface, which is applied the
InterfaceTypeAttribute and then apply this interface to the control class.
The following is a sample.

[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IMyControlCOMEvents
{
[DispId(0x60020000)]
void HostIdentificationComplete();
}

[ComSourceInterfaces(typeof(IMyControlCOMEvents))]
public partial class MyControl2 : UserControl
{
.........
}

2. Because we need to handle the event in the script in the web page, we
need assign the control assembly embeded in the web page the permission to
call unmanaged code. To do this, follow the steps below.

a. Type 'mscorcfg.msc' in the SDK command to open .Net Framework 2.0
Configuration.

b. In the configuration, navigate to My Computer->Runtime Security
Policy->Machine->Permission Sets. Right-click on the LocalIntranet sub
node and choose 'Duplicate'. A new permission set called 'Copy of
LocalIntranet' is generated.

c. Right-click on the new permission set and choose 'Change Permissions'.
In the Create Permission Set window, double-click the 'Security' item in
the right listbox. In the 'Permission Settings' window, select the checkbox
before the 'Allow calls to unmanaged assembly' option. Press OK and then
Finish button to close the windows.

d. Navigate to My Computer->Runtime Security Policy->Machine->Code
Groups. Right-click on the 'All_Code' node and choose 'New'. In the 'Create
Code Group' window, select the 'Create a new code group' option and type a
name for the new group and press Next. In the 'Choose the condition type
for this code group' combobox, select 'URL' and type the web site url into
the URL textbox, e.g. http://localhost/mytest/* and press Next. Choose 'Use
existing permission set' option and select 'Copy of LocalIntranet' in the
combobox and press Next. Press Finish.

3. Because the assembly that load the assembly of our control into the web
page doesn't have the permission to call the unmanaged code, we must assign
this permission to the assembly. To do this, we call the Assert method of
the Securitypermission class. The lines of code you wrote in the
DoHostIndenticationComplete method are correct.

Please follow the above steps to solve your problem and let me know the
result.



Sincerely,
Linda Liu
Microsoft Online Community Support
 
G

Guest

Linda,

Thanks very much for your response - I'd found the ComSourceInterfaces
attribute and that seemed to get things going for me.

Just got to work out the security side of things now and we'll be done -
should be OK as I've had things working with file system and web access, but
needx to tighten it down as much as possible.

For any one interested my final code is:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;
using System.Security.Permissions;

[assembly: ClassInterface(ClassInterfaceType.AutoDual)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode =
true)]
namespace MyControls
{
public delegate void SubmitClickedHandler();

[ComVisible(true)]
[Guid("67CD00DB-E9BC-484d-9033-83D41112EBD4")]
public interface HostNameControlCOMIncoming
{
string HostName { get; set; }
void GetHostName();
}

[ComVisible(true)]
[Guid("61CD00DB-E9BC-484d-9033-83D41112EBD4")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface HostNameControlEvents
{
[DispId(0)]
void GetHostNameComplete();
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(HostNameControlEvents))]
[ComDefaultInterface(typeof(HostNameControlCOMIncoming))]
public partial class HostNameControl : UserControl,
HostNameControlCOMIncoming
{

private string _hostname;

public HostNameControl()
{
InitializeComponent();
}

[Category("Action")]
[Description("Fired when the Submit button is clicked.")]
public event SubmitClickedHandler GetHostNameComplete;

protected virtual void OnGetHostNameComplete()
{
if (GetHostNameComplete != null)
GetHostNameComplete();
}

[Category("Appearance")]
[Description("Gets or sets the name in the text box")]
public string HostName
{
get { return _hostname; }
set { _hostname = value; }
}

[Description("Gets hostbname of local machine")]
public void GetHostName()
{
_hostname = System.Net.Dns.GetHostName();
OnGetHostNameComplete();
}


}
}


--------------------------
Shaun Venus
--------------------------


Linda Liu said:
Hi Shaun,

To access public properties or invoke public methods of the control from
javascript in the web page, all we need to do is to build the control as a
COM class. To do this, right-click the project in the Solution Explorer and
choose Properties. In the Project Designer, select the Application tab and
click the 'Assembly Information' button on the right panel. In the Assembly
Information window, select the checkbox before the 'Make assembly
COM-Visible' option and press OK.

To expose events in the control to web pages and handle the events in the
web pages, we need to do more work. The following is the walkthrough.

1. Pack the events to be exposed into an interface, which is applied the
InterfaceTypeAttribute and then apply this interface to the control class.
The following is a sample.

[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IMyControlCOMEvents
{
[DispId(0x60020000)]
void HostIdentificationComplete();
}

[ComSourceInterfaces(typeof(IMyControlCOMEvents))]
public partial class MyControl2 : UserControl
{
.........
}

2. Because we need to handle the event in the script in the web page, we
need assign the control assembly embeded in the web page the permission to
call unmanaged code. To do this, follow the steps below.

a. Type 'mscorcfg.msc' in the SDK command to open .Net Framework 2.0
Configuration.

b. In the configuration, navigate to My Computer->Runtime Security
Policy->Machine->Permission Sets. Right-click on the LocalIntranet sub
node and choose 'Duplicate'. A new permission set called 'Copy of
LocalIntranet' is generated.

c. Right-click on the new permission set and choose 'Change Permissions'.
In the Create Permission Set window, double-click the 'Security' item in
the right listbox. In the 'Permission Settings' window, select the checkbox
before the 'Allow calls to unmanaged assembly' option. Press OK and then
Finish button to close the windows.

d. Navigate to My Computer->Runtime Security Policy->Machine->Code
Groups. Right-click on the 'All_Code' node and choose 'New'. In the 'Create
Code Group' window, select the 'Create a new code group' option and type a
name for the new group and press Next. In the 'Choose the condition type
for this code group' combobox, select 'URL' and type the web site url into
the URL textbox, e.g. http://localhost/mytest/* and press Next. Choose 'Use
existing permission set' option and select 'Copy of LocalIntranet' in the
combobox and press Next. Press Finish.

3. Because the assembly that load the assembly of our control into the web
page doesn't have the permission to call the unmanaged code, we must assign
this permission to the assembly. To do this, we call the Assert method of
the Securitypermission class. The lines of code you wrote in the
DoHostIndenticationComplete method are correct.

Please follow the above steps to solve your problem and let me know the
result.



Sincerely,
Linda Liu
Microsoft Online Community Support
 
G

Guest

Linda,

The code I posted worked fine, even though I did not have the assert in the
event raising code - I have now added that just to cover that one off.

I'm still having some problems with getting the control to load when I have
anything other than Full Trust.

I added the 'Allow calls to unmanaged assemblies' (as this was mentioned in
the Jay Allen article), but when I then try to use my permission set the
control will not load.
I found something on the web about debugging IE - a couple of registry
settings under HKLM\SOFTWARE\Microsoft\.NETFramework (IEHostLogFile and
DebugIEHost) and this following is what is produced when the control attempts
to load:


Creating security manager

Microsoft.IE.Manager: Microsoft.IE.Manager: unique id lgth = 36
Microsoft.IE.SecureFactory: Create SecureFactory() with security information
Microsoft.IE.Manager: Created secure factory
Microsoft.IE.SecureFactory: Creating instance of the object in the correct
domain
Microsoft.IE.SecureFactory: pUrl =
http://localhost/Pluto/RCT/RegisterRCTDevice.aspx
Microsoft.IE.SecureFactory: id = 86474707A3C6F63616C686F6374710000000
Microsoft.IE.SecureFactory: link =
Microsoft.IE.SecureFactory: licenses =
Microsoft.IE.Manager: Url = http://localhost/Pluto/RCT/RegisterRCTDevice.aspx
Microsoft.IE.Manager: UrlGetPartW returned 0
Microsoft.IE.Manager: UrlGetPartW returned 80070057
Microsoft.IE.Manager: CodeBase = http://localhost
Microsoft.IE.Manager: Application = Pluto/RCT
Microsoft.IE.Manager: Found a codebase
Microsoft.IE.Manager: UrlCanonicalize returned 0
Microsoft.IE.SecureFactory: URL codeBase: http://localhost/
Microsoft.IE.SecureFactory: URL application: Pluto/RCT
Microsoft.IE.SecureFactory: Locating domain for http://localhost/
Microsoft.IE.IDKey: Created key
Microsoft.IE.Manager: The domain does not exist.
Microsoft.IE.IDKey: Created key
Microsoft.IE.Manager: The domain does not exist.
Microsoft.IE.SecureFactory: Need to create domain
Microsoft.IE.SecureFactory: Application base: http://localhost/
Microsoft.IE.SecureFactory: Private Bin Path: bin
Microsoft.IE.IDKey: Created key
Microsoft.IE.SecureFactory: Trying to create instance of type
http://localhost/RCTDeviceRegistrat...viceRegistrationControl.RCTDeviceRegistration
Microsoft.IE.SecureFactory: System.Security.SecurityException: That assembly
does not allow partially trusted callers.
at
System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm,
PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh,
SecurityAction action, Object demand, IPermission permThatFailed)
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean
publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor,
Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean
skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder
binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr,
Binder binder, Object[] args, CultureInfo culture, Object[]
activationAttributes)
at System.Activator.CreateComInstanceFrom(String assemblyName, String
typeName, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
at System.AppDomain.CreateComInstanceFrom(String assemblyFile, String
typeName, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
at System.AppDomain.CreateComInstanceFrom(String assemblyFile, String
typeName, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
at Microsoft.IE.SecureFactory.CreateInstanceWithSecurity(Int32 dwFlag,
Int32 dwZone, String pURL, String uniqueIdString, String link, String
licenses)
The action that failed was:
LinkDemand
Microsoft.IE.SecureFactory: LOG exception
Microsoft.IE.SecureFactory: Creating log entry
?FusionBindError!name=RCTDeviceRegistrationControl.dll
Pluto.Common.RCT.RCTDeviceRegistrationControl.RCTDeviceRegistration
Microsoft.IE.SecureFactory: Logging to file C:\Documents and
Settings\sxv\Local Settings\Temporary Internet
Files\Content.IE5\4XQ7CXQB\CAGHN3JS.HTM



I've tried a number of combinations of things with no luck. Can you help
here? Do you know of any good references on this subject as I've found them
hard to come by.

Thanks again,

--------------------------
Shaun Venus
--------------------------


sunev said:
Linda,

Thanks very much for your response - I'd found the ComSourceInterfaces
attribute and that seemed to get things going for me.

Just got to work out the security side of things now and we'll be done -
should be OK as I've had things working with file system and web access, but
needx to tighten it down as much as possible.

For any one interested my final code is:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;
using System.Security.Permissions;

[assembly: ClassInterface(ClassInterfaceType.AutoDual)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode =
true)]
namespace MyControls
{
public delegate void SubmitClickedHandler();

[ComVisible(true)]
[Guid("67CD00DB-E9BC-484d-9033-83D41112EBD4")]
public interface HostNameControlCOMIncoming
{
string HostName { get; set; }
void GetHostName();
}

[ComVisible(true)]
[Guid("61CD00DB-E9BC-484d-9033-83D41112EBD4")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface HostNameControlEvents
{
[DispId(0)]
void GetHostNameComplete();
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(HostNameControlEvents))]
[ComDefaultInterface(typeof(HostNameControlCOMIncoming))]
public partial class HostNameControl : UserControl,
HostNameControlCOMIncoming
{

private string _hostname;

public HostNameControl()
{
InitializeComponent();
}

[Category("Action")]
[Description("Fired when the Submit button is clicked.")]
public event SubmitClickedHandler GetHostNameComplete;

protected virtual void OnGetHostNameComplete()
{
if (GetHostNameComplete != null)
GetHostNameComplete();
}

[Category("Appearance")]
[Description("Gets or sets the name in the text box")]
public string HostName
{
get { return _hostname; }
set { _hostname = value; }
}

[Description("Gets hostbname of local machine")]
public void GetHostName()
{
_hostname = System.Net.Dns.GetHostName();
OnGetHostNameComplete();
}


}
}


--------------------------
Shaun Venus
--------------------------


Linda Liu said:
Hi Shaun,

To access public properties or invoke public methods of the control from
javascript in the web page, all we need to do is to build the control as a
COM class. To do this, right-click the project in the Solution Explorer and
choose Properties. In the Project Designer, select the Application tab and
click the 'Assembly Information' button on the right panel. In the Assembly
Information window, select the checkbox before the 'Make assembly
COM-Visible' option and press OK.

To expose events in the control to web pages and handle the events in the
web pages, we need to do more work. The following is the walkthrough.

1. Pack the events to be exposed into an interface, which is applied the
InterfaceTypeAttribute and then apply this interface to the control class.
The following is a sample.

[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IMyControlCOMEvents
{
[DispId(0x60020000)]
void HostIdentificationComplete();
}

[ComSourceInterfaces(typeof(IMyControlCOMEvents))]
public partial class MyControl2 : UserControl
{
.........
}

2. Because we need to handle the event in the script in the web page, we
need assign the control assembly embeded in the web page the permission to
call unmanaged code. To do this, follow the steps below.

a. Type 'mscorcfg.msc' in the SDK command to open .Net Framework 2.0
Configuration.

b. In the configuration, navigate to My Computer->Runtime Security
Policy->Machine->Permission Sets. Right-click on the LocalIntranet sub
node and choose 'Duplicate'. A new permission set called 'Copy of
LocalIntranet' is generated.

c. Right-click on the new permission set and choose 'Change Permissions'.
In the Create Permission Set window, double-click the 'Security' item in
the right listbox. In the 'Permission Settings' window, select the checkbox
before the 'Allow calls to unmanaged assembly' option. Press OK and then
Finish button to close the windows.

d. Navigate to My Computer->Runtime Security Policy->Machine->Code
Groups. Right-click on the 'All_Code' node and choose 'New'. In the 'Create
Code Group' window, select the 'Create a new code group' option and type a
name for the new group and press Next. In the 'Choose the condition type
for this code group' combobox, select 'URL' and type the web site url into
the URL textbox, e.g. http://localhost/mytest/* and press Next. Choose 'Use
existing permission set' option and select 'Copy of LocalIntranet' in the
combobox and press Next. Press Finish.

3. Because the assembly that load the assembly of our control into the web
page doesn't have the permission to call the unmanaged code, we must assign
this permission to the assembly. To do this, we call the Assert method of
the Securitypermission class. The lines of code you wrote in the
DoHostIndenticationComplete method are correct.

Please follow the above steps to solve your problem and let me know the
result.



Sincerely,
Linda Liu
Microsoft Online Community Support
 
L

Linda Liu [MSFT]

Hi Shaun,
I'm still having some problems with getting the control to load when I
have anything other than Full Trust.

Do you mean that the usercontrol couldn't be loaded when you change the
permission set of the web site other than Full Trust?

As far as I know, the problem that the usercontrol couldn't be loaded has
nothing to do with to the permission set the web site or usercontrol
assembly owns. Instead, there're two factors that may cause the problem.

One is that the 'Execute permissions' property of the virtual directory of
the web site is not set to 'Scripts only' (to set this property, open IIS
Manager, right-click the website, switch to 'Virtual Directory' tab in the
website's Properties page and select 'Scripts only' for the 'Execute
permissions' option).

The other is that you have signed the usercontrol assembly with a strong
named key file but haven't apply AllowParticallyTrustedCallersAttribute to
the assembly.
To apply this attribute to the assembly, add the following code to the
AssemblyInfo.cs file which is under Properties folder in your project.

using System.Security;
[assembly: AllowPartiallyTrustedCallers()]

Please have a check in your project according to the above suggestions. If
these suggestions don't solve your problem, you may follow the steps I
provided in my previous reply, in which the web site is with partial trust.
I have performed a test on these steps and it works.

I look forward to your reply.


Sincerely,
Linda Liu
Microsoft Online Community Support
 
R

roy

hi ,
same problem but no solution !
i found a lot of information , groups, msdn, etc ...
but i still have trouble with my control ....

i make a control like the one posted ...
and configured my CAS ...

i can intercept events only if set the
URL "MemberShip Conditions" of my Custom "Code Group" ....

from
http://localhost/web/*
to
http://localhost/*

i'm still going crazy ?!?!?!
any idea , suggestions ???
thanks in adavance to all

roy
 
G

Guest

Hi Linda,

I am back from my break now and have just got back to looking at finishing
this off.

My final control code is shown below.

It seems to work just fine however I'm still a little confused over the code
access security side of things. The control will only work if I give Full
Trust to the assembly (using a URL membership permission for example). Surely
I should be able to have a much reduced permission set - I just cannot figure
out what that is?!

Also, can you tell me how, when it is not able to be downloaded, I can have
the IE6 information bar tell the user this is the case?

Thanks again,

Shaun

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Security;

[assembly: ClassInterface(ClassInterfaceType.AutoDual)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode =
true)]
[assembly: AllowPartiallyTrustedCallers]
namespace MyDev.Common.React.ReactDeviceRegistrationControl
{
public delegate void SubmitClickedHandler();

[ComVisible(true)]
[Guid("67CD00DB-E9BC-484d-9033-83D41112EBD4")]
public interface ReactDeviceRegistrationCOMIncoming
{
string HostName { get; set; }
void GetHostName();
}

[ComVisible(true)]
[Guid("61CD00DB-E9BC-484d-9033-83D41112EBD4")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ReactDeviceRegistrationEvents
{
[DispId(0)]
void GetHostNameComplete();
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(ReactDeviceRegistrationEvents))]
[ComDefaultInterface(typeof(ReactDeviceRegistrationCOMIncoming))]
public partial class ReactDeviceRegistration : UserControl,
ReactDeviceRegistrationCOMIncoming
{

private string _hostname;

public ReactDeviceRegistration()
{
InitializeComponent();
}

[Category("Action")]
[Description("Fired when the Submit button is clicked.")]
public event SubmitClickedHandler GetHostNameComplete;

protected virtual void OnGetHostNameComplete()
{
if (GetHostNameComplete != null)
{
new
SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
GetHostNameComplete();
CodeAccessPermission.RevertAssert();
}
}

//[Category("Appearance")]
[Description("Gets or sets the name in the text box")]
public string HostName
{
get { return _hostname; }
set { _hostname = value; }
}

[Category("Action")]
[Description("Gets hostname of local machine")]
public void GetHostName()
{
_hostname = System.Net.Dns.GetHostName();
OnGetHostNameComplete();
}


}
}






Shaun Venus


Linda Liu said:
Hi Shaun,
I'm still having some problems with getting the control to load when I
have anything other than Full Trust.

Do you mean that the usercontrol couldn't be loaded when you change the
permission set of the web site other than Full Trust?

As far as I know, the problem that the usercontrol couldn't be loaded has
nothing to do with to the permission set the web site or usercontrol
assembly owns. Instead, there're two factors that may cause the problem.

One is that the 'Execute permissions' property of the virtual directory of
the web site is not set to 'Scripts only' (to set this property, open IIS
Manager, right-click the website, switch to 'Virtual Directory' tab in the
website's Properties page and select 'Scripts only' for the 'Execute
permissions' option).

The other is that you have signed the usercontrol assembly with a strong
named key file but haven't apply AllowParticallyTrustedCallersAttribute to
the assembly.
To apply this attribute to the assembly, add the following code to the
AssemblyInfo.cs file which is under Properties folder in your project.

using System.Security;
[assembly: AllowPartiallyTrustedCallers()]

Please have a check in your project according to the above suggestions. If
these suggestions don't solve your problem, you may follow the steps I
provided in my previous reply, in which the web site is with partial trust.
I have performed a test on these steps and it works.

I look forward to your reply.


Sincerely,
Linda Liu
Microsoft Online Community Support
 
G

Guest

Hi Linda,

I posted a reply the other day from my other alias (I was also given a
subscription to use at my current contract) in which I stated that I still
needed full trust.

Well, I have just got a new desktop there as my old one was doing some
pretty odd things and I can now use my own small permission set (just the top
3 security settings) for my specific URL and it all works great!

Having read the O'Reilly book on .NET Framework Security I had a more
complete picture and generated the xml for the permission set and used CASPOL
to import this and also to generate the Code Group to use it.

I do however have another question (/ problem) ...

When a machine does not have the correct security settings to load the
assembly I've used a try/catch to popup a message telling the user. This is
fine, but it would be nice if I could have the IE6 information bar tell the
user.
Can you shed any light on how this can be achieved, or if it is even
possible (if not how would I make a control that does this)?

Thanks once again,

Shaun


--------------------------
Shaun Venus
--------------------------


Linda Liu said:
Hi Shaun,
I'm still having some problems with getting the control to load when I
have anything other than Full Trust.

Do you mean that the usercontrol couldn't be loaded when you change the
permission set of the web site other than Full Trust?

As far as I know, the problem that the usercontrol couldn't be loaded has
nothing to do with to the permission set the web site or usercontrol
assembly owns. Instead, there're two factors that may cause the problem.

One is that the 'Execute permissions' property of the virtual directory of
the web site is not set to 'Scripts only' (to set this property, open IIS
Manager, right-click the website, switch to 'Virtual Directory' tab in the
website's Properties page and select 'Scripts only' for the 'Execute
permissions' option).

The other is that you have signed the usercontrol assembly with a strong
named key file but haven't apply AllowParticallyTrustedCallersAttribute to
the assembly.
To apply this attribute to the assembly, add the following code to the
AssemblyInfo.cs file which is under Properties folder in your project.

using System.Security;
[assembly: AllowPartiallyTrustedCallers()]

Please have a check in your project according to the above suggestions. If
these suggestions don't solve your problem, you may follow the steps I
provided in my previous reply, in which the web site is with partial trust.
I have performed a test on these steps and it works.

I look forward to your reply.


Sincerely,
Linda Liu
Microsoft Online Community Support
 
L

Linda Liu [MSFT]

Hi Shaun,

Sorry for my delayed reply.

When a machine does not have the correct security settings to load an
assembly and the assembly has been augmented with
SecurityPermissionAttribute to request the necessary permissions, this
control could not be loaded properly in IE, instead a blank picture is
displayed where the control should reside.

If we don't apply SecurityPermissionAttribute to the assembly, the control
could be loaded properly in IE because CLR doesn't check permissions when
loading the assembly. However, if a call that requires some permission
which the machine has not assigned to the assembly is invoked, e.g. click
the 'Get HostName' button to get the machine's name in your sample, an
exception is thrown.

As you mentioned, we could add try/catch block on the code that requires
the special permission to popup a messagebox to tell the user the error
message. If you want to show this error message at the IE status bar, I
think a possible way is to fire an event from the control and handle this
event in the web page which hosts the control to have the IE status bar
display the error message.

Note that in order to handle events of a control in the web page, we must
assign the permission of calling unmanaged code to the assembly. If the
assembly isn't assigned the permission of calling unmanaged code, this
solution won't work.

Hope this helps.
If you have anything unclear, please feel free to let me know.


Sincerely,
Linda Liu
Microsoft Online Community Support
 
G

Guest

Hi Linda,

Thanks for your reply.

With the try/catch, this is in the page load javascript method which calls
the GetHostName method so it shows an alert informing the user that the
control could not be loaded. This works OK, but I would like to know if it
is possible to have the IE information bar inform the user that the control
could not be loaded, as it does with many ActiveX components that try to
install when I browse the web.

Can you tell me how this is possible as I think I have the original query
sorted now and can get my events raised and handles as well as calling
methods in the control from javascript in the page.

If you could point me in the right direction it would be much appreciated.

Regards,

Shaun
--------------------------
Shaun Venus
--------------------------


sunev said:
Hi Linda,

I posted a reply the other day from my other alias (I was also given a
subscription to use at my current contract) in which I stated that I still
needed full trust.

Well, I have just got a new desktop there as my old one was doing some
pretty odd things and I can now use my own small permission set (just the top
3 security settings) for my specific URL and it all works great!

Having read the O'Reilly book on .NET Framework Security I had a more
complete picture and generated the xml for the permission set and used CASPOL
to import this and also to generate the Code Group to use it.

I do however have another question (/ problem) ...

When a machine does not have the correct security settings to load the
assembly I've used a try/catch to popup a message telling the user. This is
fine, but it would be nice if I could have the IE6 information bar tell the
user.
Can you shed any light on how this can be achieved, or if it is even
possible (if not how would I make a control that does this)?

Thanks once again,

Shaun


--------------------------
Shaun Venus
--------------------------


Linda Liu said:
Hi Shaun,
I'm still having some problems with getting the control to load when I
have anything other than Full Trust.

Do you mean that the usercontrol couldn't be loaded when you change the
permission set of the web site other than Full Trust?

As far as I know, the problem that the usercontrol couldn't be loaded has
nothing to do with to the permission set the web site or usercontrol
assembly owns. Instead, there're two factors that may cause the problem.

One is that the 'Execute permissions' property of the virtual directory of
the web site is not set to 'Scripts only' (to set this property, open IIS
Manager, right-click the website, switch to 'Virtual Directory' tab in the
website's Properties page and select 'Scripts only' for the 'Execute
permissions' option).

The other is that you have signed the usercontrol assembly with a strong
named key file but haven't apply AllowParticallyTrustedCallersAttribute to
the assembly.
To apply this attribute to the assembly, add the following code to the
AssemblyInfo.cs file which is under Properties folder in your project.

using System.Security;
[assembly: AllowPartiallyTrustedCallers()]

Please have a check in your project according to the above suggestions. If
these suggestions don't solve your problem, you may follow the steps I
provided in my previous reply, in which the web site is with partial trust.
I have performed a test on these steps and it works.

I look forward to your reply.


Sincerely,
Linda Liu
Microsoft Online Community Support
 
L

Linda Liu [MSFT]

Hi Shaun,

Thank you for your reply.

Generally speaking, the information bar is used to notify the user of
downloads and blocked pop-up windows.

I have spent some time on how to display a text on the information bar but
unfortunately, I haven't found an answer yet.

I am consulting this question in our inner discussion group. As soon as I
have any new finding, I will get it back to you.

By the way, I think you could show the information text on the status bar
of IE alternatively.


Sincerely,
Linda Liu
Microsoft Online Community Support
 
L

Linda Liu [MSFT]

Hi Shaun,

I have consulted the question of displaying text in the information bar in
our inner discussion group.

Unfortunately, the replies from our product engineers are that the
information bar doesn't support such a function at present.

Alternatively, I think you could display the text at the status bar or just
on the web page with an attractive color, e.g. red.

Hope this helps.
If you have any concerns, please feel free to let me know.


Sincerely,
Linda Liu
Microsoft Online Community Support
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top