In a Silverlight 4 app I'm trying to instantiate an object whose type isn't known until run-time, using this code:
Assembly assembly = Assembly.LoadFrom("Name.Of.Some.dll");
Type type = assembly.GetType("Full.NameSpace.And.ClassName");
object o = Activator.CreateInstance(type);
However, the Assembly.LoadFrom() call results in an exception:
{System.MethodAccessException: Attempt by security transparent method 'Mosaic.Layers.LayerParamChangeHandlerInfo.CreateParamHandler()' to access security critical method 'System.Reflection.Assembly.LoadFrom(System.String)' failed.
I've done some Googling for the error, but I still can't figure out why I'm getting the exception (something related to the assemblies being strongly signed, I believe) and, more importantly, how to solve the problem and create my object.
You are not allowed to call this method from your own code, cause its security critical and restricted to be used only internal in .NET Framework.
Do not use this member in your application. If you do, your code will throw a MethodAccessException. This member is security-critical, which restricts it to internal use by the .NET Framework for Silverlight class library.
The only available Load method for assemblies in Silverlight is Assembly.Load(string). If you want to dynamically load an assemblies, take a look at this approach.
Related
Let's say that I have a simple WPF or Winforms solution. To that solution I add a new project (based on a class library template , which I then reference in the main project) which is intended to be a data layer containing an entity framework data model. When I create the data model in the new project the connection string that it uses gets added to the app.config file of the main project in the solution.
Now let us say that I want to add two more projects to the solution (both of which will again be based on class libraries) to contain details of WCF services that I wish to use. In each case I add the WCF service by using the ADD Service Reference option from the right click context menu of the projects.
Unlike the data model project though the bindings for the service model get added to the local projects app.config file ass opposed to the app.config file of the main start-up project.
Should I simply copy those bindings to the start-up project's app.config file, or should I copy and then delete, or in fact should I be doing something completely different. Thus far trying combination of the first two suggestions I get error messages connected with endpoint configuration, however my knowledge of WCF is not really sufficiently good to fully understand the MSDN articles that the error list points me to.
Note that if the service references are added to the main project I get no errors whatsoever, so I figure this must be a configuration problem of some description.
Would anyone be able to provide the correct procedure for adding projects that essentially contain no more than a WCF service reference to an existing visual studio solution.
Edit
The screenshot below shows my main app.cofig file after having copied over the bindings configurations from the two service contracts. I'm not sure whether I should have commented out the bit that I did or not, I had thought that by doing so I might get rid of the blue squiggly underlines telling me the following (which I must admit to not understanding):
Warning The 'contract' attribute is invalid - The value 'ErsLiveService.IERSAPIService' is invalid according to its datatype 'clientContractType' - The Enumeration constraint failed.
You're likely getting the blue squigglies because the namespace ErsTestService is defined within the project in which you created the service reference. If the root namespace of that project is MyServiceReferenceProject then try changing the namespace to MyServiceReferenceProject.ErsTestService.IERSAPIService.
Can anybody shed any light on how I can use the precompiled protobuf-net serializer assembly with WCF and a client (not to serialize/deserialize in code) to speed up first use of a DTO type?
I have managed to gain a lot of petrformance improvement in my large WCF/WPF application by using protobuf-net vs. datacontractserializer. However, even though I can precompile a serialization assembly from my DTO's, I cannot make WCF or it's WPF Client use it. The web service process always takes a long time for any first call from that process involving a new DTO, presumably to generate a serialization assembly on the fly.
How can I instruct the WCF server and/or the WPF client to use my generated assembly?
On a related issue, I have properties of type SolidColorBrush in some DTO's and this makes the precompiler fall over with "No serializer defined for type: System.Windows.Media.SolidColorBrush".
I have some code to add this support to the protobuf-net model, but I cannot understand how to apply it (to the precompiler or my code), when the rest of the DTO's are decorated with attibutes e.g. ProtoContractAttribute.
Any help much appreciated
At the moment, the only way to make WCF use a precompiled model would be configure WCF manually through code, in particular adding a ProtoOperationBehavior manually, and specifying the model:
var behavior = new ProtoOperationBehavior();
behavior.Model = new MyPrecompiledSerializer();
I confess I don't have a full end-to-end WCF example of doing that. I suspect it may be easier for me, in a new release, to tweak ProtoBehaviorExtension and/or ProtoBehaviorAttribute to allow you to specify the custom serializer-type via configuration - but that code does not exist today.
In the interim, if the issue is a slight delay on the first operation, then you can also add a few of the types you need exlicitly toe the default model, and compile it:
RuntimeTypeModel.Default.Add(typeof(Foo), true);
RuntimeTypeModel.Default.Add(typeof(Bar), true);
RuntimeTypeModel.Default.CompileInPlace();
that said: the compilation isn't horrendously slow - I'd be a little surprised if it is causing noticeable delay, unless your model is really complex (hundreds of types). Is it possible the delay is just WCF, network, TCP, etc overheads?
Regarding SolidBrush, and by implication: Color - it is possible to configure them at runtime:
RuntimeTypeModel.Default.Add(typeof(System.Windows.Media.Color), false)
.Add("R", "G", "B", "A");
RuntimeTypeModel.Default.Add(typeof(System.Windows.Media.SolidColorBrush), false)
.Add("Color");
However, I have not yet added a mechanism to do this when using "precompile" - it is much trickier at the technical level: I can't just use an executable method on (say) an attribute, because the assembly being inspected by "precompile" could be for any CLI (Silverlight, WinRT, .NET 1.1, CF, etc) - and as such, it is loaded by very different mechanisms.
My preferred approach would be: don't expose it as System.Windows.Media.Color - write your own DTO class that represents the data (rather than the final implementation), and map between them. Alternatively, it is also possible to write your own utility console exe that acts like "precompile", by configuring the model then calling RuntimeTypeModel.Default.Compile(string,string) or RuntimeTypeModel.Default.Compile(CompilerOptions).
I have a large object structure that I'm wanting to share between a .Net4 backend and a Silverlight 5 front end. I've created two class library projects of the appropriate type, and have my object structure implemented in the .Net library, and linked into the SL library. On the Silverlight client side I am referencing the Silverlight class library. When I generate the service reference I have checked the option to "Reuse types in referenced assemblies". However when I generate the service reference I am finding that types that are in referenced assemblies are still being generated. It is only certain types, and appears to be largely collection types (attributed with <CollectionDataContract>).
I have a main object that has many properties which are generally either List<MyTypeA> or in some cases they are MyListTypeB, where MyListTypeB inherits from List<MyTypeB>. It seems to be the classes similar to MyListTypeB that are causing the proxies to be generated. These are all attributed with <CollectionDataContract> and have a default constructor.
I also find that even though the project where I am adding the service reference to has a reference to the other SL project containing the entities, when I update the service a new reference directly to the dll is also being added to the project. I'm not sure why this is happening, or if it is causing confusion in the service proxy generation
Is there any way to tell what classes/properties are causing the service generation to generate proxy classes? Or is it a case of trial and error having to comment out attributes until they aren't generated and hone in on the problem class?
I have now found out about the use of the svcmap file, and updating the CollecitonMappings elements to include my collection types, described here:
http://mostlydevelopers.com/blog/post/2009/12/14/Configure-WCF-Service-ndash3b-Reuse-Collection-Types-Issue.aspx
It seems a little unusual that the svcmap functionality is so undocumented.
I was able to add an entry int he svcmap file similar to the following:
<CollectionMappings>
<CollectionMapping TypeName="MyNamespace.MyType" Category="List" />
</CollectionMappings>
And then when I updated the service reference the proxy collections are not generated.
David Betz describes in his article how to create reference to WCF without using "Add Service Reference" option:
http://www.netfxharmonics.com/2008/11/Understanding-WCF-Services-in-Silverlight-2
Once WCF service is created, these are the statements within the silverlight:
BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
EndpointAddress endpointAddress = new EndpointAddress("http://localhost:1003/Person.svc");
IPersonService personService = new ChannelFactory<IPersonService>(basicHttpBinding, endpointAddress).CreateChannel();
...
How does one references the types (such as IPersonService interface) created in WCF from Silverlight when I do not use "Add Service Reference" to buid proxies?
Idea is to reference assemblies that contain WCF data contracts in silverlight application, and to do that you need to fool VS so it thinks assembly is a SL assembly, he describes this in detail here
http://www.netfxharmonics.com/2008/12/Reusing-NET-Assemblies-in-Silverlight
and its not so easy, here is what needs to be done
Just use the same ILDasm/Edit/ILAsm
procedure already mentioned to tell
the assembly to use the appropriate
Silverlight assemblies instead of the
.NET assemblies. This is an extremely
simple procedure consisting of nothing
more than a replace, a procedure that
could easily be automated with very
minimal effort. It shouldn't take you
much time at all to write a simple
.NET application to do this for you.
It would just be a simple .NET to
Silverlight converter and validator
(to test for assemblies not supported
in Silverlight). Put that application
in your Post Build Events (one of the
top 5 greatest features of Visual
Studio!) and you're done. No special
binary hex value searching necessary.
All you're doing is changing two well
documented settings (the public key
token and version).
Second solution is a file level solution , you use add link option on files that contain your required data contracts implementations to SL and make sure they only contain types that allow to build SL and dont reference a lot of external assemblies , usually those conditions should be met for WCF services & data contracts.
I can write more but it would be just the copy paste from that link
You also have to split all methods declaration in you IPersonService according to Async pattern (BeginXXX/EndXXX) since Silverlight supports only asyncronous WCF (even in background threads).
As a help to do this, you may add Service Reference, then copy generated IPersonService (all methods will be decoupled) from Reference.cs. Then you may remove the reference.
However, if your service contract is often changed, you have to repeat Add-Service procedure again, and starting from this, I would say, it's easier just use Add-Service-Reference feature, rather than sharing the contract with your app server.
Only one thing that I would like detect. Often you need in namespaces with more complex support of NET within your WCF service. Therefore you must have real reasons to reference to Silverlight subset within your WCF service (or service library). There are many ways to
use so named traditional ways by Add Service Reference. They are presented in good article enter link description here.
Is there any cost/drawback (apart from typing too much) to adorning a class with System.Runtime.Serialization attributes (like [DataContract]) such that it can be used locally as a direct reference to a desktop Client project or as a type for a WCF service? The goal here is to write a data-tier class that can be used in both rich client (WPF) and Web scenarios. My data classes will be in a project that is separate from Client and WCF (*.svc code-behind) code. Is this a valid attempt to reuse code?
Adorning a class, property, or method does not incur any cost - except of the time it takes to write the attribute. The attribute will be complied into the metadata of the type, and then is used by another component to implement additional functionality.
The only drawback I can see is the cost of including attributes in the assembly. They have very little performance impact unless they are used.
I would say none but it does make the .DLL larger and does spread the RTTI in the assembly out a bit which, especially if you push a class over a read block boundary, could slow down assembly load (causing a couple extra blocks to be read that wouldn't have been otherwise). These differences are usually only noticable in cold start testing, however.