How to load a dll in an AppDomain with different NET version - appdomain

I have some third party assembly which was build using Net 2.0. Although I can of course reference that assembly in net 4, running the app results in all kinds of strange errors.
So I though loading it in a separate application domain will fix the problem but it does not. I assume it is still executed using the Net 4 runtime. Is there any way to force execution of an application domain in a different net version ?
I use CreateInstanceFromAndUnwrap and than call the proxy.
Thanks for any help
Joe

You can use the supportedRuntime configuration element to set the CLR version of an AppDomain. If you do not want to add this to your app.config, you can add a second .config file that will be used during the construction of the new AppDomain. Have a look at AppDomainSetup.ConfigurationFile for more info.

Create AppDomain. And Create DomainManager:MarshalByRef object in new domain.
DomainManager Load Assembly To created(new) domain.
AppDomainSetup ads = new AppDomainSetup();
AppDomain managerAD = AppDomain.CreateDomain("AD1", null, ads);
Assembly asm = managerAD.Load(typeof(DomainManager).Assembly.FullName);
string typeName = typeof(DomainManager).FullName;
DomainManager manager = (DomainManager)managerAD.CreateInstanceAndUnwrap(asm.GetName().Name,
typeName);
public class DomainManager : MarshalByRefObject
{
public void GetAppDomain(string assemblyFileName)
{
Assembly asm2 = Assembly.LoadFrom(assemblyFileName);
Type neededType = asm2.GetType(<paste type>);
object instance = Activator.CreateInstance(procType);
}

Related

Registering .net assembly for COM succeeds with regasm but fails using RegistrationServices.RegisterAssembly

This is one of the strangest issue I have encountered.
There is a .net assembly, which is exposed to COM.
If you register it with regasm /codebase my.dll - it is sucessfully registered, and can be used.
However, if you register it from code using RegistrationServices.RegisterAssembly() :
[...]
RegistrationServices regSvcs = new RegistrationServices();
Assembly assembly = Assembly.LoadFrom(path);
// must call this before overriding registry hives to prevent binding failures on exported types during RegisterAssembly
assembly.GetExportedTypes();
using (RegistryHarvester registryHarvester = new RegistryHarvester(true))
{
// ******** this throws *********
regSvcs.RegisterAssembly(assembly, AssemblyRegistrationFlags.SetCodeBase);
}
Then it throws exception:
Could not load file or assembly 'Infragistics2.Win.UltraWinTree.v9.2, Version=9.2.20092.2083,
Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb' or one of its dependencies.
Provider type not defined. (Exception from HRESULT: 0x80090017)
This error has very little resource on the net, and looks like related to some security(?) cryptography(?) feature.
After long-long hours, I figured out what causes this (but don't know why):
If there is a public class with a public constructor in the assembly with a parameter UltraTree (from the referenced assembly 'Infragistics2.Win.UltraWinTree.v9.2'), then you cannot register from code, but with regasm only.
When I changed the have a public function Init(UltraTree tree), then it works, I can register from code. So:
// regasm: OK / RegistrationServices.RegisterAssembly(): exception
public class Foo
{
public Foo(UltraWinTree tree) { .. }
}
Foo foo = new Foo(_tree);
-------------- vs --------------
// regasm: OK / RegistrationServices.RegisterAssembly(): OK
public class Foo
{
public Foo() {}
public void Init(UltraWinTree tree) { .. }
}
Foo foo = new Foo();
foo.Init(_tree);
So I could workaround by passing UltraWinTree in a new Init() function instead of constructor, but this is not nice, and I want to know the reason, what the heck is going on?
Anyone has any idea? Thanks.
PS:
Okay, but why we want to register from code? As we use Wix to create installer, which uses heat.exe to harvest registry entries (which are added during asm registration), so heat.exe does assembly registration from code.
I've been dealing with this for years so this is the only answer you need to read:
Heat calls regasm /regfile. So does InstallShield when you tell it to. If you read this page:
https://learn.microsoft.com/en-us/dotnet/framework/tools/regasm-exe-assembly-registration-tool
There's a very important caveat in the remarks section.
You can use the /regfile option to generate a .reg file that contains
the registry entries instead of making the changes directly to the
registry. You can update the registry on a computer by importing the
.reg file with the Registry Editor tool (Regedit.exe). The .reg file
does not contain any registry updates that can be made by user-defined
register functions. The /regfile option only emits registry entries
for managed classes. This option does not emit entries for TypeLibIDs
or InterfaceIDs.
So what to do? Use Heat to generate most of the metadata. Then on a clean machine, (snapshot VM best) us a registry snapshot and compare tool such as InCntrl3 or InstallWatch Pro and sniff out what additional meta regasm writes to the registry. Finally massage that into your Wxs code.
Then on a cleam machine test the install. The result should work and not require any custom actions in the install.

Using Kentico API from LINQPad is throwing an exception

I am trying to call Kentico API from LINQPad, but getting the following exception:
[AbstractProvider.GetProvider]: The object type 'cms.document' is missing the provider type configuration
My code is:
void Main()
{
var pages = DocumentHelper.GetDocuments("CMS.MenuItem").Path("/", PathTypeEnum.Children);
pages.Dump();
}
Note: I tested the code from Visual Studio, it works, but not from LINQPad.
The problem is that during the initial discovery Kentico looks only at the following paths:
AppDomain.CurrentDomain.BaseDirectory
AppDomain.CurrentDomain.RelativeSearchPath
Which in case of LINQPad are C:\Program Files (x86)\LINQPad4\ and null. Therefore the providers do not get resolved.
I've tried running the code in a new AppDomain but it doesn't seem to work in LINQPad. I suggest submitting this to Kentico as an idea or an issue.
A workaround to this would be copying the LINQPad executable to a location of Kentico DLLs - e.g. C:\inetpub\wwwroot\Kentico82\Lib. That works just fine.
Update (thx to Joe Albahari):
If you wrap your code in this:
var appDomain = Util.CreateAppDomain ("AD", null, new AppDomainSetup
{
PrivateBinPath = #"C:\inetpub\wwwroot\Kentico82\CMS\bin",
});
appDomain.DoCallBack(() => { /* your code */ });
you'll be able to execute it. However, you can't Dump() it to the output window. But you can write it to a text file for example. If you experience the following error:
FileNotFoundException: Could not load file or assembly 'LINQPad, Version=1.0.0.0, Culture=neutral, PublicKeyToken=21353812cd2a2db5' or one of its dependencies. The system cannot find the file specified.
Go to Edit -> Preferences -> Advanced -> Run each query in its own process and turn it off.

Can I reference a DataContract and its proxy version from same class

I'm dipping my foot into WCF and am trying to make a simple test project that can both consume the service as a service and also directly instantiate it's classes and work with them.
I had an earlier working version where data passed was just primitive types. However, when I attempted to convert to using data contracts, I'm getting conflicts in whether it's referencing the proxy-declared version of the contract or the version from the project itself.
Question: Is it possible to do this and if so, how would I resolve the data contract references?
private void Test()
{
MyService fssDirect = new MyService(); // direct instantiation
MyServiceClient fssService = new MyServiceClient(); // Service proxy
ClientCredentialsContract Client = new ClientCredentialsContract();
ResponseDataContract Result = new ResponseDataContract();
if (CallAsService)
{
Result = fssService.Create(Client, Request);
}
else
{
Result = fssDirect.Create(Client, Request);
}
}
In the above, any reference to the RequestDataContract and ClientCredentialsContract types indicates
Warning: The type 'MyContracts.RequestDataContract' in 'C:...\Test\MyServiceProxy.cs' conflicts with the imported type 'MyContracts.RequestDataContract' in 'C:...\MyService\bin\Debug\Contracts.dll'. Using the type defined in 'C:...\Test\MyServiceProxy.cs'.
(Names changed and paths shortened to protect the innocent)
Thanks,
John
When you create the proxy for your service, try referencing the assembly which contains the data contracts (if using "Add Service Reference", go to the advanced options, select "reuse types in referenced assemblies"; if using svcutil, use the /r argument). This way the tool won't generate the data contracts and you won't have the conflicts.

WCF Service Reference Will not compile

I currently have a simple WCF service with the following operation:
[OperationContract]
int InsertApplication(Application application);
The Application Parameter is defined as follows:
[DataContract]
public class Application
{
int test = 0;
[DataMember]
public int Test
{
get { return test; }
set { test = value; }
}
}
This service is being consumed within a Windows service with a namespace SpringstoneColoAgent. I added a service reference with no problems called OfficeInternalService. The code that calls the service method is as follows:
Application application = new Application();//= ConvertToApp(app);
application.Test = 1;
int oracleID = client.InsertApplication(application);
However, visual studio is telling me that 'application' is an invalid parameter. On further research I try to build anyway. I get a bunch of errors pointing to the Reference.cs file. Looking at this file I determine all the errors revolve around code that uses the following:
SpringstoneColoAgent.OfficeInternalService._
Where anything it is trying to reference under the service reference name is incorrect. So for example this code is giving an error:
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IOfficeInternalService/InsertApplication", ReplyAction="http://tempuri.org/IOfficeInternalService/InsertApplicationResponse")]
int InsertApplication(SpringstoneColoAgent.OfficeInternalService.Application application);
If I do not fully qualify the namespace and remove SpringstoneColoAgent.OfficeInternalService. so that the code looks like this:
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IOfficeInternalService/InsertApplication", ReplyAction="http://tempuri.org/IOfficeInternalService/InsertApplicationResponse")]
int InsertApplication(Application application);
This will fix the error. I repeated this everywhere I could find the error and everything compiled fine. The downside is that everytime I make a change to the WCF service and need to update the service reference it loses these changes and I have to go back and change them.
I'm guessing I am missing something here and was curious if anyone had any direction or has run into a similar situation.
Thanks for any advice!
The Application class is a known .NET type: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.aspx. Try to work with a different class name to avoid name clashes.
Also try to avoid the int private member in the datacontract. Because it is not a datamember, it is not exposed in the WSDL and a generated proxy class on the client side does not know this private member. This can also cause problems.

How to read xml file from a relative path in RIA Service?

I am trying to read an XML file in RIA Service and I am getting the following error.
Load operation failed for query 'GetSummaryList'. Could not find a part of the path 'C:\WINDOWS\SYSTEM32\CoreResources\SumaryListDS.xml'.
I am using Silverlight 4 which is using RIA service. I am trying to read the SumaryListDS.xml located in the bin\CoreResources folder. But the application insted of looking for the file under bin\CoreResources, its trying to read it from C:\WINDOWS\SYSTEM32\CoreResources.
I am just wondering how to read a file using relative path in RIA Service with Silverlight front end?
Thanks,
Vinod
You should be able to use .. to go up one directory, such as ../CoreResources/GetSummaryList.xml
Here is how I resolved my problem. Its been implemented in one of the layers of business tier, which can be used by variety of clients (ASP.NET, Console App, Windows Client, Silverlight hosted inside ASP.NET). So when GetSummaryXml is called, previously it used to be
public DataSet GetSummaryXml()
{
var dsReport = new DataSet("Report");
var summaryListXmlPath = "CoreResources/SumaryListDS.xml";
dsReport.ReadXml(summaryListXmlPath);
return dsReport;
}
I started getting an error when I started consuming it in RIA Domain Service to be used by Silverlight 4 client.
ERROR:
Load operation failed for query
'GetSummaryList'. Could not find a
part of the path
'C:\WINDOWS\SYSTEM32\CoreResources\SumaryListDS.xml'.
But SumaryListDS.xml located in the bin\CoreResources, not WINDOWS\SYSTEM32\CoreResources
So I modified GetSummaryXml to...
public DataSet GetSummaryXml()
{
var dsReport = new DataSet("Report");
var currContext = HttpContext.Current;
var summaryListXmlPath = "CoreResources/SumaryListDS.xml";
if (currContext != null)
summaryListSchemaPath = currContext.Server.MapPath(#"../bin/" + summaryListXmlPath);
dsReport.ReadXml(summaryListXmlPath);
return dsReport;
}
And now its working fine. I am not sure if this is a perfect solution thou.