ASP.NET MVC 2 RTM - Multiple-attribute validation with localization using data annotation fails - asp.net-mvc-2-validation

My resource file is working fine and the two keys (ValNameRequired and ValNameLength) are defined in the resource file. But when you have more than one attribute with localization, then the validation does not work. Anyone with a solution?
public class ContactModel
{
[Required(ErrorMessageResourceType = typeof(ViewRes.Contact), ErrorMessageResourceName = "ValNameRequired")]
[StringLength(50, ErrorMessageResourceType = typeof(ViewRes.Contact), ErrorMessage = "ValNameLength")]
public string Name { get; set; }
}

I figured it out. The StringLength attribute was wrong. You have to use ErrorMessageResourceName, not ErrorMessage. It should be like this:
[StringLength(50, ErrorMessageResourceType = typeof(ViewRes.Contact), ErrorMessageResourceName = "ValNameLength")]

Related

Passing dynamically generated value to NUnit Custom Attribute

For our test scenarios - based on configuration of the application, we may want to either enable or disable a scenario. For this purpose, I created a custom IgnoreIfConfig Attribute like this :
public class IgnoreIfConfigAttribute : Attribute, ITestAction
{
public IgnoreIfConfigAttribute(string config)
{
_config = config;
}
public void BeforeTest(ITest test)
{
if (_config != "Enabled") NUnit.Framework.Assert.Ignore("Test is Ignored due to Access level");
}
public void AfterTest(ITest test)
{
}
public ActionTargets Targets { get; private set; }
public string _config { get; set; }
}
Which can be used as follows :
[Test, Order(2)]
[IgnoreIfConfig("Enabled")] //Config.Enabled.ToString()
public void TC002_DoTHisIfEnabledByConfig()
{
}
Now This attribute would only take a constant string as an input. If I were to replace this with something generated dynamically at the runtime, Such as a value from Json file - How can I convert it to a Constant. Constant Expression, TypeOf Expression or Array Creation Expression of Attribute parameter type ? Such as Config.Enabled ?
You can't do as you asked but you can look at the problem differently. Just give the attribute the name of some property in the JSON file to be examined, e.g. "Config".
As per Charlie's suggestion : I implemented it like this -
PropCol pc = new PropCol(); // Class where the framework reads Json Data.
public IgnoreIfConfigAttribute(string config)
{
pc.ReadJson();
if(config = "TestCase") _config = PropCol.TestCase;
// Here TestCase is a Json element which is either enabled or disabled.
}

unable to deserialise odata to Dataset using JSON.NET due to odata.metadata

I'm trying to get some help on deserializing a JSON reponse to a DataSet.
in theory this should be easy as using this example
http://www.newtonsoft.com/json/help/html/DeserializeDataSet.htm
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
DataTable dataTable = dataSet.Tables["Table1"];
However the JSON I am getting back is supplemented / decorated using "odata.metadata"
see below.
{"odata.metadata":"http://nodts004.cloudapp.net:7058/TNPMaster2016Dev/OData/$metadata#NP_Customer","value":[{"No":"01121212","Name":"Spotsmeyer's Furnishings","City":"Miami","Amount":"0","Customer_Posting_Group":"FOREIGN","Balance_LCY":"0","Sales_LCY":"0","Profit_LCY":"0","Balance_Due_LCY":"0","Payments_LCY":"0","Inv_Amounts_LCY":"0","Cr_Memo_Amounts_LCY":"0","Outstanding_Orders":"0","Shipped_Not_Invoiced":"0","No_of_Quotes":0,"No_of_Blanket_Orders":0,"No_of_Orders":6,"No_of_Invoices":0,"No_of_Return_Orders":0,"No_of_Credit_Memos":0,"No_of_Pstd_Shipments":0,"No_of_Pstd_Invoices":0,"No_of_Pstd_Return_Receipts":0,"No_of_Pstd_Credit_Memos":0,"No_of_Ship_to_Addresses":0,"Outstanding_Orders_LCY":"0","Shipped_Not_Invoiced_LCY":"0"},{"No":"01445544","Name":"Progressive Home Furnishings","City":"Chicago","Amount":"0","Customer_Posting_Group":"FOREIGN","Balance_LCY":"1499.02","Sales_LCY":"1499.02","Profit_LCY":"305.12","Balance_Due_LCY":"1499.02","Payments_LCY":"0","Inv_Amounts_LCY":"1499.02","Cr_Memo_Amounts_LCY":"0","Outstanding_Orders":"0","Shipped_Not_Invoiced":"0","No_of_Quotes":0,"No_of_Blanket_Orders":0,"No_of_Orders":0,"No_of_Invoices":0,"No_of_Return_Orders":0,"No_of_Credit_Memos":0,"No_of_Pstd_Shipments":1,"No_of_Pstd_Invoices":1,"No_of_Pstd_Return_Receipts":0,"No_of_Pstd_Credit_Memos":0,"No_of_Ship_to_Addresses":0,"Outstanding_Orders_LCY":"0","Shipped_Not_Invoiced_LCY":"0"},{"No":"01454545","Name":"New Concepts Furniture","City":"Atlanta","Amount":"0","Customer_Posting_Group":"FOREIGN","Balance_LCY":"222241.32","Sales_LCY":"0","Profit_LCY":"0","Balance_Due_LCY":"222241.32","Payments_LCY":"0","Inv_Amounts_LCY":"222241.32","Cr_Memo_Amounts_LCY":"0","Outstanding_Orders":"15609","Shipped_Not_Invoiced":"0","No_of_Quotes":0,"No_of_Blanket_Orders":0,"No_of_Orders":1,"No_of_Invoices":0,"No_of_Return_Orders":0,"No_of_Credit_Memos":0,"No_of_Pstd_Shipments":0,"No_of_Pstd_Invoices":0,"No_of_Pstd_Return_Receipts":0,"No_of_Pstd_Credit_Memos":0,"No_of_Ship_to_Addresses":0,"Outstanding_Orders_LCY":"8702.82","Shipped_Not_Invoiced_LCY":"0"},{"No":"01905893","Name":"Candoxy Canada Inc.","City":"Thunder Bay","Amount":"0","Customer_Posting_Group":"FOREIGN","Balance_LCY":"0","Sales_LCY":"0","Profit_LCY":"0","Balance_Due_LCY":"0","Payments_LCY":"0","Inv_Amounts_LCY":"0","Cr_Memo_Amounts_LCY":"0","Outstanding_Orders":"0","Shipped_Not_Invoiced":"0","No_of_Quotes":0,"No_of_Blanket_Orders":0,"No_of_Orders":0,"No_of_Invoices":0,"No_of_Return_Orders":0,"No_of_Credit_Memos":0,"No_of_Pstd_Shipments":0,"No_of_Pstd_Invoices":0,"No_of_Pstd_Return_Receipts":0,"No_of_Pstd_Credit_Memos":0,"No_of_Ship_to_Addresses":0,"Outstanding_Orders_LCY":"0","Shipped_Not_Invoiced_LCY":"0"},{"No":"01905899","Name":"Elkhorn Airport","City":"Elkhorn","Amount":"0","Customer_Posting_Group":"FOREIGN","Balance_LCY":"0","Sales_LCY":"0","Profit_LCY":"0","Balance_Due_LCY":"0","Payments_LCY":"0","Inv_Amounts_LCY":"0","Cr_Memo_Amounts_LCY":"0","Outstanding_Orders":"0","Shipped_Not_Invoiced":"0","No_of_Quotes":0,"No_of_Blanket_Orders":0,"No_of_Orders":0,"No_of_Invoices":0,"No_of_Return_Orders":0,"No_of_Credit_Memos":0,"No_of_Pstd_Shipments":0,"No_of_Pstd_Invoices":0,"No_of_Pstd_Return_Receipts":0,"No_of_Pstd_Credit_Memos":0,"No_of_Ship_to_Addresses":0,"Outstanding_Orders_LCY":"0","Shipped_Not_Invoiced_LCY":"0"}]}
I have for certain scenarios created a POCO to deal with the returned json for the properties
public class RootObject2
{
[JsonProperty("odata.metadata")]
public string odatametadata { get; set; }
[JsonProperty("odata.nextLink")]
public string NextLinkUrl { get; set; }
}
and
public class RootObject
{
[JsonProperty("odata.metadata")]
public string odatametadata { get; set; }
[JsonProperty("odata.nextLink")]
public string NextLinkUrl { get; set; }
public List<UrlItem> Value { get; set; }
}
These are used in instances where I know the returned JSON will contain certain structures and can be safely dealt with.
The problem is that the VALUE part of the JSON will be dynamic in many instances and I wanted to take advantage of the dynamic nature of the JSONConvert functions to build DataSets that I can then pass through as a source for an Excel table. It should be noted that the data coming back will never be definable.
When i use the code:
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
I get an error, because I need to be passing the sting / contents of the VALUE node/element to the DeserialseObject.
Is there a setting on the JSON converter that allows this?
I have tried to create a POCO with a string field and then after mapping the VALUE node to the POCO passing the string to the JSONConverter but this errors out.
A solution to this would be most helpful.
Thanks.
B....
You can create your own custom subclass of DataSetConverter that strips out non-array-valued properties from the root DataSet object:
public class DataSetConverter : Newtonsoft.Json.Converters.DataSetConverter
{
public override bool CanConvert(Type valueType)
{
if (!base.CanConvert(valueType))
return false;
return typeof(DataSet).IsAssignableFrom(valueType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
var token = JObject.Load(reader);
// Strip non-array-valued properties
foreach (var property in token.Properties().Where(p => p.Value.Type != JTokenType.Array).ToList())
property.Remove();
using (var subReader = token.CreateReader())
{
while (subReader.TokenType == JsonToken.None)
subReader.Read();
return base.ReadJson(subReader, objectType, existingValue, serializer); // Use base class to convert
}
}
}
Then use it as follows:
var dataSet = JsonConvert.DeserializeObject<DataSet>(json, new JsonSerializerSettings { Converters = new JsonConverter[] { new DataSetConverter() } });
var dataTable = dataSet.Tables["value"];
Prototype fiddle.

ArangoDB update action in .Net

I am a .Net developer and is currently exploring on ArangoDB. I have played around with the arangod web user interface and arangod and like this NoSql very much until I delve into the detail of coding. I could not find the .Net driver working properly. Even for simple CRUD operation. Here's the problem.
ArangoClient.AddConnection("127.0.0.1", 8529, false, "Sample", "Sample");
var db = new ArangoDatabase("Sample");
string collectionName = "MyTestCollection";
var collection = new ArangoCollection();
collection.Name = collectionName;
collection.Type = ArangoCollectionType.Document;
if (db.Collection.Get(collectionName) == null)
{
db.Collection.Create(collection);
}
var employee = new Employee();
employee.Id = "1234";
employee.Name = "My Name";
employee.Salary = 33333;
employee.DateOfBirth = new DateTime(1979, 7, 22);
db.Document.Create<Employee>("MyTestCollection", employee);
employee.Name = "Tan";
db.Document.Update(employee);
It thrown the error for db.Document.Update(employee). Here's the error message: Field '_id' does not exist.
Then I tried to add the field _id though I think it is weird, it prompted me another error message.
Arango.Client.ArangoException : ArangoDB responded with error code BadRequest:
expecting PATCH /_api/document/<document-handle> [error number 400]
at Arango.Client.Protocol.DocumentOperation.Patch(Document document, Boolean waitForSync, String revision)
at Arango.Client.ArangoDocumentOperation.Update[T](T genericObject, Boolean waitForSync, String revision) ...
I have no clues at all and do not know how to to proceed further. Any help will be much appreciated. Thanks.
This is likely due to the definition of the Employee class, which is not contained in the above snippet.
To identify a document in a collection, documents have special system attributes, such as _id, _key and _rev. These attributes should be mapped to properties in .NET classes, even if not used explicitly. So one property in the class should be tagged with "Identity", one with "Key", and one with "Revision". Here is an example class definition that should work:
public class Employee
{
/* this will map the _id attribute from the database to ThisIsId property */
[ArangoProperty(Identity = true)]
public string ThisIsId { get; set; }
/* this will map the _key attribute from the database to the Id property */
[ArangoProperty(Key = true)]
public string Id { get; set; }
/* here is _rev */
[ArangoProperty(Revision = true)]
public string ThisIsRevision { get; set; }
public DateTime DateOfBirth { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public Employee()
{
}
}
The ThisIsId property will contain the automatically assigned _id value, and can also be used to retrieve the document easily later:
var employeeFromDatabase = db.Document.Get<Employee>(employee.ThisIsId);
You can of course rename the properties to your like.

How to retrieve data using a strong typed model in LinqToSql

This code works fine.
using (ContextDB db = new ContextDB())
{
var custAcct = (from c in db.CustAccts
select new
{
c.AcctNo,
c.Company,
c.UserName
}).ToList();
But this one doesn't
public class CustAcct
{
public int AcctNo { get; set; }
public string Company { get; set; }
public string UserName { get; set; }
}
....
....
....
using (ContextDB db = new ContextDB())
{
CustAcct custAcct = (from c in db.CustAccts
select new
{
c.AcctNo,
c.Company,
c.UserName
}).ToList();
It returns this error:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'EMailReader.Models.CustAcct'. An explicit conversion exists (are you missing a cast?)
I used Google, found many related topics but still couldn't put it to work using the available solutions
I just need to return data to a strong typed model.
EDITED:
After more research I found this solution bellow, but I wonder why I cannot retrieve directly in the list from LinqToSql.
List<CustAcct> temp = new List<CustAcct>();
IEnumerable<dynamic> items = custAcct;
foreach (var item in items)
{
temp.Add(new CustAcct()
{
AcctNo = item.AcctNo,
Company = item.Company,
UserName = item.UserName,
});
}
You are re defining those properties by creating new Class. And this will override LINQ2SQL generated class.
Just change "public class CustAcct" to "public partial class CustAcct".
This will solve your problem, and you do not need to define those properties again. Remove those from your class. Those will be automatically create for you.
If you can just post your class, and I will change it for you.
//Shyam

How to generate empty get & set statements using CODEDOM in c#

currently the code which i have is generating the properties like
private int integerProperty
{
get
{
return integerField;
}
set
{
integerField = value;
}
}
I wanted the properties to be simple like...
private int integerProperty
{
get;
set;
}
The code i have with me is
CodeMemberProperty property1 = new CodeMemberProperty();
property1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "integerField")));
property1.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "integerField"),new CodePropertySetValueReferenceExpression()));
type1.Members.Add(property1);
Anyone please help. Thanks in advance.
As Botz3000 mentioned, it's officially not possible. However, with the following hack you can implement it:
var field = new CodeMemberField
{
Attributes = MemberAttributes.Public | MemberAttributes.Final,
Name = "MyProperty",
Type = new CodeTypeReference(typeof(MyType)),
};
field.Name += " { get; set; }";
By appending { get; set; } to the field name, it will generate a property in the actual source code.
This is an old question, but is worth noting that the answer by "#Serguei Fedorov" is no longer applies (it's valid only for c# 1.0 to c# 2.0)
The solution of replacing "};" with "}" should be avoid, because "};" is used for the syntax of Object and Collection Initializers starting from C# 3.0.
Review Object and Collection Initializers.
Example:
var pet = new { Age = 10, Name = "Fluffy" }; //it's ended by "};"
Alternative solution
You can use the new .NET Compiler Platform ("Roslyn") which support C# 1.0 to c#6.0.
The samples include ConvertToAutoProperty - A code refactoring to change a simple property with a trivial getter and setter into an auto property.
If you interested by CodeDom, there's a new CodeDOM Providers for .NET Compiler Platform (“Roslyn”) that can be installed from nuget
No, it's not possible. Automatic properties are a language specific feature, so you won't find any way to generate those.

Resources