Custom editortemplate when property has some attribute on it - c#

This is what the implementation would look like
public class Product
{
public integer id {get;set;}
[MultiLangual]
public string name {get;set;}
}
In the database, name would contain something like:
{en:Pataoto, nl: Aardappel, de: Patat, fr: pommes de terre}
This would contain all the translated fields, that a client has given to his own product.
(in this case: a patato).
In the frontend, this would appear as multiple html elements, which i (somehow) detect which language it is, on submitting the form.
My question is, how would i do this? I'm always stuck on creating the attribute and don't know where to continue...
In my attribute, i shouldn't do a lot, just something like this (i think):
public class MultiLangualAttribute : Attribute
{
public MultiLangualAttribute() : base()
{
}
public override string ToString()
{
return base.ToString();
}
}
But how would i detect everything in my views and create a custom layout for it (this should work with and .
It would only contain text.
Any ideas or a better implementation of above, would be VERY usefull :)

I think the better (arguably) implementation is standard way of application localization.
You define your resources and strings under App_GlobalResources folder you will have to create.
For example you will create file Fruits.resx with all your fruits you want to translate in your system language.
Afterwards you will create Fruits.de.resx, Fruits.es.resx etc, with all the languages you want to have in your website.
It is also possible to update the resources at runtime.
Its too much to describe all the approach in this answer, I would rather provide a link or two with detailed tutorial on MVC application localization:
This is classic ASP.NET MVC localization explanation:
Globalization And Localization With Razor Web Pages
Another explanation of the same thing, little more detailed is here:
ASP.NET MVC Localization: Generate resource files and localized views using custom templates
This should be enough for you to localize your app the standard way.
This is a little more advanced approach, when they use language as part of the URL you accessing.
es.yourdomain.com will be in Spanish, fr.yourdomain.com will be in French:
Localization in ASP.NET MVC – 3 Days Investigation, 1 Day Job
With regards to your approach (storing different languages in the database) here's link to microsoft approach for this. Its much more involved and complex, and I am not sure if benefitting you by its complexity, since you end up using database to fetch every single string in your app. Not the most efficient, but possible approach as well:
Extending the ASP.NET Resource-Provider Model
Hope this all will be of helps to you & good luck

Related

.NET c# - Customize Display Attribute

.NET MVC Application EF code first, using Identity 2
Each application user belongs to a specific user_type (ApplicationUser.user_type). (the application uses Identity roles too, but they are completely independent of this user_type).
also, I am extensively using Display attribute on properties of models and viewmodels with:
[Display(Name="some literal"]
public string someProperty { get; set; }
and in the view:
#Html.LabelFor(model => model.someProperty)
or
#Html.DisplayNameFor(model => model.someProperty)
But now I am required to, in some cases, display different things if the logged-in user is of a specific user_type ("Client").
What would be the best way to implement this? I am guessing maybe its possible to customize the Display attribute so that it accepts a parameter "userType", so I could decorate the properties with something like:
[Display(Name="This will be shown to users with user_type: Client", UserType="Client"]
[Display(Name="This will be shown to everyone else"]
public int myProperty { get; set; }
or something like that... but I have no idea how to do it... any help is appreciated
To me it seems that you are trying to put too much logic/responsibility in one place.
I recon you would manage to come up with something to deal with this scenario, but, if you do, you'll risk ending up with an inter tangled property which behaviour will depend on all sorts of external parameters. The more you'll add, the more complex it will become. That can be hard to maintain.
I am not fond of "keep it simple" but I think it does apply here, by keeping it simple in maintenance.
IMO you have a couple of options to help you out:
create a complete new view and a model for this client page
add a propery to your (view)model which contains the string.
add the string to the page and handle it with razor.
use a viewbag or similar temp data container
So, to sum it: I dont think expanding the Display attribute would be the way to go here and consider one (or another) of the methods mentioned above.

C# extend MVC maxlengthattribute

I have already searched here to answer my question, and the closest I ever got was that post, but it still does not completely clarify the matter to me, so I will ask.
What I need is extending maxlengthattribute in the way that when I set it inside the C# file,
[MaxLength(50)]
[Display(Name = "Project Description")]
public string ProjectDescription { get; set; }
the attribute "maxlength" will be added inside the tag and will be <\stuff stuff maxlength = "50">
I have initially implemented it as writing html-helper to modify TextBoxFor, however, this is out of option since project is tightly intertwined with .js, and inserting renamed method will break a code, which will be a pain to fix.
The answer I referred above provides the closest explanation of what I need, but it looks like I will need to declare attributes (like inside ( ) in function), which I do not see there.
At this point I can either try modifying JS file on the server-side, or extending maxlengthattribute. Thus far, latter is preferable for me, thus I would like to ask how to properly extend it inside the c# file.
Thank you very much in advance!
You can write a custom dataannotation provider. The max length attribute will get added to the control.
Refer this link

Common Message/Error/Status to used across jquery or C#

There are times when we use same error or success message/checking of some status both in jquery & c#.
For consistency, we can define all message/status flag in as static class and use it wherever needed in c#.
Just an example:
C#
public class MyConstant
{
public static string Admin = "AdminRole";
public static string Approver= "ApproverRole";
}
if(userRole==MyConstant.Admin || userRole==MyConstant.Approver)
{
//more work
}
jquery:
if(userRole=="AdminRole" || userRole=="ApproverRole")
{
//more work
}
In stead hard coding msg/status in jquery, I would prefer approach similar to C#. Would be better to have common place to pull for client/service side.
How can I achieve similar in jquery? Better to say, How can I share common msgs/status flags between jquery & C#. I can think of following options:
Use Database. Cons: hitting DB every time may not be good idea.
Define some classes/property for msgs/status flags separately in jquery. Cons: duplicate; have to ensure all of them in sync.
maybe CMS but not necessarily, will be used in every application
Is there any better approach to share common Message/Error/Status to used across jquery or C#?
Thoughts?
One possible solution is T4 (text templates).
Just imagine a T4 which iterates each enumeration value (why classes of constants? use enumerations!) and creates an object literal like this in JavaScript:
var Roles = { "AdminRole": 1, "ApproverRole": 2 };
If you've never heard about T4, it's the text templating engine behind Visual Studio templates. For example, Entity Framework uses it to generate model classes.
Once you've created the text template, you can sync C# enumeration to JavaScript object literal from Visual Studio when you build your project or running the template manually (right-click on T4 and choose "Run custom tool").
Learn more about T4
I would consider enums for status codes, but you can stay with your strings (no problem). To better address JavaScript part use solution presented here: https://stackoverflow.com/a/2383215/3170952, that is:
my.namespace.Roles = {
ADMIN: "Admin",
APPROVER: "Approver"
}
Then you have one place where you define literals in JS. Better yet, you can weave C# literals into your JS (if you define it in one of ASP.NET MVC views or have other mechanism of incorporating C# into JS files). Then you have one place of definition statically checked during compilation time.

Is there an equivalent of Java's Spring MVC style url mapping for C#/.NET?

I am looking for the C# equivalent of Spring MVC's url mapping using annotations, i.e in Java I can write:
#Controller
#RequestMapping("/some-friendly-url/")
class MyController
{
#RequestMapping(value = "/{type}/more-seo-stuff/{color}", method = RequestMethod.GET)
public List<SomeDTO> get(#PathVariable String type,
#PathVariable String color,
int perPage) {
...
}
#RequestMapping(method = RequestMethod.POST)
public String post(#RequestBody SomeDTO somethingNew) {
...
}
}
It's actually much more powerful than this simple example as anyone familiar the the concept knows.
I've tried to search on how to achieve the same with either ASP.MVC 3 or with MonoRail and both frameworks seem to be based on RoR's convention-over-configuration "//" philosophy and it would be hard to achieve the above with them and require a lot of bespoke routing entries outside the controller class with only a small subset of the functionality available via attributes. Spring.NET does not seem to address this either stating that ASP.MVC's routing functionality is sufficient.
Is there anything out there in the C# world that provides this type of functionality? I was just about to start looking into writing something of my own to address this, but I was hoping not to have to do that.
Edit: Finally found the "AttributeRouting" project which is available on NuGet as well: https://github.com/mccalltd/AttributeRouting/wiki/1.-Getting-Started. Works perfectly. Doesn't support to full range of features that Spring MVC does, but supports most of it.
Also Akos Lukacs pointed to another good library below by ITCloud. However that one unfortunately is not available on NuGet.
Sure, you can use Spring.NET:
http://www.springframework.net/
I Eventually used https://github.com/mccalltd/AttributeRouting/wiki/1.-Getting-Started. Posting this only now for the sake of keeping the question complete.

Are DataAnnotations attributes cached? If so, how to switch between different cultures?

I have a site that supports both US and Canada. My zip code validation uses a custom RegEx attribute that I created to allow my RegEx pattern to be localized:
public class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.RegularExpressionAttribute
{
public RegularExpressionAttribute(Type patternResourceType, string patternResourceName)
: this(ResourceHelper.GetString(patternResourceType, patternResourceName))
{
this.PatternResourceName = patternResourceName;
this.PatternResourceType = patternResourceType;
}
}
The problem is, if the client switches from one country to the other, it holds onto the RegEx pattern from the first country. So if they load it in US, it keeps the US zip pattern when they switch to Canada, and vice versa.
How can I get this to always use the proper culture?
Thanks in advance.
I found the answer. Create a custom DataAnnotationsModelMetadataProvider. It's really easy. You just need to override a single method. This gets called every time a property attribute is required. There's quite a few samples on the web for this, eg: http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html and http://www.freewebdevelopersite.com/2011/07/10/custom-metadata-providers-in-asp-net-mvc/.
Cheers

Categories