How to remove data memeber form validtion summary in Silverlight MVVM - silverlight-4.0

In SilverLight Validation summary shows error in two parts one is data member name and the other is error message.
Data member is the binding source Property name .I just don't want to show the datamember name.
How can i remove this from validation summary?

I have found the solution .
By using DisplayAttribute of DataAnnotations we can change the display name of the viewmodel property.
For Example:
[Display(Name="First Name")]
public string FirstName
{
get { return firstName; }
set
{
firstName = value;
RaisePropertyChanged("FirstName");
}
}
By setting Display now ValidationSummary will Show Display attribute name instead of propertyName.
And if you don't want to show any name just errors in Summary just set Display attribute as [Display(Name="")]

Related

Send JSON with list to Controller

I am trying to send following JSON to my controller:
[
{
"collection": "col1",
"uuid": [
"11:22:33:44:55:66",
"11:22:33:44:55:66"
]
},
{
"collection": "test"
}
]
Every object "collection" contains a list of strings symbolized by the uuids.
My model looks like this:
public class DummyDeviceApiModel {
[Display(Name = "UUID")]
[StringLength(36)]
public List<string> uuid {get; set;}
[Display(Name = "Collection")]
public string collection {get; set;}
}
and my controller function like this:
public async Task<ActionResult<DummyDeviceModel>> PostCreateDummyDevice(List<DummyDeviceApiModel> ddpm)
What works is when I just send the collection part, but the UUID with its list makes problem:
System.InvalidCastException: Unable to cast object of type
'System.Collections.Generic.List`1[System.String]' to type
'System.String'
.
Any idea what I am doing wrong? The issue seems to be the "second" list in the model.
Thanks
Stephan
[StringLength(36)] is a validation attribute for type string not arrays of string or List<string>. The exception is probably happening behind the scenes as it tries to validate on your property since it is of type List<string>. If you want to do what I think you do, create a custom validation on your list to make sure you only have strings in your list which are less than or equal to a length of 36, then you need to either implement IValidatableObject on your model (class) or create a custom Validation Attribute for validation by creating a class which inherits from ValidationAttribute. You can read more about how to implement this interface and/or create a custom attribute at MSDN: (https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.1). As a test to see if it is indeed the StringLength attribute which is throwing the exception, comment out that particular Validation Attribute in your code and see if it runs without error.

Using model's property for requiredif statement without putting it in an actual DOM

I need to validate input field based on a property that is within the same model, however is not being used in the DOM. Something like so:
[RequiredIf("NameRequired", ErrorMessage = "Name is required")]
public string Name {get;set;}
public bool NameRequired {get;set} = true;
DOM:
#HTML.TextBoxFor(model=>model.Name);
NameRequired by default is true however it can be changed in other places of the code, which is why it is needed, however when running this code expressiveannotations complains that NameRequired field is not found in the DOM
Put it in the DOM as a hidden field (using #Html.HiddenFor() )

ASP.NET Core DisplayAttribute Localization

According to the documentation:
The runtime doesn’t look up localized strings for non-validation attributes. In the code above, “Email” (from [Display(Name = "Email")]) will not be localized.
I'm looking for a way to localize text in DisplayAttribute. Any suggestions to do it in a proper way(s)?
You can set the ResourceType on the DisplayAttribute which can be used to localize your text.
Add a resource .resx file to your project e.g. MyResources.resx, and add a resource for your field:
Then reference the name of the field and the MyResources type in your DisplayAttribute
[Display(Name = "RememberMe", ResourceType = typeof(MyResources))]
public bool RememberMe { get; set; }
The localized resource will be pulled through automatically (see the text box)
Having a Central location for all your localization whether in view or dataannotations is the best approach I can think of, and this how I got to work.
In Startup.cs file after you installed nuget packages for localization add the following code
services.AddMvc().AddViewLocalization().AddDataAnnotationsLocalization(options =>
options.DataAnnotationLocalizerProvider = (type, factory) => new StringLocalizer<Resources>(factory));
services.Configure<RequestLocalizationOptions>(options => {
var cultures = new[]
{
new CultureInfo("en"),
new CultureInfo("ar")
};
options.DefaultRequestCulture = new RequestCulture("en", "en");
options.SupportedCultures = cultures;
options.SupportedUICultures = cultures;
});
This way the DataAnnotationLocalizerProvider will be from the Resources.{culture}.rex -( The Resource file must have an access modifier of No code gen)- assuming that no resources will be needed for the default language, and to be able to access the resource file since no code will be generated and empty class with the same name must be created.
and in _ViewImports.cshtml file inject the following
#inject IHtmlLocalizer<Resources> Localizer
by doing this you now have a global variable Localizer to be used in any of the views for localization purposes.
you can find further information on Globalization and localization in ASP.NET Core
For those who struggle (#lucius, #vladislav) with error:
Cannot retrieve property 'Name' because localization failed. Type 'Xxxx.EmployeeResx' is not public or does not contain a public static string property with the name 'FirstName'.
It is caused by access modifier on .resx files which is by default set to Internal (in my case it was No code generation). Change it to public in Access Modifier dropdown in the resource file toolbar.
After that you should be able to see the properties from the resource type:
Also, consider not using special signs in field names as they are a basis for auto-generated C# property names. The field names are converted into C# friendly names and that is why you can end up with inconsistency between name of resource file field and name of auto-generated property. Best to avoid any hyphens - or dots . Underscores _ are fine. You can always look up how the auto-generated properties look like in resource_file_name.Designer.cs class under the related resource file.
Many thanks to Bala Murugan who wrote a good article concerning this topic on Code Digest.
Actually I found an simple solution for the followers. The display name in most of time is used in the label of an input field. So do this if you like:
<label asp-for="Email">#Localizer["Email"]</label>
of course, you can pass the property name by #Html.DisplayNameFor, but most of time, this one already works well.
I have just created a project which demonstrates localization including localization of Display attribute for class properties as well as enums.
The project can be found here https://github.com/feradz/ASPNetCoreLocalization/wiki
The Display attribute has to be localized using the approach prior to ASP.NET Core 1.0. Have a look at the DataAnnotations.resx file in the project.
The Name property of Display cannot contain empty spaces, and special characters.
[Display(Name = "NoSpacesAndSpecialChanractersHere", ResourceType = typeof(Resources.DataAnnotations))]
public string FirstName { get; set; }
ResourceType should be the fully qualified resource class name (i.e. including the name space).

Yii Custom Validator creation

I am new to Yii framework, so please any one help me for this question
How to create custom validator class for the following validation,
I am having one table list , it is having listname and types on it, my validator want to check the list name to be unique for the specific type, for example,
listName Type
test1 1
test2 1
test3 2
when I insert a new list name validator, I want to retrieve the listnames and type and provide error if it is not unique for the specific type.
Well creating a custom validator method is really simple if that's what you are looking for.
You need a to add an element to rules() method in your Model (i.e protected/model/youTableName.php)
return array(
array('listName', 'uniqueForType', 'type')
);
Create a method to youTableName.php named by the validator name.
public function uniqueForType($field, $params)
{
$filedToCompare = $this->$field;
$fieldToCompareWith = $this->$params;
// Do your checking and comparing
if($weHaveAnError) {
$this->addError($field, printf("This listName already exists for type %s", $this->$params));
}
}
That should do the trick. Got that information form http://www.yiiframework.com/forum/index.php/topic/20399-conditional-validation-rule/

How to hide a Model class field based on custom logic in MVC Web Api RC

I am using Asp.Net Mvc Web api RC.
I wanted to hide the fields/properties of my model class using custom attribute. Below is my class:
public class Employee
{
public int EmpId { get; set; }
public string Name{ get; set; }
//Wanted to hide this attribute based on custom logic. Like for a certain role, i want to hide the designation
public string Designation{ get; set; }
public string Department{ get; set; }
}
How can we achieve using Data Annotations. I mean i wanted to create a separate attribute to use in this manner:
[HideForRoles(Roles="Admin,Writer")]
public string Designation{ get; set; }
UPDATE :
As i am developing web api. The response is serialized to either XML or Json format depend upon the formatter. So better question would be how not to allow the fields to be serialize while writing to the response.
However one option could be using IgnoreDataMember attribute. Like
[IgnoreDataMember]
public string Designation{ get; set; }
But the above is a compile time declaration where i cannot impose any condition.
Question: How to ignore the field/property while serializing based on some condition at runtime?
Totally missed on the first go-round that you were using Web Api, my apologies.
What you want to do is to create a custom formatter.
There's a good article here on the flow/differences between MVC and Web Api (which I'm getting that you already understand, still some valid points here):
http://lostechies.com/jimmybogard/2012/04/10/asp-net-web-api-mvc-viewmodels-and-formatters/
And here's a sample implementation of a custom formatter:
http://www.tugberkugurlu.com/archive/creating-custom-csvmediatypeformatter-in-asp-net-web-api-for-comma-separated-values-csv-format
Building from that, you would use reflection to read from the attributes, building on the custom ActionFilterAttribute you would have to write, where you evaluate the user's roles and determine which fields should be omitted/included. Here's a sample of an action filter:
https://github.com/MisterJames/MovieFu/blob/master/MovieFu/ActionFilters/UserNameFilter.cs
Hope this helps more.
Cheers.
Your best bet is to return a dynamic object. In this case you can say:
dynamic viewModel = new ExpandoObject();
viewModel.Id = 12;
if(role == "Admin")
{
viewModel.SecureStuff = "Others should not see it";
}
It won't be as straightforward as that, as you'll need to have the fields conditionally rendering in the view. But you can get most of the way there through the attribute.
You will need to make your custom attribute meta-data aware, then check the attribute in your view. A solution is posted here: Can't get Custom Attribute Value in MVC3 HTML Helper.
Cheers.
I have done the authorization checking in the model repository itself. Rather ideal way was to create custom formatters for hiding the certain fields based on some condition.
After getting the list of Employees from db and have them in list, i iterated again and place a NULL to the fields i don't want to display.
The code i have written as:
foreach (var employee in listEmployees)
{
//get all props. of Employees object using reflection
var props = employee .GetType().GetProperties();
//loop through each field to match with the field name to remove/place null
foreach (var propertyInfo in props)
{
var fieldName = propertyInfo.Name;
if (fieldsNamesToRemove .Contains(fieldName))
{
propertyInfo.SetValue(employee , null, null);
}
}
}
here fieldsNamesToRemove is a list that i created dynamically based on roles of current user.
This solution actually placing a NULL for the fields we do not want display. As a result in JSon format the fields are not displaying but in the XML the fields are displaying with syntax like lt; Designation i:nil="true"/ gt;, but manageable as we need to deal mostly with json response.
Thanks Ali and MisterJames for your valuable suggestions