Dynamics CRM 2013: Inheritance security rules violated while overriding member - dynamics-crm-2013

I created a quite simple plugin for Dynamics CRM 2013 that should populate some attributes based on some other attribute values.
The following error message occurs when query data:
Unexpected exception from plug-in (Execute):
Foobar.IsoCountry.Plugins.PreAddressCreateUpdate: System.TypeLoadException: Inheritance
security rules violated while overriding member:
'Microsoft.Crm.Services.Utility.DeviceRegistrationFailedException.GetObjectData(System.Runtime
.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'.
Security accessibility of the overriding method must match the security accessibility of
the method being overriden.
The code is quite simple:
var context = localContext.PluginExecutionContext;
var orgServiceSystem = localContext.OrganizationServiceAsSystem;
var target = this.GetTargetEntity(context).ToEntity<Account>();
using (var xrm = new XrmContext(localContext.OrganizationServiceAsCallingUser))
{
var list = from account in xrm.AccountSet where account.Name.StartsWith("foobar")select account;
///...
}
I am using the lasts SDK Version (6.1.1) and targeting Dynamics CRM Online (Spring Wave Update is installed).
The only think that might be a bit special, is the fact that I am usiong ILMerge to combine multiple dll into my plugin.dll.

Solved, I used an dedicated Visual Studio project for the data-access (repository pattern) and part of this project was a class (BaseXrmFactory) that used the "DeviceIdManager" class("DeviceIdManager.cs"; part of the SDK).
The class was used to created new instances of the org-service:
...
private ClientCredentials GetDeviceCredentials()
{
return Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
}
...
Via ILMerge was this project include in my plugin-dll that was deployed to the CRM. Once I removed the class (DeviceIdManager) the plugin executed as expected :)
I do not fully understand way this was the problem because the BaseXrmFactory was NOT invoked as part of the plugin execution.

I had two plugins first with Isolation mode Sandbox and second with isolation mode None. I set all isolation mode to none and after all working correctly.

Related

Can I create an object from the DI container/Lamar in .NET 6.0 minimal hosting, preserving singletons?

We have migrated from a windows Framework 4.7 application to .NET 6.0. Lamar is added for Dependency Injection. We are trying to finalize a refactor to the latest "one-file" program.cs but are getting unexpected System.ObjectDisposedException: 'Cannot access a disposed object'. In all cases, the error is against a Func<T> during object creation.
All our tests are running correctly using the same environment, except to start the tests we (a) create the DI container and (b) use the container to create an object that loads the singletons (from MongoDB):
Container = new Container(registry);
var start = Container.GetInstance<HomeService>();
In the program.cs, we configure the container, but do not get to see it created, or access it inside program.cs. Instead we create HomeService from IServiceProvider during the first use of a controller. Here we were trying to limit the lifecyle scope during creation:
using (var scope = _container.CreateScope())
{
scope.ServiceProvider.GetService<INewHomeService>();
}
For test, we use the same loading steps, except for adding controllers/mvc, of course (i.e. NOT using builder.Services.AddControllers(); and builder.Services.AddMvc() for (integration) testing).
We have tried a lot of different things, like creating our object independently to the startup, but that did not align the singletons. We can get functionality by using static instead, but then we lose dynamic change access.
Some great tips like Resolving instances with ASP.NET Core DI from within ConfigureServices and https://andrewlock.net/exploring-dotnet-6-part-10-new-dependency-injection-features-in-dotnet-6/ but I can't see the specific example to get the live container just after initial creation.
Is it possible that the issue is just the difference between the lifecycle management of the new .NET DI implementation? As this is configuration at the composition root, if we can configure as per our testing approach, it should solve our problem. Other solutions welcome!
The problem 'Cannot access a disposed object' was being caused by a lifecycle mismatch between retained context and the controller access. The code retained a handle on the state object, that had a handle on the factory using FUNC. As we did not configure the Func as anything, it was transient during the controller graph creation, and so was disposed when the controller request ended.
To solve, we tried registering ALL of the FUNC, per How to use Func<T> in built-in dependency injection which was a large task as we had a few factories throughout an old codebase.
The better solution was to create a factory in the composition root, and use an injected IserviceProvider (or with Lamar an IContainer). This is a simple workaround.
With our creation concern, the creation of our object after the completion of the startup process is working correctly as a lazy validation of the first controller access.

.net Core 2.0 OData - EnableQuery attribute not allowing operations

I am trying to use Microsoft.AspNetCore.OData, v7.0.0.0-beta1, in a simple project.
I am failing to filter, select, and use top or skip.
Overriding the ValidateQuery of the EnableQueryAttribute, I can successfully perform these type of operations so I believe the library is buggy.
I could not find the right channel to report the issue, can anyone help?
The sample code to reproduce is available here: https://github.com/norcino/AspNetCoreSamples/tree/master/SampleODataApp
The solution to the problem was the actual initialization of the MVC route builder.
Like in the .net framework version it is possible to specify which operation is allowed for OData query. In the example below I am whitelisting everything but you can do a more fine tuning passing an instance of QueryOptionSetting.
app.UseMvc(routeBuilder =>
{
routeBuilder
.Select()
.Expand()
.Filter()
.OrderBy(QueryOptionSetting.Allowed)
.MaxTop(2000)
.Count();
routeBuilder.EnableDependencyInjection();
});
Note that, the attribute [HttpGet, EnableQuery(AllowedOrderByProperties = "Id")], will effectively enforce the order by to the sole Id property specified in the attribute, but first you need to enable all from the configuration.

Task based asynchronous operation disabled in PCL Service Reference setting

I'm currently building a Xamarin based mobile application. For that project, I have created a PCL project with framework 4.5. I'm using VS 2013 as the development IDE. Now I want add a WCF service reference to this PCL. While adding service reference to this PCL project, I noticed that generation of asynchronous operation is disabled. Please check the image for more detail.
I added the BCL.Async package via Nuget to the project. But still I can't access the Task based operation from the radiobutton list (its disabled).
So is there any way to generate task based asynchronous operation in service client?
Hate to break it to you but you cannot generate Task based WCF client in Xamarin. The reason is Xamarin or Mono implements the Silverlight set which is a limited WCF implementation. As such you need to use SLSVCUTIL.exe instead(Adding a service reference in Xamarin would use this tool). The silverlight WCF client generated by SLSVCUTIL will be async based only.
All is not lost! You can easily wrap the silverlight async client into a task based client using the Task.FromAsync method.
A sample taken from the Xamarin website:
public async Task<List<TodoItem>> RefreshDataAsync ()
{
...
var todoItems = await Task.Factory.FromAsync <ObservableCollection<TodoWCFService.TodoItem>> (
todoService.BeginGetTodoItems,
todoService.EndGetTodoItems,
null,
TaskCreationOptions.None);
foreach (var item in todoItems) {
Items.Add (FromWCFServiceTodoItem (item));
}
...
}
https://developer.xamarin.com/guides/xamarin-forms/web-services/consuming/wcf/
Now if someone can figure out how to catch an Fault Exception when wrapping in Tasks that would be awesome!
I've not used Xamarin before, but I'll assume APM and maybe Tasks are actually supported in it and this is just a Visual Studio limitation. Try using wsdl.exe manually to generate code. This is the tool Visual Studio calls when you add a service reference.
You'll need to pass either newAsync (Tasks) or oldAsync (APM) through the /parameters switch.

API modularization in Restlet

I have developed a web application based on Restlet API. As I am adding more features over time, I need sometimes to reuse similar group of REST API under different endpoints, which provides slightly different context of execution (like switching different instances of databases with same schema). I like to refactor my code to make the API reusable and reuse them at different endpoints. My initial thinking was to design an Application for each reusable API and attach them on the router:
router.attach("/context1",APIApplication.class)
router.attach("/foo/context2",APIApplication.class)
The API should be agnostic of configuration of the REST API. What is the best way to pass context information (for example the instance of database) to the Application API? Is this approach viable and correct? What are the best practices to reuse REST API in Restlet? Some code samples would be appreciated to illustrate your answer.
Thanks for your help.
I have see this basic set-up running using a Component as the top level object, attaching the sub applications to the VirtualHost rather than a router, as per this skeleton sample.
public class Component extends org.restlet.Component
{
public Component() throws Exception
{
super();
// Client protocols
getClients().add(Protocol.HTTP);
// Database connection
final DataSource dataSource = InitialContext.doLookup("java:ds");
final Configuration configuration = new Configuration(dataSource);
final VirtualHost host = getDefaultHost();
// Portal modules
host.attach("/path1", new FirstApplication());
host.attach("/path2", new SecondApplication(configuration));
host.attach("/path3", new ThirdApplication());
host.attachDefault(new DefaultApplication(configuration));
}
}
We used a custom Configuration object basically a pojo to pass any common config information where required, and used this to construct the Applications, we used separate 'default' Contexts for each Application.
This was coded originally against restlet 1.1.x and has been upgraded to 2.1.x via 2.0.x, and although it works and is reasonably neat there may possibly be an even better way to do it in either versions 2.1.x or 2.2.x.

Ambiguous reference in WCF and client application

I've managed to reproduce one of the errors in a test project with a similar structure to my production code. It consists of three simple projects:
Common (class library):
namespace Common
{
public enum PrimaryColor
{
Red,
Green,
Blue
};
}
Library (WCF service library), which has a reference to Common:
using Common;
namespace Library
{
[ServiceContract]
public interface ILibrary
{
[OperationContract]
PrimaryColor GetColor();
}
public class Library : ILibrary
{
public PrimaryColor GetColor()
{
return PrimaryColor.Red;
}
}
}
ClientApp (console application), which has a reference to Common, and a service reference to Library called "LibraryServiceReference":
using Common;
using ClientApp.LibraryServiceReference;
namespace ClientApp
{
class Program
{
static void Main(string[] args)
{
LibraryClient client = new LibraryClient("WSHttpBinding_ILibrary");
PrimaryColor color = client.GetColor();
}
}
}
The app.config files in ClientApp and Library are auto-generated and I have not modified them, and I have not changed the default configuration for the LibraryServiceReference in ClientApp.
When I compile this solution, I get the following errors in the ClientApp project:
Error 1
'PrimaryColor' is an ambiguous reference between 'Common.PrimaryColor' and 'ClientApp.LibraryServiceReference.PrimaryColor'
Error 2
Cannot implicitly convert type 'ClientApp.LibraryServiceReference.PrimaryColor' to 'Common.PrimaryColor'. An explicit conversion exists (are you missing a cast?)
please help me to fix this.
Make sure that 'Reuse types in all referenced assemblies' is selected in the Advanced options of Add service reference or Configure Service Reference.
it's because you're building x64 not "AnyCpu". I am running across this right now, and am trying to figure out if it's a bug, or if it's expected behavior.
Decorate your enum like this:
namespace Common
{
[DataContract]
public enum PrimaryColor
{
[EnumMember]
Red,
[EnumMember]
Green,
[EnumMember]
Blue
};
}
Update Your service reference (with checking reuse types just like Mark stated).
Rebuild your client code.
I have had this issue arise in innocuous, unpredictable manners so many times! I thought I'd share how I "fixed" it this last time.
I am using Visual Studio 2013 - but have had the issue down rev.
The ambiguous reference seems to come on by itself. I did nothing of note to cause it. In the latest instance I was debugging some code behind and suddenly I had 7, then 22 then 49 errors - all of the same nature.
I deleted the service reference altogether and re-added it. Simply modifying the re-use type did nothing. My solution has a WCF service, Class Library, UI and a Control Library. I also removed the using - in some code behind, of the class library.
This is an exceptionally troublesome issue which thankfully only occurs about every few weeks. Why this worked? Beyond my pay grade. I feel your pain! Hope this helps. In this case, the error came on, again, when I opened some code behind on a xaml page.
It sounds like you control both the client and the server code. Why do you want to create a service reference, is there a specific reason or is it just deemed easier?
In projects where you control both sides of the client server application you are better of creating a "contract assembly" (which is probably your common assembly). This contains the interfaces and objects that are involved with the contract and should be referenced by both your client and your server. In order to communicate with the service the client creates a proxy class using the ChannelFactory, there is no need to have a dedicated WCF client.
Example:
ChannelFactory<ISampleService> factory = new ChannelFactory<ISampleService>("Binding_from_config");
ISampleService sampleService = factory.CreateChannel();
sampleService.SomeCall();
factory.Close();
The factory pattern also makes it an ideal candidate for injecting your proxy in via IoC.
The benefits of referencing a common assembly over creating a service reference are:
No ambiguous reference as there will be no need for auto generated classes.
You will not have to update your service reference every time you change the contract.
For what it's worth, I was running in to this same error after moving my data contracts to a separate library. Updated the service references multiple times and tried all combinations of the settings for assembly reuse, to no avail.
What eventually fixed it for me was to 1) restart Visual Studio and 2) update the service reference. The auto-generated code in Reference.cs in the service definition looked very different and did not duplicate my data contract class. It used the proper reference from my library. So something must be getting cached in the IDE.
Hopefully someone else finds this useful.
I was able to fix this by right-clicking on the Service Reference and then changing from "Reuse types in all referenced assemblies" to "Reuse types in specified referenced assemblies" and then checking the specific common assembly.
Just remove the reference to Common project from your ClientApp project and the error should go away. When you're creating a proxy for your service, all dependent code from the service must be injected into the proxy. If you want your types to be same as those on the service side, just enable the 'Reuse types' option while generating the proxy code (otherwise they will be put under a different namespace).
The problem here is that PrimaryColor exists in both Common and ClientApp.LibraryServiceReference and you are referencing both namespaces in your class.
To overcome this issue, either explicitly reference the instance that you require, i.e.
Common.PrimaryColor color = ....
or set up an alias:
using Service = ClientLibraryServiceReference;
...
Service.PrimaryColor color = ......
When making the service reference aren't there some options that say something like: "inlcude common types in generated service contract" ?
I have the idea that in your service reference the classes are "copied" and that's why you get this error. Inspect the generated service files, remove then and add them again with "Add Service Reference" and see what options you have there.
EDIT
Although I'm almost sure that the Type PrimaryColor is defined twice. One time in the common project and one time in your service reference, you can also try this in your clientApp (to more explicitely specify the PrimaryColor Type):
Common.PrimaryColor color = client.GetColor();