Embedded resource mapping files added - class not mapped - asp.net-mvc

In my asp.net mvc application I'm using nhibernate 3.2 as ORM. I have catalogue structure like
..\Models\Persons with User.cs and OtherClass.cs in it and also ..\Mapping with files hibernate.xml,Persons.xml I added mapping files as embeeded resources and in code of application I have
Assembly assembly = Assembly.GetExecutingAssembly();
config.AddAssembly(assembly);
sFactory = config.BuildSessionFactory();
I tried to run simple hql query
From User up WHERE up.Password=admin AND up.Login=admin
but I still get an error:
A first chance exception of type 'NHibernate.Hql.Ast.ANTLR.QuerySyntaxException' occurred in NHibernate.DLL
User is not mapped [ FROM User up WHERE up.Password=admin AND up.Login=admin]
I can't get an idea what I'm doing wrong. I'd appreciate any help.

Can you check if the mappings are loaded by inspecting the sessionfactory properties after creation?

Related

Asp.Net Core Localized Resource in Separate Assembly

I am trying to use the new Localization features of .NET Core, but outside the simple sample Microsoft has provided here, https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization#resource-file-naming.
I have my Controllers in a separate project, ProjectA.Controllers, while I have a shared resource class in a common project, ProjectB.Localization. I've configured my startup class as prescribed in the docs.
I am unclear on what to name my resource file and where exactly to put it. I've configured the option to store in the directory "Resources". Is that in the Web project or my ProjectB.Localization where my SharedResource class is? The docs say that if it's a separate assembly, the full namespace should be used. So I've named it, "WorldCart.Facilities.Localization.SharedResource.es.resx" and placed it in the resources folder of the website.
When I run the web app, and debug in the home controller, I do not get a translated string, I get the english version.
Any ideas?
Very late answer, but it might help someone...
I had a similar situation where I had to have the resource files in separate common assembly instead of having it inside the mail web/api project (Core 2.1). The reason being, I could be using the localized resources from other assemblies like Business or DAL layer for throwing warning/error/information messages. This is what I did:
Assume that my web project namespace is MyApp.Web and my resources are in separate class lib MyApp.Resources. In the resources library, create a folder (optional), say "Messages", and create a class Messages.cs. Create the resource files inside the same folder adhering to the naming conventions. For example, Messages.fr.resx.
In the ConfigureServices method of the main project, add the localization without any resource path*:
services.AddLocalization();
services.Configure<RequestLocalizationOptions>(
opts =>
{
/* your configurations*/
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en"),
new CultureInfo("fr")
};
opts.DefaultRequestCulture = new RequestCulture("en", "en");
// Formatting numbers, dates, etc.
opts.SupportedCultures = supportedCultures;
// UI strings that we have localized.
opts.SupportedUICultures = supportedCultures;
});
And in the Configure method, add app.UseRequestLocalization();
In your controller, inject IStringLocalizer<Messages> localizer, where Messages is the class you created in the Resources library. All your localized resources will be available in the localizer object, i.e., localizer["your key or default text"].
The reason for not adding any ResourcePath in the services.AddLocalization(); options is due to the reason that both the resource files (Messages.fr.resx) and the dummy class (Messages.cs) are in the same path. The framework will check for the resource file relative to the class which we have specified in IStringLocalizer<>. If the Messages.cs was in the root folder of MyApp.Resources lib and the resource files were inside folder "xyz", then the configuration should be services.AddLocalization(ops => ops.ResourcesPath = "xyz");
UPDATE - Responding to the queries in the comments:
MVC Views
In MVC Views, the documented approach uses IViewLocalizer, but does not support resource sharing. So you can inject IStringLocalizer<> in the view for using the shared resources. For example:
#inject IStringLocalizer<Messages> localizer
<h2>Information - #localizer["Shared resource access in MVC Views"]</h2>
Data Annotations
In order to use shared resources in the data annotations, you can use the factory method in the service:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddDataAnnotationsLocalization(options => {
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(Messages));
});
where the Messages in the typeof(Messages) is your shared resource dummy class.

Models not loaded by Glass Mapper

Could anyone tell me why the models that I have in an external library (referenced in my main project) can't be loaded by Glass Mapper?
I get something like this:
Type Test.Project.Models.Item has not been
loaded
The version of Glass Mapper is 2.0.11 and Sitecore has the version 7.2 (client's request).
Thank you
When you install Glass.Mapper using the Glass.Mapper.Sc.CastleWindsor it will automatically load classes configured with attributes from the current assembly, but if you want to load classes configured with attributes from another assembly. you have to add adding another SitecoreAttributeConfigurationLoader
public static IConfigurationLoader[] GlassLoaders(){
var attributes = new SitecoreAttributeConfigurationLoader("Project.Website");
var attributes2 = new SitecoreAttributeConfigurationLoader("Project.Models");
return new IConfigurationLoader[]{attributes, attributes2};
}

How to configure automapper for Unity dependency injection and Entity Framework in MVC 5 / Web API 2.0 app?

I'm using Automapper in my MVC 5 app to auto map my Entity Framework entities. Some of the mappings need to be looked up, so I need to inject them in the AutoMapperConfig. I use PerRequestLifetimeManager. To do the injection I've setup Unity in Appliction_BeginRequest the following lines:
Mapper.Initialize(cfg => cfg.ConstructServicesUsing(type => UnityConfig.GetConfiguredContainer().Resolve(type)));
var UnityContainer = UnityConfig.GetConfiguredContainer();
UnityContainer.Resolve<AutoMapperConfig>().MapAutoMapper();
But strangely after a few requests (hit F5 several times) the app breaks on Mapper.AssertConfigurationIsValid(); with the error message:
AutoMapper.AutoMapperConfigurationException was unhandled by user code
HResult=-2146233088 Message= Unmapped members were found. Review the
types and members below. Add a custom mapping expression, ignore, add
a custom resolver, or modify the source/destination type
======================================================================= IssueDTO -> Issue (Destination member list)
Improveize.Classes.DTO.IssueDTO -> Improveize.Classes.Persistent.Issue
(Destination member list)
----------------------------------------------------------------------- CreatedBy
But the member mentioned (CreatedBy) is mapped correctly in my code. FYI: the specific mapping makes use of a repository to lookup the data.
The relevant part of the AutoMapperConfig mapping that seems to generate the issue:
Mapper.CreateMap<IssueDTO, Issue>()
.ForMember(dest => dest.CreatedBy,
opt => opt.MapFrom(
src => _UserRepository.Get(u => u.UserID == src.CreatedByID).FirstOrDefault()));
So I thought this would have anything to do, that Automapper is initialized too often (every request) so I've put the Mapper.Initialize..... line in Application_Start.
But strangly (at least to me) I get the following error message when I want so save the data of a partial view through an Ajax call to the webapi part of the app.
The relationship between the two objects cannot be defined because
they are attached to different ObjectContext objects.
It breaks on the following lines in my DBContext when I want to set the EntityState to Modified:
public new virtual DbEntityEntry Entry(object obj)
{
return base.Entry(obj);
}
So apperantly the mapping resolved by a repository gets another DBContext. (if I ignore the properties that need a lookup, 'everything' works fine)
So it is Obvious that I'm doing something wrong, but I do not know what. The questions that arise:
where to put Mapper.Initialize(cfg => cfg.ConstructServicesUsing(type => UnityConfig.GetConfiguredContainer().Resolve(type))); ?? In which class to put in in?
can the context issue have anything to do with the web app is using MVC 5 and Webapi 2.0? Do they generate different dbcontext? And how can I avoid this.
where is the AutoMapper error coming from (it looks like the wrong message to me)? And how to solve
EDIT to answer the questions of Gert Arnold:
DbEntityEntry method breaks my DBContext
it breaks when I want to set the EntityState to Modified, called in the update action of the repository
Since I use PerRequestLifeTimeManager I assume the lifetime of _UserRepository.Get to be the lifespan of the request. I'm doing nothing explicitly to dispose the context nor the repository.
1) Mapper.AssertConfigurationIsValid(); is meant to be used in unit tests, not in production code.
2) Also this
Mapper.CreateMap<IssueDTO, Issue>()
.ForMember(dest => dest.CreatedBy,
opt => opt.MapFrom(
src => _UserRepository.Get(u => u.UserID ==src.CreatedByID).FirstOrDefault()));
is scary usage of Automapper. I never could imagine it could be abused this way. Violation of SRP in it's worst! Your mapping code does mapping AND does database lookup? mixing responsibilities here. Therefore you are going into lot of complexity with injecting Automapper configuration and other strange issues. Don't do it, keep it simple.
Let your controllers (or QueryHandlers) query database for entities and mapper just do it's job by mapping DB objects into view models.

by default where the data is stored in mvc 3

simply i take mvc 3 project then add model "class1" in that there is another class "person"
in class1 there is two properties id,name and
in class person i inherits dbcontext class and it contains
"public DbSet classes { get; set; }"
and i take default1controller with read/write actions and views, using entity framework and
set
model class "class1" and
data context class "person"
so now my program runs successfully
and i can insert the data but i don't know that where it stores the data.
plz help me.
It might use SQL Server Compact which stores data in a file inside the ~/App_Data folder.
I've not yet used MVC 3 but have a look at your Visual Studio solution. See if there is an App_data folder and expand that. In there you might see an MDF database. Chances are the data is stored in there.
The only thing that I would add to #ManishG's comment:
it stores the data in my local sqlexpress
is that, for connecting to a sqlexpress instance, you should put (local)\SQLEXPRESS in the Server Name field if you are creating a connection from VS 2010 Server Explorer.

Linq DataContext class not accessible in my MVC after I save the dbml

I just downloaded MVC and I am going through a tutorial. Everything goes fine until I try to declare a DataContext object.
My dbml is named db.dbml (tried another on named test.dbml) and when I try this:
public dbDataContext db = new dbDataContext();
I get:
The type or namespace name
'dbDataContext' could not be found ...
Am I missing something? In webforms this is all I had to do, and in the tutorial that is all that is shown. I downloaded the newest MVC today...
Thank you.
**EDIT: I am using VS2008 SP1
This is a sp1 bug if you are using partial classes, see the following and work-arounds:
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361577
A few quick questiosn: Is the name of your data context "dbDataContext"?... also, is it in a namespace? (do you have that namespace referenced).
Another question... is this a runtime error, or a compiletime error?
try to add context to the namespace {ProjectName}.Models...
because the models are stored in the models namespace.. try to check if you have include the namespace in your current context..
once you add the class just build the solution.you ll find your classes in the list

Resources