Leggendo sui newsgroup Microsoft del CRM 3.0 mi sono imbattuto su un post che spiegava, con tanto di esempio, come deve essere realizzato un assembly in modo che possa essere richiamato da codice JavaScript utilizzato da IE. Ovviamente questo ha poco a che fare col CRM ma può risultare utile in molti casi, visto che molto del codice che gestisce l'interfaccia utente è scritto in JavaScript.
Allora, Michael, autore del post allega questo esempio:
JavaScript doesn't know anything about .NET, but it knows COM and new
ActiveXObject is the way to create an instance of a COM class. For a simple
test, you can create a .NET assembly (class library) and insert the
following code as a template:
public abstract class SafeObject : IObjectSafety {
public int GetInterfaceSafetyOptions(ref Guid riid, out int
pdwSupportedOptions, out int pdwEnabledOptions) {
pdwSupportedOptions = 0;
pdwEnabledOptions = 0;
return 0;
}
public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int
dwEnabledOptions) {
return 0;
}
}
[ComImport]
[Guid("CB5BDC81-93C1-11CF-8F20-00805F2CD064")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IObjectSafety {
[PreserveSig]
int GetInterfaceSafetyOptions(ref Guid riid, out int
pdwSupportedOptions, out int pdwEnabledOptions);
[PreserveSig]
int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int
dwEnabledOptions);
}
Create a test class deriving from SafeObject like the following:
[ComVisible(true)]
[Guid("45F498CE-372D-4b2b-8E61-CFA97180FDE6")] //replace this with a new
Guid
[ClassInterface(ClassInterfaceType.None)]
[ProgId("myNamespace.myClass")] //replace this with a new prog id - this is
the name you pass to new ActiveXObject
public class MyClass : SafeObject, IMyClass {
public MyClass() {
}
public void Test() {
System.Windows.Forms.MessageBox.Show("Hello World");
}
}
[Guid("F157577E-7958-421b-B623-2108A56B26D5")] //replace with a new Guid
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IMyClass {
void Test();
}
Spiegando che:
Yes, you can use .NET assemblies on the client. You need to implement the
IObjectSafety interface to mark the code as sdafe for scripting, preventing
unwanted security warnings from IE. You should mark the classes you want to
use with ComVisible(true), and give them a unique classid and progid.
In JavaScript you instantiate your class like a usual COM object: var
myClass = new ActiveXObject("yourNamespace.yourClassName").
Che dire oltre? Grazie Michael