jgauffin / griffin.mvccontrib Goto Github PK
View Code? Open in Web Editor NEWA contribution project for ASP.NET MVC3
Home Page: http://blog.gauffin.org/tag/griffin-mvccontrib/
License: GNU Lesser General Public License v3.0
A contribution project for ASP.NET MVC3
Home Page: http://blog.gauffin.org/tag/griffin-mvccontrib/
License: GNU Lesser General Public License v3.0
I'm having a problem using localization,
using LocalizedModelValidatorProvider breaks client validation of custom validation attributes.
The way to register the client validation for the custom attribute is by registering an adapter in DataAnnotationsModelValidatorProvider, but as we cleared all ModelValidatorProviders to add LocalizedModelValidatorProvider then client validation is not working anymore.
I'm trying to use Data Annotations Extensions from: http://dataannotationsextensions.org/ and for example client validation for Email attribute does not work (But server validation do work)
And this is the way they register the adapters: DataAnnotationsModelValidatorProvider.RegisterAdapter
Is there any solution for this problem?
Thanks
Validation message always returns "#g#" unless explicit ErrorMessage in attribute.
I am using MS Sql 2012.
Some times i get error "ExecuteScalar requires an open and available Connection. The connection's current state is closed."
This error i get in subclass of ViewLocalizer and RepositoryStringProvider :
// Caching view texts
public class CachedViewLocalizer : ViewLocalizer
{
private readonly ILocalizedViewsCache _cache;
public CachedViewLocalizer(IViewLocalizationRepository repository, ILocalizedViewsCache cache) : base(repository)
{
_cache = cache;
}
public override string Translate(string viewPath, RouteData routeData, string text)
{
string prompt;
if (_cache.TryGetValue(viewPath, routeData, text, out prompt))
return prompt;
if (prompt != null)
{
prompt = base.Translate(viewPath, routeData, text);// THIS LINE THROW ERROR
}
_cache.Insert(viewPath, routeData, text, prompt);
return prompt;
}
}
// caching type translations
public class CachedTypeLocalizer : RepositoryStringProvider
{
private readonly ILocalizedTypesCache _cache;
public CachedTypeLocalizer(ILocalizedTypesRepository repository, ILocalizedTypesCache cache) : base(repository)
{
_cache = cache;
}
protected override string Translate(Type type, string name)
{
var promptName = type.FullName + "." + name;
string prompt;
if (_cache.TryGetValue(promptName, out prompt))
return prompt;
prompt = base.Translate(type, name);
if (prompt != null)
{
_cache.Insert(promptName, prompt);
}
return prompt;
}
}
After re-build of project everything works again.
So i think, Griffin.MvcContrib close connection.
Maybe some suggestions?
Thanks, Roman
I am working with your localization solution in MVC4, and I am currently in the process of refactoring the stock AccountController so it is localized. However, I ran into a snag - much of the logic is not using DataAnnotations Attributes, but instead is running server-side code and then calling ModelState.AddModelError() directly. I can think of many other cases where using DataAnnotations Attributes are not appropriate.
Is there a way to localize ModelState.AddModelError() using your solution, is there a workaround you have worked out, or is this functionality not included in the box?
NOTE: I am also using the CSLA framework for my models, which support DataAnnotations, but there are more features available in the CSLA framework that DataAnnotations don't support (validation rules that apply to the model itself, validation rules that apply to more than one property, warning priority instead of error, etc.) Therefore, one way or another I need a fix for localizing the text for messages that are added directly using ModelState.AddModelError().
Hi.
I used your 'TestProject' sample code from the codeproject page and let the HomeViewModel implement IValidatableObject, to do some extra checks. For instance: object-level validation, or a call to the database.
But the Validate() method of IValidatableObject is never called.
Is there a way to let the Validation method be called?
The viewmodel code:
public class HomeViewModel : IValidatableObject
{
[Required()]
[StringLength(40)]
public string Name { get; set; }
[Required, Compare("Name", ErrorMessage = "Ange messy")]
public int Age { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
//this is never called
var errors = new List<ValidationResult>();
if (nameIsNotUniqueInDatabase(Name))
errors.Add(new ValidationResult(LocalizedErrors.NameIsNotUnique));
return errors;
}
private bool nameIsNotUniqueInDatabase(string name)
{
//call to the database...
return false;
}
}
Thanks!
Anna
Wondering why ValidatePassword is a void and throws an exception instead of returning MembershipCreateStatus. So on invalid password it would return MembershipCreateStatus.InvalidPassword
According to the example code in the article at CodeProject, you should initialize the library like this:
var stringProvider =
new ResourceStringProvider(Resources.LocalizedStrings.ResourceManager);
ModelMetadataProviders.Current = new LocalizedModelMetadataProvider(stringProvider);
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(
new LocalizedModelValidatorProvider(stringProvider));
However, using the latest version of the library, I get a compiler error on the last line, because the class LocalizedModelValidatorProvider has only a parameterless constructor.
Is the sample code out of date?
If model have DisplayAttribute for property "Name", for example, in table LocalizedTypes create record with TextName = Name_NullDisplayText, and don't create record with TextName = Name, and localization not work. If model not have DisplayAttribute for property "Name", in table LocalizedTypes create record with TextName = Name, and localization work properly.
In FileLocalizedTypeRepository.cs, the GetLanguage method, loads the entire JSON prompts file every time a translation is requested.
Lines 241-246 can be replaced with:
prompts = LoadLanguage(culture) ?? new TypePromptCollection(culture);
_languages.Add(culture, prompts);
I'll open this as a separate issue which it indeed is.
So, I run the site and while the site is running change some texts for en-US from default to something else. For instance
"Text": "The {0} field is required."
to
"Text": "aaaa {0} field is required."
Save in RavenDB studio and refresh the site. The modified text is gone and overwritten with the default en-US text again.
This has nothing to do with missing texts. The DefaultUICulture is set to "en-US" but the actual current culture of my page is set to "sl-SI" (I do it via SetCulture attribute on my ControllerBase, which essentially just sets the Thread cultures).
So what we have here is two fold.
Thank you for this project, it's a great approach for localization.
It would be nice if we could replace the default DataContractJsonSerializer via the default container (MVC 3).
The images for the edit, delete buttons do not show up in FF or Chrome. If FF it is impossible to edit any of the translations
Behavior similar to issue #6, a NullReferenceException occurs when a Compare attribute is used to compare two fields after submission.
I have double-checked this against your Admin Test Project, which also fails in the same way, as described in issue #6, except line number is 207.
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Source=System.Web.Mvc
StackTrace:
at System.Web.Mvc.CompareAttribute.IsValid(Object value, ValidationContext validationContext)
at System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(Object value)
at Griffin.MvcContrib.Localization.LocalizedModelValidatorProvider.MyValidator.d__5.MoveNext() in C:\projects\git\griffin.mvccontrib\source\Griffin.MvcContrib\Localization\LocalizedModelValidatorProvider.cs:line 207
at System.Web.Mvc.ModelValidator.CompositeModelValidator.d__5.MoveNext()
at System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model)
at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
InnerException:
I've integrated griffin.mvccontrib v 1.1.3 with my mvc3 application.
I've added "FieldMustBeNumeric" and "FieldMustBeDate" keys to LocalizationStrings.resx
But "data-val-number" validation attribute doesn't appear in html.
What's wrong?
How can i add locatization for "FieldMustBeNumeric" and "FieldMustBeDate" validation rules?
I want to propose a useful modification to the ResourceStringProvider I'm currently using.
/// <summary>
/// Get a localized string for a model property
/// </summary>
/// <param name="model">Model being localized</param>
/// <param name="propertyName">Property to get string for</param>
/// <returns>Translated string</returns>
public string GetModelString(Type model, string propertyName)
{
var result = GetString(Format(model, propertyName));
return string.IsNullOrEmpty(result) ? GetString(Format(propertyName)) : result;
}
/// <summary>
/// Get a localized metadata for a model property
/// </summary>
/// <param name="model">Model being localized</param>
/// <param name="propertyName">Property to get string for</param>
/// <param name="metadataName">Valid names are: Watermark, Description, NullDisplayText, ShortDisplayText.</param>
/// <returns>Translated string</returns>
/// <remarks>
/// Look at <see cref="ModelMetadata"/> to know more about the meta data
/// </remarks>
public string GetModelString(Type model, string propertyName, string metadataName)
{
var result = GetString(Format(model, propertyName, metadataName));
return string.IsNullOrEmpty(result) ? GetString(Format(propertyName, metadataName)) : result;
}
This simply provides a default fallback to retrieve model property display names and metadata.
->MyModel_FullName = Full name
if not found, checks for:
->FullName = Full name
This still allows for overriding the defaults which is a win-win situation.
Thanks for your contribution :)
I get the following problem when trying to use the System.Web.Mvc.Compare attribute on my model.
Object reference not set to an instance of an object.
Call stack location:
Griffin.MvcContrib.DLL!Griffin.MvcContrib.Localization.LocalizationModelValidatorProvider.MyValidator.Validate() Line 194 + 0x35 bytes
Source file information:
Locating source for 'D:\Tfs\External\griffin.mvccontrib\griffin.mvccontrib\source\Griffin.MvcContrib\Localization\LocalizedModelValidatorProvider.cs'. Checksum: MD5 {a4 85 85 22 c3 89 75 c4 a7 85 35 77 1e a4 29 1f}
The file 'D:\Tfs\External\griffin.mvccontrib\griffin.mvccontrib\source\Griffin.MvcContrib\Localization\LocalizedModelValidatorProvider.cs' does not exist.
Looking in script documents for 'D:\Tfs\External\griffin.mvccontrib\griffin.mvccontrib\source\Griffin.MvcContrib\Localization\LocalizedModelValidatorProvider.cs'...
Looking in the projects for 'D:\Tfs\External\griffin.mvccontrib\griffin.mvccontrib\source\Griffin.MvcContrib\Localization\LocalizedModelValidatorProvider.cs'.
The file was not found in a project.
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\crt\src'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\src\mfc'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\src\atl'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\include'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: D:\Tfs\External\griffin.mvccontrib\griffin.mvccontrib\source\Griffin.MvcContrib\Localization\LocalizedModelValidatorProvider.cs.
The debugger could not locate the source file 'D:\Tfs\External\griffin.mvccontrib\griffin.mvccontrib\source\Griffin.MvcContrib\Localization\LocalizedModelValidatorProvider.cs'.
I noticed that with Remote Attribute localization not work at all.
Hello,
It looks like it is not possible anymore to override the ViewLocalizer class and handle cache that way (as suggested on CodeProject)
I tried to register my new class in every possible way within the Autofac builder but the GriffinWebViewPage is unable to find it and is constantly initializing the ViewLocalizer(IViewLocalizationRepository)
Is there any other suggestion on how to handle cache ?
My pages are getting bigger and bigger and i'm getting hundreds of sql requests that I would like to avoid :)
Thanks
Hey Jonas, great work overall. But where are the docs for RavenDB? I cannot find them in Griffin.Mvc.Docs or in wiki. In CodeProject article you say: "I've chosen SqlServer as the data source in this article. The wiki at github shows how to use the other sources." But there is no RavenDB wiki article. Or is it?
Hi @jgauffin !
I successfully updated, compiled and runned and tested your project in my fork with VS2015, MVC5 and .NET Framework 4.5.2.
Admin backend at the moment have some issues caused by MVC3 template.
Project is forked here
https://github.com/omarpiani/griffin.mvccontrib
it will be awesome to use CI of appveyor for new releases of this package.
For example https://ci.appveyor.com/project/fiorebat/griffin-mvccontrib/build/1.0.5 builds, test requiring SQLExpress are failing, but I will replace them with LocalDB
Are you still available for an hot pull in this project?
Regards
Hello EveryOne,
I'm Using Mvc4 and I have this error 'Could not find a part of the path 'C:\AED\AED.WebMVC4\App_Data\ViewLocalization.sv-SE.dat'.
Can you Help Me please?
Best regards
Helmi
Currently a null reference exception is thrown when trying to use validation attributes that override IsValid(Object, ValidationContext) in conjunction with griffin validation extensions.
Griffin.MvcContrib.Admin no use master page, and jquery scripts, for example "Show metadata", don't work.
Hello I tried to cache ViewLocalizer and succeeded, but I am struggling with RepositoryStringProvider
I did subclass of ViewLocalizer and RepositoryStringProvider in following way:
public class CachedViewLocalizer : ViewLocalizer
{
public CacheWrapper CacheRepository { get; set; }
public CachedViewLocalizer(IViewLocalizationRepository repository): base(repository)
{
this.CacheRepository = new CacheWrapper();
}
public override string Translate(string viewPath, RouteData routeData, string text)
{
string prompt;
if (CacheRepository.IsSet(text)) return text;
prompt = base.Translate(viewPath, routeData, text);
CacheRepository.Set(text, prompt, 600);
return prompt;
}
}
// caching type translations
public class CachedTypeLocalizer : RepositoryStringProvider
{
/// <summary>
/// Gets or sets the instance of the class which wraps Cache Object
/// </summary>
public CacheWrapper CacheRepository { get; set; }
public CachedTypeLocalizer(ILocalizedTypesRepository repository) : base(repository)
{
this.CacheRepository = new CacheWrapper();
}
protected override string Translate(Type type, string name)
{
var promptName = type.FullName + "." + name;
string prompt;
if (CacheRepository.IsSet(promptName)) return promptName;
prompt = base.Translate(type, name);
CacheRepository.Set(promptName, prompt, 600);
return prompt;
}
}
In Global.asax
private static void RegisterLocalizationFeaturesInTheContainer(ContainerBuilder builder)
{
builder.RegisterControllers(typeof(Griffin.MvcContrib.GriffinAdminRoles).Assembly);
builder.RegisterControllers(Assembly.GetExecutingAssembly());
//builder.RegisterType<RepositoryStringProvider>().AsImplementedInterfaces().InstancePerLifetimeScope();
builder.RegisterType<CachedTypeLocalizer>().As<RepositoryStringProvider>().InstancePerLifetimeScope();
//builder.RegisterType<ViewLocalizer>().AsImplementedInterfaces().InstancePerLifetimeScope();
builder.RegisterType<CachedViewLocalizer>().As<ViewLocalizer>().InstancePerLifetimeScope();
builder.RegisterType<SqlLocalizedTypesRepository>).AsImplementedInterfaces().InstancePerLifetimeScope();
builder.RegisterType<SqlLocalizedViewsRepository>).AsImplementedInterfaces().InstancePerLifetimeScope();
builder.RegisterInstance(new AdoNetConnectionFactory("CustomerConnection")).AsSelf();
builder.RegisterType<LocalizationDbContext>().AsImplementedInterfaces().InstancePerLifetimeScope();
}
but with error
System.InvalidOperationException: Failed to find an 'ILocalizedStringProvider' implementation. Either include one in the LocalizedModelMetadataProvider constructor, or register an implementation in your Inversion Of Control container.
Do you have any suggestion
Thanks
the URL's generated ( @item.CreateUri(Url) ) while using plugins seems to generate wrong links. to reproduce the problem click one of the plugin's urls, after that every link on the menu seems to fall apart and show wrong links, also additional actions don't seem to be resolved correctly
My specific case brought me to use the select html helper for enum
Problem is that I'm getting the "Object reference not set to an instance of an object." error
After alot of digging, here is what I have found :
Since I'm not fully understanding what is going on behind the scenes in all that, I stopped there :)
I was first using the nuget version of the library and got these errors
And after that I donwloaded the sources in order to investigate where the error is comming from
I'm not sure if I'm going the right way ? Maybe I'm missing something more general (like the registratio of the DefaultTagBuilderFactory) ? Any pointer would be helpful !
Thanks
When using RemoteAttribute with unobstrusive validation the text is not correctly shown, neither if I set my ErrorMessage on Attribute
Hello,
the issue is related to the localization library.
If i decorate a property with the EmailAddressAttribute (so it is validated as an email) it seems that the library recognize it as its base type (DataTypeAttribute).
The validation message is not displayed as untranslated, too, in the pages (the notation with the []).
The EmailAddressAttribute class belongs to the Assembly System.ComponentModel.DataAnnotations.dll, v4.0.0.0
Another issue i had is that i can't understand how the translations are automatically inserted in the database.. i found the ID field that i've never displayed (@Html.Display(m=>m.ID) so i expect the library doesn't add it.. I expect that just the text shown somewhere in my application should be translated.
I don't think you should be using DependencyResolver as that is specific to Web.Mvc. Your membership provider should be independent of Mvc. Also the error you give is misleading as it's not actually a service locator that is missing, but rather dependency resolver:
get
{
if (_userService == null)
{
_userService = DependencyResolver.Current.GetService<IAccountRepository>();
if (_userService == null)
throw new InvalidOperationException(
"You need to assign a locator to the ServiceLocator property and it should be able to lookup IAccountRepository.");
}
return _userService;
I'm having a beast of a time unit testing this as the dependencyresolover is always failing for some reason, even if I initialize it in my test setup fixture. I think if you would just assign the service locator, it would be sufficient:
UnityServiceLocator locator = new UnityServiceLocator(_container);
ServiceLocator.SetLocatorProvider(() => locator);
In Html/FormHtmlHelper methods you call:
_tagBuilderFactory.Create("input")
but there should be used
public ITagBuilder Create(string tagName, string type)
variant instead, as 'input' builders are registered with 'input.type' key.
Using griffin.mvccontrib break functionality of RemoteAttribute in models.
Does this library support Web API out of the box?
Hi
I've been looking around for a decent solution for localizing model validators and your solution seems to be the best around. I can tell you've put a lot of effort into this package and I'm thankful for that. It's strange that it's not built into MVC (especially now in MVC 4), but you can't get everything you wish for can you?
Anyway, I was going to try it out, so I downloaded it through NuGet in Visual Studio 2012 Express RTM, but after adding the code for Global.cs I get this error:
Quote:
'Griffin.MvcContrib.Localization.LocalizedModelValidatorProvider' does not contain a constructor that takes 1 arguments
I tried to remove the "stringProvider", but then I instead got this at run-time:
Quote:
Failed to find an 'ILocalizedStringProvider' implementation. Either include one in the LocalizedModelMetadataProvider constructor, or register an implementation in your Inversion Of Control container.
Am I doing something wrong, or is it because I'm using Visual Studio 2012 or something else?
Using example project (PluginSystemDemo) for testing, added to PluginService
private readonly EmbeddedFileProvider _embeddedContentProvider =
new EmbeddedFileProvider(VirtualPathUtility.ToAbsolute("~/"));
and in constructor, I added this provider to GriffinVirualPathProvider before the EmbeddedViewFileProvider named _embededProvider.
And in Startup method, added call
_embeddedContentProvider.Add(new NamespaceMapping(assembly, Path.GetFileNameWithoutExtension(assembly.Location)));
I added a Content folder to the Plugin.Messaging project Areas folder, created a css file, configured it to be an embedded resource and link to ~/Areas/Messaging/Content/StyleSheet1.css.
If I run the project and check the CSS file, I see all the inherits in the file, as if itβs processed as a view by the ExternalViewFixer, rendering it unusable by the browser. Same happens to JS files.
However, if i don't add the _diskFileProvider to the GriffinVirualPathProvider in PluginService for runtime edits, the css and js files are rendered normally to the browser.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.