I made the following changes to my DbContext
//public DbSet<Role> Roles { get; set; } //old
//public DbSet<TypePermissionObject> TypePermissionObjects { get; set; } //old
//public DbSet<User> Users { get; set; } //old
public DbSet<PermissionPolicyRole> Roles { get; set; }
public DbSet<PermissionPolicyTypePermissionObject> TypePermissionObjects { get; set; }
public DbSet<PermissionPolicyUser> Users { get; set; }
Now the following line of code is returning an error. When it should be returning false.
var compatible = db.Database.CompatibleWithModel(false);
The call stack is
Application: MyApp2.Win.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.InvalidOperationException
at System.Linq.Enumerable.Single[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Collections.Generic.IEnumerable`1<System.__Canon>, System.Func`2<System.__Canon,Boolean>)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer+<GetStoreAssociationTypePairs>d__15.MoveNext()
at System.Linq.Enumerable+<SelectManyIterator>d__23`3[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext()
at System.Linq.Enumerable+<DistinctIterator>d__64`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext()
at System.Collections.Generic.List`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]..ctor(System.Collections.Generic.IEnumerable`1<System.__Canon>)
at System.Linq.Enumerable.ToList[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Collections.Generic.IEnumerable`1<System.__Canon>)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.FindAssociationTypePairs(System.Collections.Generic.ICollection`1<System.Tuple`2<System.Data.Entity.Core.Metadata.Edm.EntityType,System.Data.Entity.Core.Metadata.Edm.EntityType>>)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata, ModelMetadata, System.Lazy`1<System.Data.Entity.Migrations.Infrastructure.ModificationCommandTreeGenerator>, System.Data.Entity.Migrations.Sql.MigrationSqlGenerator, System.String, System.String)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(System.Xml.Linq.XDocument, System.Xml.Linq.XDocument, System.Lazy`1<System.Data.Entity.Migrations.Infrastructure.ModificationCommandTreeGenerator>, System.Data.Entity.Migrations.Sql.MigrationSqlGenerator, System.String, System.String)
at System.Data.Entity.Internal.InternalContext.ModelMatches(System.Data.Entity.Migrations.Infrastructure.VersionedModel)
at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean, System.Data.Entity.Internal.DatabaseExistenceState)
at System.Data.Entity.CreateDatabaseIfNotExists`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].InitializeDatabase(System.__Canon)
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(System.Action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.RetryAction`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].PerformAction(System.__Canon)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(System.Action`1<System.Data.Entity.Internal.InternalContext>)
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(System.Type)
at System.Data.Entity.Internal.Linq.InternalSet`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Count[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Linq.IQueryable`1<System.__Canon>)
at MyApp2.Win.Program.Main()
I have double checked the connection string
The projects reference EntityFramework 6.4.4
Event Viewer shows that the Source of the Error is .NET Runtime
Crosschecking the error time with output from Process Monitor ( from sysinterenals.com ) I see a NAME NOT FOUND error for EntityFramework.pdb
4 milli seconds earler there is a NAME NOT FOUND error for BiDInterface
The answer to this question indicates that I might have duplicate entries in my database. I am not sure what is meant.
I tried changing to the following but it did not help/
public DbSet<PermissionPolicyRole> Roles2 { get; set; }
public DbSet<PermissionPolicyTypePermissionObject> TypePermissionObjects2 { get; set; }
public DbSet<PermissionPolicyUser> Users2 { get; set; }
[Update]
I decided to delete the migrations and generate a new one.
When I attempted this I got the following error in the PM Console
PM> add-migration security
System.InvalidOperationException: Sequence contains no matching element
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<GetStoreAssociationTypePairs>d__15.MoveNext()
at System.Linq.Enumerable.<SelectManyIterator>d__23`3.MoveNext()
at System.Linq.Enumerable.<DistinctIterator>d__64`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.FindAssociationTypePairs(ICollection`1 entityTypePairs)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInternal(String name, DbConnectionInfo connectionInfo, String migrationsConfigurationName, Boolean ignoreChanges)
at System.Data.Entity.Infrastructure.Design.Executor.Scaffold.<>c__DisplayClass0_0.<.ctor>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
Sequence contains no matching element
PM>
I have the following in the DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new RoleConfiguration());
modelBuilder.Configurations.Add(new UserConfiguration());
}
with
public class RoleConfiguration : EntityTypeConfiguration<DevExpress.Persistent.BaseImpl.EF.PermissionPolicy.PermissionPolicyRole>
{
public RoleConfiguration()
{
HasMany(x => x.Users).WithMany(y => y.Roles).Map(x => x.ToTable("PermissionPolicyUserPermissionPolicyRoles"));
}
}
public class UserConfiguration : EntityTypeConfiguration<DevExpress.Persistent.BaseImpl.EF.PermissionPolicy.PermissionPolicyUser>
{
public UserConfiguration()
{
HasMany(x => x.Roles).WithMany(y => y.Users).Map(x => x.ToTable("PermissionPolicyUserPermissionPolicyRoles"));
}
}
[Update]
I studied a new xaf project and realised that the configurations are not needed.
Now I try to run the migration without the configuration files I get
PM> add-migration security
ystem.InvalidOperationException: Sequence contains no matching element
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<GetStoreAssociationTypePairs>d__15.MoveNext()
at System.Linq.Enumerable.<SelectManyIterator>d__23`3.MoveNext()
at System.Linq.Enumerable.<DistinctIterator>d__64`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.FindAssociationTypePairs(ICollection`1 entityTypePairs)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInternal(String name, DbConnectionInfo connectionInfo, String migrationsConfigurationName, Boolean ignoreChanges)
at System.Data.Entity.Infrastructure.Design.Executor.Scaffold.<>c__DisplayClass0_0.<.ctor>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
Sequence contains no matching element
PM>
I think have done the security table upgrade in the wrong order.
I will need to roll back and proceed more carefully.
Related
I'm following the tutorial on how to build a console application that connects to Dynamics CRM, but stuck on the very beginning with using the CrmSvcUtil.
here's what I did:
copied this command:
CrmSvcUtil.exe /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration" /out:Xrm.cs /url:https://<mydomain>.api.crm.dynamics.com/XRMServices/2011/Organization.svc /username:<myusername>#<mydomain>.onmicrosoft.com /password:<mypassword> /namespace:Xrm /serviceContextName:XrmServiceContext
replaced the above /url with the one listed on my CRM online deployment under Settings > Customizations > Developer Resources > Organization Service.
replaced the above /username with my onmicrosoft.com username, and put quotes before and after it.
replaced the above /password the way I did with /username.
followed this note and put the Xrm.Client.CodeGeneration.dll on the same directory with CrmSvcUtil.exe.:
Note that the Microsoft.Xrm.Client.CodeGeneration.dll file must be in
the same directory as the CrmSvcUtil.exe file
and then I ran it, and got the following error:
CrmSvcUtil : CRM Service Utility [Version 8.1.0.7711]
c 2015 Microsoft Corporation. All rights reserved
Exiting program with exception: Could not load file or assembly 'CrmSvcUtil, Version=7.0.0.0, Cult
ure=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest
definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
CrmSvcUtil Error: 2 : Exiting program with exit code 2 due to exception : System.IO.FileLoadExcept
ion: Could not load file or assembly 'CrmSvcUtil, Version=7.0.0.0, Culture=neutral, PublicKeyToken
=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'CrmSvcUtil, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase
, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadType
FromPartialName, ObjectHandleOnStack type)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase
, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromP
artialName)
at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolea
n reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName, Boolean throwOnError)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultSer
viceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters param
eters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!En
ableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
CrmSvcUtil Error: 2 : ===== DETAIL ======
CrmSvcUtil Error: 2 : Source : mscorlib
Method : GetTypeByName
Date : 15:52:37
Time : 28/10/2016
Error : Could not load file or assembly 'CrmSvcUtil, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
or one of its dependencies. The located assembly's manifest definition does
not match the assembly reference. (Exception from HRESULT: 0x80131040)
Stack Trace : at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean
ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder,
Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase,
Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName, Boolean throwOnError)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
What's the way to solve it?
EDIT: I tried using Early Bound Generator - just downloading it, connecting, and clicking "Create Entities", but it ends with an error:
System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at DLaB.CrmSvcUtilExtensions.Entity.CodeWriterFilterService.GenerateOptionSet(OptionSetMetadataBase optionSetMetadata, IServiceProvider services)
at Microsoft.Crm.Services.Utility.CodeGenerationService.BuildAttributeOptionSet(EntityMetadata entity, AttributeMetadata attribute, CodeTypeMember attributeMember, ServiceProvider serviceProvider)
at Microsoft.Crm.Services.Utility.CodeGenerationService.BuildEntity(EntityMetadata entity, ServiceProvider serviceProvider)
at Microsoft.Crm.Services.Utility.CodeGenerationService.BuildEntities(EntityMetadata[] entityMetadata, ServiceProvider serviceProvider)
at Microsoft.Crm.Services.Utility.CodeGenerationService.BuildCodeDom(IOrganizationMetadata organizationMetadata, String outputNamespace, ServiceProvider serviceProvider)
at Microsoft.Crm.Services.Utility.CodeGenerationService.Microsoft.Crm.Services.Utility.ICodeGenerationService.Write(IOrganizationMetadata organizationMetadata, String language, String outputFile, String outputNamespace, IServiceProvider services)
at DLaB.CrmSvcUtilExtensions.BaseCustomCodeGenerationService.WriteInternal(IOrganizationMetadata organizationMetadata, String language, String outputFile, String targetNamespace, IServiceProvider services)
at DLaB.CrmSvcUtilExtensions.BaseCustomCodeGenerationService.Write(IOrganizationMetadata organizationMetadata, String language, String outputFile, String targetNamespace, IServiceProvider services)
Output file was not updated or not found!
You tagged your question as 'CRM 2016' and article that you linked is for CRM 2015. 'Xrm.Client.CodeGeneration.dll' is not present in SDK for CRM 2016. Copying this DLL from CRM 2015 SDK to bin directory of CRM 2016 SDK won't work and will result with error that you described, because this DLL depends on 7.0.0 versions not 8.0.0. You could try using CRM 2015 SDK (7.1.0) to generate CS file - it should work.
All of a sudden my app won't display a page and I now get "You do not have permission to view this directory or page." I looked at this but the suggestions there didn't help.
for my code:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
// NOTE: If this class is renamed, remember to update the global.asax.cs file
public class Service
{
[WebGet(UriTemplate = "")]
public string GetTest()
{
return "Windward update REST service running.";
}
}
When I request an aspx page, it works.
Global.asx.cs:
public class Global : HttpApplication
{
private static readonly ILog log = LogManager.GetLogger(typeof(Global));
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
log4net.Config.XmlConfigurator.Configure();
log.Info(string.Format("Update REST server started, running under user {0}", WindowsIdentity.GetCurrent().Name));
}
private void RegisterRoutes()
{
// The class providing the REST service
RouteTable.Routes.Add(new ServiceRoute("Service", new WebServiceHostFactory(), typeof(Service)));
}
web.config (relevant parts):
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
Nothing substantive has changed. So why do the requests no longer call the service?
thanks - dave
I'm using Web.api and Unity and I am getting the following error when trying to open the default "help" area:
[InvalidOperationException: The type String cannot be constructed. You must configure the container to supply this value.]
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsNonPrimitive(IBuilderContext context, SelectedConstructor selectedConstructor) +280
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context) +356
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey) +205
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +231
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
BuildUp_System.Web.Http.HttpRouteCollection(IBuilderContext ) +202
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +319
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
BuildUp_System.Web.Http.HttpConfiguration(IBuilderContext ) +202
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +319
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
BuildUp_API.Areas.HelpPage.Controllers.HelpController(IBuilderContext ) +204
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +319
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +373
[ResolutionFailedException: Resolution of the dependency failed, type = "API.Areas.HelpPage.Controllers.HelpController", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type String cannot be constructed. You must configure the container to supply this value.
-----------------------------------------------
At the time of the exception, the container was:
Resolving API.Areas.HelpPage.Controllers.HelpController,(none)
Resolving parameter "config" of constructor API.Areas.HelpPage.Controllers.HelpController(System.Web.Http.HttpConfiguration config)
Resolving System.Web.Http.HttpConfiguration,(none)
Resolving parameter "routes" of constructor System.Web.Http.HttpConfiguration(System.Web.Http.HttpRouteCollection routes)
Resolving System.Web.Http.HttpRouteCollection,(none)
Resolving parameter "virtualPathRoot" of constructor System.Web.Http.HttpRouteCollection(System.String virtualPathRoot)
Resolving System.String,(none)
]
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +436
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides) +50
Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) +48
Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides) +61
Unity.Mvc4.UnityDependencyResolver.GetService(Type serviceType) +140
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +87
[InvalidOperationException: An error occurred when trying to create a controller of type 'API.Areas.HelpPage.Controllers.HelpController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +247
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +438
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +226
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +326
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +177
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
I am new to unity and am sure I am missing step(s).
In webapiconfig.cs:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//Custom formatter
config.Formatters.Clear();
config.Formatters.Add(new JSONPFormater());
config.EnableSystemDiagnosticsTracing();
//Setup DI
Bootstrapper.Initialise();
}
Bootstraper.cs(default values)
public static class Bootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
RegisterTypes(container);
return container;
}
public static void RegisterTypes(IUnityContainer container)
{
}
}
My attempt at a web.config
web.config
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-API-20130708152001;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-API-20130708152001.mdf" />
<add name="<REMOVED>DBEntities" connectionString="metadata=res://*/Models.DAL.<REMOVED>.csdl|res://*/Models.DAL.<REMOVED>.ssdl|res://*/Models.DAL.<REMOVED>.msl;provider=System.Data.SqlClient;provider connection string="data source=<REMOVED>;initial catalog=<REMOVED>;persist security info=True;user id=<REMOVED>;password=<REMOVED>;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<!--unity setting-->
<unity>
<containers>
<types>
<register type="API.Areas.HelpPage.Controllers.HelpController, API">
<constructor>
<param valu=""></param>
</constructor>
</register>
</types>
</containers>
</unity>
Am I headed in the right direction??
Thanks
Update:
helpcontroller.cs:
public class HelpController : Controller
{
public HelpController()
: this(GlobalConfiguration.Configuration)
{
}
public HelpController(HttpConfiguration config)
{
Configuration = config;
}
public HttpConfiguration Configuration { get; private set; }
public ActionResult Index()
{
return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
}
public ActionResult Api(string apiId)
{
if (!String.IsNullOrEmpty(apiId))
{
HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);
if (apiModel != null)
{
return View(apiModel);
}
}
return View("Error");
}
}
url I am trying to access: http:// hostname:port/Help
I think a better way is to add InjectionConstructor attribute to the default constructor. This attribute forces unity to use the decorated constructor.
Example:
public class HelpController : Controller
{
private const string ErrorViewName = "Error";
[InjectionConstructor]
public HelpController()
: this(GlobalConfiguration.Configuration)
{
}
As your code sample, I'm assuming you are on a Controller and not a API Controller (from web api).
Your api controller has a dependency on the constructor from HttpConfiguration. The container problably does not have this definition for this type and consequently does not know how to solve it and the string on the error message should come from this type as a dependency. I recommend you use the GlobalConfiguration static class and access the Configuration property to get a HttpConfiguration instance. You could abstract it in a property, for sample:
// include this namespace
using System.Web.Http;
public class HelpController : Controller
{
// remove the constructors...
// property
protected static HttpConfiguration Configuration
{
get { return GlobalConfiguration.Configuration; }
}
public ActionResult Index()
{
return View(this.Configuration.Services.GetApiExplorer().ApiDescriptions);
}
public ActionResult Api(string apiId)
{
if (!String.IsNullOrEmpty(apiId))
{
HelpPageApiModel apiModel = this.Configuration.GetHelpPageApiModel(apiId);
if (apiModel != null)
{
return View(apiModel);
}
}
return View("Error");
}
}
Now, if you are on a Api Controller, you just can access directly the this.Configuration property that is already on the ApiController (base class for Api controllers) and get a instance of HttpConfiguration.
The reason this happens is because Unity will by default choose to use the constructor with the most parameters thus bypassing the default constructor.
Comment out the two constructors that exist in the HelpController template and add a default one that sets the configuration.
//public HelpController()
// : this(GlobalConfiguration.Configuration)
//{
//}
//public HelpController(HttpConfiguration config)
//{
// Configuration = config;
//}
public HelpController()
{
Configuration = GlobalConfiguration.Configuration;
}
Registering the HttpConfiguration object as an instance in UnityContainer will also help resolve the issue.
Just need to add to add the below line while registering in UnityContainer.
public static void RegisterTypes(IUnityContainer container) {
container.RegisterInstance<HttpConfiguration>(GlobalConfiguration.Configuration);
}
This will help Unity resolve the config parameter, when it invokes the constructor with the parameter.
public HelpController(HttpConfiguration config) {
Configuration = config;
}
I've recently had this error happen on a previously working codebase. The following answer shows what I did to correct it:
Adding Web API and API documentation to an existing MVC project
Basically make the constructor with parameters protected rather than public
When I make a call to an API an error is displayed:
"Could not load file or assembly 'System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.",
Code
I have a base controller for my APIs
[BreezeNHController]
public class baseApiController<T> : ApiController
where T : class, IEntity
{
public IRepository<T> Repositorio { get; private set; }
[HttpGet, BreezeNHQueryable(AllowedQueryOptions = AllowedQueryOptions.All, PageSize = 20)]
public IQueryable<T> Get()
{
return Repositorio.All();
}
// ..
}
And implementation:
[BreezeController, Authorize]
public class usuariosController : baseApiController<User>
{
public usuariosController(IUserRepository repositorio)
: base(repositorio)
{ }
}
Url: GET /api/usuarios throw a exeption!
But my DDL is in reference:
Full response errror:
{
"Message": "An error has occurred.",
"ExceptionMessage": "The type initializer for 'Breeze.WebApi.BreezeControllerAttribute' threw an exception.",
"ExceptionType": "System.TypeInitializationException",
"StackTrace": " at Breeze.WebApi.BreezeControllerAttribute.Initialize(HttpControllerSettings settings, HttpControllerDescriptor descriptor)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.InvokeAttributesOnControllerType(HttpControllerDescriptor controllerDescriptor, Type type)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.InvokeAttributesOnControllerType(HttpControllerDescriptor controllerDescriptor, Type type)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor..ctor(HttpConfiguration configuration, String controllerName, Type controllerType)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerSelector.InitializeControllerInfoCache()\r\n at System.Lazy`1.CreateValue()\r\n at System.Lazy`1.LazyInitValue()\r\n at System.Lazy`1.get_Value()\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerSelector.SelectController(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Could not load file or assembly 'System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.",
"ExceptionType": "System.IO.FileNotFoundException",
"StackTrace": " at Breeze.WebApi.JsonFormatter.Create()\r\n at Breeze.WebApi.BreezeControllerAttribute..cctor()"
}
}
Attempts
In the package manger console, run the command Add-BindingRedirect.
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
Found strange is not pointing to the 4.0. Can it be the problem? If yes, why Add-BindingRedirect did not work?
This is most definitely a binding redirect issue. I advice you copy the entire <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> content from a fresh ASP.NET MVC 4 project to your web.config file. This happens to me occasionally and refreshing the messed up bindings fixes the issue.
We have 2 roles which use a cache role to share data. When we deploy we get many many of the following entries in the logs:
INFORMATION: <CASClient> Updated partition table to (1-901) generation: 635036190744461419:0 with transfer (1-901) generation: 635036190744461419:0; TraceSource 'w3wp.exe' event
INFORMATION: <Complaint> Add hard complaint :0 ; TraceSource 'w3wp.exe' event
Changing the values of the setting:
<Setting name="Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel" value="0" />
seems to have no effect.
Any ideas how we can remove this noise from the WADLogs table?
It seems there is a bug in Caching (see this post). I tried to get rid of these log entries with no luck running SDK1.8. Recently I switched to SDK2.0 but unfortunately the problem is still not fixed.
Bug report on GitHub
I'm going to be adding a filter for this.
Sample for web.config:
<system.diagnostics>
<trace>
<listeners>
<add name="console" type="System.Diagnostics.ConsoleTraceListener">
<filter type="Namespace.TraceFilter, Assembly" initializeData="Information"/>
</add>
</listeners>
</trace>
</system.diagnostics>
Note: The attribute initializeData is set to the text from System.Diagnostics.SourceLevels enum. See here.
TraceFilter.cs
public class TraceFilter : EventTypeFilter
{
public TraceFilter(SourceLevels level)
: base(level) {}
public override bool ShouldTrace(TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data)
{
return !Regex.IsMatch(formatOrMessage, "INFORMATION: <[^>*]*>");
}
}
You could extend this to a more generic filter which could run off a configuration accepting different patterns to include/ignore.
After reading a suggestion at the end of this thread on GitHub we managed to disable this by running the following code in the application:
DataCacheClientLogManager.ChangeLogLevel(TraceLevel.Off);
DataCacheClientLogManager.SetSink(DataCacheTraceSink.DiagnosticSink, TraceLevel.Off);
This stops all logging from the Azure Cache Client without you having to turn off your own Warning or Information level logs.
We ended up adding this in the constructor of our Cache Provider wrapper around the DataCacheClient:
public class AzureCacheProvider : ICacheProvider
{
public AzureCacheProvider()
{
DataCacheClientLogManager.ChangeLogLevel(TraceLevel.Off);
DataCacheClientLogManager.SetSink(
DataCacheTraceSink.DiagnosticSink,
TraceLevel.Off);
InitializeCache();
}
Here is a complete solution
Just make sure to use your namespace and corresponding assembly name.
using Microsoft.WindowsAzure.Diagnostics;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace MyNamespace
{
/*
Solves the Azure In-Role Cache client warnings bug which is too verbose in the WAD logs
Also Solves Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener not using Filter
For roles which uses in-role caching, configure your Web.config or app.config with the following system.diagnostics listner and filter:
<system.diagnostics>
<trace>
<listeners>
<add name="AzureDiagnostics" type="MyNamespace.FilteringDiagnosticMonitorTraceListener, MyAssemblyName">
<!-- WARNING: does not work with type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
because the DiagnosticMonitorTraceListener does not call the filter's ShouldTrace method as is was supposed to... -->
<!-- Note: working with type="System.Diagnostics.ConsoleTraceListener" -->
<filter type="MyNamespace.SuppressCacheClientWarningsTraceFilter, MyAssemblyName" initializeData="Information"/>
<!-- Note: The attribute initializeData is set to the text from System.Diagnostics.SourceLevels enum. -->
</add>
</listeners>
</trace>
</system.diagnostics>
*/
/// <summary>EventTypeFilter which suppress the 'noise' messages from the In-Role Azure Cache client
/// </summary>
/// <remarks>It's a workaround for the following problem http://social.msdn.microsoft.com/Forums/windowsazure/en-US/7ebbc44e-7b61-4bbe-aa54-a85a7788079f/complaint-add-hard-complaint?forum=windowsazuredata.
/// The solution is based on http://stackoverflow.com/questions/16443856/how-to-suppress-azure-cache-client-warnings-from-the-wad-logs and http://pastebin.com/qKc1aTTW
/// </remarks>
public class SuppressCacheClientWarningsTraceFilter : EventTypeFilter
{
public SuppressCacheClientWarningsTraceFilter(SourceLevels level)
: base(level) { }
public override bool ShouldTrace(TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data)
{
return !(
(eventType == TraceEventType.Information && Regex.IsMatch(formatOrMessage, #"^INFORMATION:\ <(CASClient|Complaint)>"))
|| (eventType == TraceEventType.Warning && Regex.IsMatch(formatOrMessage, #"^WARNING:\ <SimpleSendReceiveModule>\ DeadServerCallback"))
);
//return !Regex.IsMatch(formatOrMessage, #"^INFORMATION: <[^>*]*>");
}
}
/// <summary>Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener which uses the configured Trace Filter
/// </summary>
/// <remarks>It's a workaround for the following problem http://social.msdn.microsoft.com/Forums/en-US/92ed1175-d6b7-4173-a224-0f7eb3e99481/diagnosticmonitortracelistener-ignors-filter?forum=windowsazuretroubleshooting
/// The solution is based on the thread comment from "Qin Dian Tang - MSFT": "If you need to use trace filter, then it is needed to use a custom trace listener which derives from DiagnosticMonitorTraceListener, override TraceData, and either manually check filters or call the root class's (TraceListener) TraceData."
/// </remarks>
public class FilteringDiagnosticMonitorTraceListener : DiagnosticMonitorTraceListener
{
public FilteringDiagnosticMonitorTraceListener() : base() { }
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
{
if (this.Filter == null || this.Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null))
base.TraceEvent(eventCache, source, eventType, id, format, args);
}
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
if (this.Filter == null || this.Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null))
base.TraceEvent(eventCache, source, eventType, id, message);
}
}
}
Hope it helps.