Error while updating Castle.Windsor to 3.3 - castle-windsor

I am updating my project from Castle.Windsor 2.5.4 to 3.3.0.
I get an error:
The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) GenericArguments[0], 'TInterface', on 'Castle.MicroKernel.Registration.ComponentRegistration`1[TService]'
violates the constraint of type parameter 'TService'.
It's while it tries to resolve:
IActiveRequestService requestService = _container.Resolve<IActiveRequestService>();
public interface IActiveRequestService
{
void SetActiveRequest(IActiveRequest request);
IActiveRequest Current { get; }
void ClearActiveRequest();
bool HasActiveRequest { get; }
void StartAcceptingRequests();
void StopAcceptingRequests(string Reason);
bool IsAcceptingRequests { get; }
string ReasonRequestRejected { get; }
}

Related

Exception when trying to use Mysql.Data.Entity

I'm trying to get a test project running using MySQL and EF6 using Visual Studio 2019 Community Preview for Mac. I am using the Web Application (Model-View-Controller) / .NET Core -> App template as a starting point as well as the MyWind database. I'm getting the following exception and am not sure how to proceed.
TypeLoadException: Could not load type 'System.ComponentModel.DataAnnotations.AssociatedMetadataTypeTypeDescriptionProvider' from assembly 'System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetTypeDescriptor(Type type)
System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(Type type)
System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
System.Data.Entity.Internal.RetryLazy<TInput, TResult>.GetValue(TInput input)
System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
System.Data.Entity.Internal.InternalContext.Initialize()
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
System.Data.Entity.Internal.Linq.InternalSet<TEntity>.Initialize()
System.Data.Entity.Internal.Linq.InternalSet<TEntity>.get_InternalContext()
System.Data.Entity.Infrastructure.DbQuery<TResult>.System.Linq.IQueryable.get_Provider()
System.Linq.Queryable.OrderBy<TSource, TKey>(IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector)
Ef2MySql.Controllers.HomeController.Contact() in HomeController.cs ViewData["Customers"] = db.Customers.OrderBy(c => c.company).ThenBy(c => c.last_name).ThenBy(c => c.first_name).Take(10);
lambda_method(Closure , object , object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Here's my relevant code.
HomeController.cs
namespace Ef2MySql.Controllers
{
public class HomeController : Controller
{
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
using (var db = new NorthwindContext())
{
ViewData["Customers"] = db.Customers.OrderBy(c => c.company).ThenBy(c => c.last_name).ThenBy(c => c.first_name).Take(10);
}
return View();
}
}
}
NorthwindContext.cs
namespace Ef2MySql.Database
{
public partial class NorthwindContext : DbContext
{
public NorthwindContext() : base("Server=localhost;Database=northwind;Uid=northwind;Pwd=northwind;")
{
}
public virtual DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}
NorthwindMysqlConfiguration.cs
namespace Ef2MySql.Database
{
public class NorthwindMysqlConfiguration : MySqlEFConfiguration
{
public NorthwindMysqlConfiguration()
{
}
}
}
Customer.cs
namespace Ef2MySql.DomainObjects
{
public class Customer
{
public Customer()
{
}
public String id { get; set; }
public String company { get; set; }
public String last_name { get; set; }
public String first_name { get; set; }
public String email_address { get; set; }
public String job_title { get; set; }
public String business_phone { get; set; }
public String home_phone { get; set; }
public String mobile_phone { get; set; }
public String fax_number { get; set; }
public String address { get; set; }
public String city { get; set; }
public String state_province { get; set; }
public String zip_postal_code { get; set; }
public String country_region { get; set; }
public String web_page { get; set; }
public String notes { get; set; }
}
}
Here's the version of mono I'm using.
$ mono --version
Mono JIT compiler version 5.18.0.248 (2018-08/a4956c837e1 Fri Jan 25 16:13:12 EST 2019)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
TLS:
SIGSEGV: altstack
Notification: kqueue
Architecture: amd64
Disabled: none
Misc: softdebug
Interpreter: yes
LLVM: yes(600)
Suspend: preemptive
GC: sgen (concurrent by default)
I'm not sure if this is relevant, but for the MySql.Data.Entity and EntityFramework packages, I'm getting the following warning:
Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.1'. This package may not be fully compatible with your project.
For what it's worth, I am able to use MySql.Data.MySqlClient.MySqlConnection directly to retrieve data from the database.
After doing some research, it seems that this class is simply missing from corefx. It has been added for 3.0.

EntityFramework not updating enum value in MySQL database

Important note: the column online in my MySQL table is of type enum and I'm not allowed to change the database
So here's my entity:
public enum onlineStatus { online = 1, offline = 0 };
public onlineStatus online { get; set; }
And in my db context:
public class UsersContext : DbContext
{
public DbSet<User> Users { get; set; }
public void AddUser(User user) // I'm using a custom membership provider that calls this method
{
try
{
user.online = 0; // this will give me the word "offline"
Users.Add(user);
SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
}
Somehow user.online = 0; doesn't add to the database. And how do I make it so that it saves the value 0 instead of offline. Thanks in advance.

Generic return types with interface type params in WCF

How can I return interface types in generic type parameters from the OperationContracts in my WCF REST service? More specifically, it works for one operation but not when I add a second operation with a generic T that is an interface.
I'm using JSON as the request and response format, feeding a non-WCF client that parses the JSON responses for the data it needs. I am not using SOAP, or the WSDL generated by the service.
My service interface:
[ServiceContract]
[ServiceKnownType("GetServiceKnownTypes", typeof(ServiceKnownTypesHelper))]
public interface IMyService
{
[WebGet(UriTemplate="count")]
[OperationContract]
IServiceResult<int> GetCount();
[WebGet(UriTemplate="desc")]
[OperationContract]
IServiceResult<string> GetDescription();
[WebGet(UriTemplate="foo")]
[OperationContract]
IServiceResult<IFooData> GetFooData();
// Fails when I invoke either method if I uncomment this operation.
//[WebGet(UriTemplate="bar")]
//[OperationContract]
//IServiceResult<IBarData> GetBarData();
}
I left GetCount() and GetDescription() in the example to point out that those two generic results work fine, but obviously they are concrete types. And even GetFooData() works fine until I add a second method of IServiceResult<T> where T is an interface.
The return types of GetFooData() and GetBarData() are not the same, nor are the concrete classes that implement them.
You may imagine that I've reduced the implementation to a skeleton as I don't think the implementation is the heart of the problem:
#region My service implementation
public class MyService : IMyService
{
public IServiceResult<int> GetCount()
{
return new ServiceResult<int>(42);
}
public IServiceResult<string> GetDescription()
{
return new ServiceResult<string>("Muffins");
}
public IServiceResult<IFooData> GetFooData()
{
return new ServiceResult<IFooData>(new FooData() { Foo = 99 });
}
public IServiceResult<IBarData> GetBarData()
{
return new ServiceResult<IBarData>(new BarData() { Bar = "Elvis was here" });
}
}
#endregion
#region ServiceKnownTypesHelper.GetServiceKnownTypes():
public static class ServiceKnownTypesHelper
{
private static IList<Type> serviceKnownTypes = new List<Type>()
{
typeof(FooData),
typeof(BarData),
typeof(ServiceResult<int>),
typeof(ServiceResult<string>),
typeof(ServiceResult<IFooData>),
typeof(ServiceResult<IBarData>),
};
public static IEnumerable<Type> GetServiceKnownTypes(ICustomAttributeProvider paramIgnored)
{
return serviceKnownTypes;
}
}
#endregion
#region IServiceResult<T> and its concrete implementation:
public interface IServiceResult<T>
{
IList<string> Errors { get; }
T Value { get; set; }
}
[DataContract]
public class ServiceResult<T> : IServiceResult<T>
{
public ServiceResult(T value)
{
this.Value = value;
}
private IList<string> errors = new List<string>();
[DataMember]
public IList<string> Errors
{
get
{
return this.errors;
}
}
[DataMember]
public T Value { get; set; }
}
#endregion
#region IFooData and its concrete implementation:
public interface IFooData
{
int Foo { get; set; }
}
[DataContract]
public class FooData: IFooData
{
[DataMember]
public int Foo { get; set; }
}
#endregion
#region IBarData and its concrete implementation:
public interface IBarData
{
string Bar { get; set; }
}
[DataContract]
public class BarData: IBarData
{
[DataMember]
public string Bar { get; set; }
}
#endregion
And the error message when I invoke GetBarData() from the browser:
Type 'ServiceResult`1[IBarData]' cannot be added to list of known types since
another type 'ServiceResult`1[IFooData]' with the same data contract name
'http://schemas.datacontract.org/2004/07/ServiceResultOfanyType' is
already present.
The rest of the error message is a red herring about colliding collection types List<Test> and Test[], which isn't the case here.
Clearly, IFooData and IBarData aren't the same, nor are the classes that implement them.
So why do ServiceResult<IFooData> and ServiceResult<IBarData> both resolve to ServiceResultOfanyType?
Am I missing something, or is there no way to fix this?
After much trial and error, I've finally got this working with minimal changes:
My service operations now return ServiceResult<T> instead of IServiceResult<T>. In fact, IServiceResult<T> is now gone entirely.
GetServiceKnownTypes() no longer returns all the variants of ServiceResult<T>. I only return the DataContracts used as T.
#region My service interface
[ServiceContract]
[ServiceKnownType("GetServiceKnownTypes", typeof(ServiceKnownTypesHelper))]
public interface IMyService
{
[WebGet(UriTemplate="count")]
[OperationContract]
ServiceResult<int> GetCount();
[WebGet(UriTemplate="desc")]
[OperationContract]
ServiceResult<string> GetDescription();
[WebGet(UriTemplate="foo")]
[OperationContract]
ServiceResult<IFooData> GetFooData();
[WebGet(UriTemplate="bar")]
[OperationContract]
ServiceResult<IBarData> GetBarData();
}
#endregion
#region My service implementation (minus bodies)
public class MyService : IMyService
{
public ServiceResult<int> GetCount() {}
public ServiceResult<string> GetDescription() {}
public ServiceResult<IFooData> GetFooData() {}
public ServiceResult<IBarData> GetBarData() {}
}
#endregion
#region ServiceKnownTypes
// My list of ServiceKnownTypes is now much shorter and simpler. I was feeding the service too much information
public static class ServiceKnownTypesHelper
{
private static IList<Type> serviceKnownTypes = new List<Type>()
{
typeof(FooData),
typeof(BarData),
//typeof(ServiceResult<int>),
//typeof(ServiceResult<string>),
//typeof(ServiceResult<IFooData>),
//typeof(ServiceResult<IBarData>),
};
// Remaining implementation is the same as before
}
#endregion
#region ServiceResult<T> with no interface (it's not used or needed)
[DataContract]
public class ServiceResult<T> //: IServiceResult<T>
{
// implementation is the same as before
}
#endregion
I can now invoke all of those methods and get back lists of generic types referred to by their interfaces in the ServiceContract.

Entity Framework Code First One to One Constraint Violation

Given the following simplified model:
public class Account
{
public Account()
{
Id = Guid.NewGuid();
ContactCard = new ContactCard();
}
//[ForeignKey("ContactCard")]
public Guid Id { get; set; }
public string Name { get; set; }
public string Number { get; set; }
public ContactCard ContactCard { get; set; }
}
public class ContactCard
{
public ContactCard()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public Account Account { get; set; }
}
public class MightDbContext: DbContext
{
public DbSet<Account> Accounts { get; set; }
public DbSet<ContactCard> ContactCards { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Account>().HasRequired(x => x.ContactCard).WithOptional(x => x.Account);
}
}
public class MightDbInitializer : DropCreateDatabaseIfModelChanges<MightDbContext>
{
protected override void Seed(MightDbContext context)
{
var accounts = new List<Account>
{
new Account()
{
Name = "Acme Corporation Pty. Ltd.",
Number = "001ABC"
},
new Account()
{
Name = "Three Little Pigs Pty. Ltd.",
Number = "002DEF"
}
};
accounts.ForEach(c => context.Accounts.Add(c));
}
}
And the following simple console program to iterate the contents of the Accounts and ContactCards collections:
static void Main(string[] args)
{
Database.SetInitializer<MightDbContext>(new MightDbInitializer());
using (var context = new MightDbContext())
{
foreach (Account c in context.Accounts)
{
Console.WriteLine(c.ContactCard.Id);
}
var contactCards = context.ContactCards.ToList(); /* ERROR OCCURS HERE */
foreach (ContactCard a in contactCards)
{
Console.WriteLine(a.Id);
}
}
Console.Read();
}
Why do I get the following error as soon as I try to access the ContactCards collection:
Multiplicity constraint violated. The role 'Account_ContactCard_Source' of the relationship 'InvestAdmin.Might.DataAccess.Account_ContactCard' has multiplicity 1 or 0..1.
When I look at the data that has actually been stored in the database tables all seems to be correct. In fact here is that data:
Accounts:
Id Name Number
ab711bad-1b32-42ca-b68b-12f7be831bd8 Acme Corporation Pty. Ltd. 001ABC
dc20a1dd-0ed4-461d-bc9c-04a85b555740 Three Little Pigs Pty. Ltd. 002DEF
ContactCards:
Id
dc20a1dd-0ed4-461d-bc9c-04a85b555740
ab711bad-1b32-42ca-b68b-12f7be831bd8
And for completeness here is the Account_ContactCard foreign key constraint as defined in the database:
-- Script Date: 06/12/2011 7:00 AM - Generated by ExportSqlCe version 3.5.1.7
ALTER TABLE [Accounts] ADD CONSTRAINT [Account_ContactCard] FOREIGN KEY ([Id]) REFERENCES [ContactCards]([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
I have been reading all I can on defining one to one relationships in Code First and have tried many different configurations. All end up back at the same problem.
I found that I could resolve this problem by moving the creation of the associated ContactCard from the Account constructor into the actual creation of the Account objects in the Seed method of the DBInitializer. So it appears that it was not (directly) a problem with the One to One relationship.

EF Code First, create new object in collection with a proxy

How can I create+persist+have-a-proxy-to a new instance of a code-first poco using only navigation property collections? In the bellow code, I show how you might want to do this, if using member functions to create POCOs that then create POCOs. You don't have a DbContext, but if you create an object and persist it using DbSet.Add, the returned object isn't a proxy, so you can't in turn use its DbSet.Add to add a different sub-object.
In this code, if you call MailingList.AddIncomingMessage("my message"), you get an exception at the "OOPS" comment, because the created msg isn't a proxy and thus its Message.doodads property is null.
class Doodad {
public int ID { get; set; }
public string doodad { get; set; };
}
class Message {
public int ID { get; set; }
public virtual MailingList mailingList { get; set; }
public virtual ICollection<Doodad> doodads { get; set; }
public string text { get; set; }
public void GetDoodadCreateIfNeeded(string doodad) {
try {
// won't be found since we just created this Message
return this.doodads.First(d => d.doodad == doodad);
} catch (Exception e) {
Doodad newDoodad = new Doodad() { doodad=doodad };
// OOPS! this.doodads == null, because its not a proxy object
this.doodads.Add(newDoodad);
return newDoodad;
}
}
}
class MailingList {
public int ID { get; set; }
public virtual ICollection<Message> messages { get; set; }
public void AddIncomingMessage(string message) {
var msg = new Message() { text=message };
// we have no Context, because we're in a POCO's member function
this.messages.Add(msg);
var doodad = msg.GetDoodadCreateIfNeeded("bongo drums");
}
}
EDIT: sorry guys, I forgot to put the property accessors and ID in for this simplified case, but I am using them in the actual code.
It has nothing to do with proxies. It is the same as any other code - if you want to use object / collection you must first initialize it! Your fist command:
return this.doodads.First(d => d.doodad == doodad);
doesn't throw exception because it didn't find doodad but because the doodads is null.
What do you need to do? You need to initialize collections before you first use them. You can do it:
Directly in their definition
In entity's constructor
In property getter (lazy initialization) once they are first needed - that would require to change your fields to properties which is btw. correct way to write classes in .NET
In your custom methods you can check if they are null and initialize them
Complementary to the navigation property, you need to have a property that is the Id of the foreign key.
So your MailingList will need to have this property:
[Key] // this attribute is important
public int Id { get; set; }
and you'll have to change the Message classe to have these properties:
public virtual int mailingListId { get; set;
public virtual MailingList mailingList { get; set; }
The { get; set; } property is important, so that it is a property, not just a public attribute.