MVC3 C# LocalizedRequiredAttribute not works - c#

I wrote this attribute extension:
public class LocalizedRequiredAttribute : RequiredAttribute
{
public LocalizedRequiredAttribute(string resourceTag)
{
ErrorMessage = GetMessageFromResource(resourceTag);
}
private static String GetMessageFromResource(String resourceTag)
{
return ResourceManager.Current.GetResourceString(resourceTag);
}
}
but I get this error: 'System.Resources.ResourceManager' does not contain a definition for 'Current'.
What is wrong?
Thanks a lot.

This can already be done using the RequiredAttribute
[Required(ErrorMessageResourceType=typeof(ClassLib1.Resources), ErrorMessageResourceName="Character_FirstName_Required")]
see Model Metadata and Validation Localization using Conventions
EDIT:
I Guess you're referencing the wrong ResourceManager, see ResourceManager.Current | current property

It looks like you don't have the Windows.ApplicationModel.Resources.Core namespace referenced in the file where you define this attribute so VS in it's wisdom is referencing System.Resources.Resource manager.

Related

Unable to run xaml and c# example [duplicate]

My program uses a class called Time2. I have the reference added to TimeTest but I keep getting the error, 'Time2' is a 'namespace' but is used like a 'type'.
Could someone please tell me what this error is and how to fix it?
namespace TimeTest
{
class TimeTest
{
static void Main(string[] args)
{
Time2 t1 = new Time2();
}
}
}
I suspect you've got the same problem at least twice.
Here:
namespace TimeTest
{
class TimeTest
{
}
... you're declaring a type with the same name as the namespace it's in. Don't do that.
Now you apparently have the same problem with Time2. I suspect if you add:
using Time2;
to your list of using directives, your code will compile. But please, please, please fix the bigger problem: the problematic choice of names. (Follow the link above to find out more details of why it's a bad idea.)
(Additionally, unless you're really interested in writing time-based types, I'd advise you not to do so... and I say that as someone who does do exactly that. Use the built-in capabilities, or a third party library such as, um, mine. Working with dates and times correctly is surprisingly hairy. :)
namespace TestApplication // Remove .Controller
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
Remove the controller word from namepsace
The class TimeTest is conflicting with namespace TimeTest.
If you can't change the namespace and the class name:
Create an alias for the class type.
using TimeTest_t = TimeTest.TimeTest;
TimeTest_t s = new TimeTest_t();
All the answers indicate the cause, but sometimes the bigger problem is identifying all the places that define an improper namespace. With tools like Resharper that automatically adjust the namespace using the folder structure, it is rather easy to encounter this issue.
You can get all the lines that create the issue by searching in project / solution using the following regex:
namespace .+\.TheNameUsedAsBothNamespaceAndType
If you're working on a big app and can't change any names, you can type a . to select the type you want from the namespace:
namespace Company.Core.Context{
public partial class Context : Database Context {
...
}
}
...
using Company.Core.Context;
someFunction(){
var c = new Context.Context();
}
I had this problem as I created a class "Response.cs" inside a folder named "Response". So VS was catching the new Response () as Folder/namespace.
So I changed the class name to StatusResponse.cs and called new StatusResponse().This solved the issue.
If you are here for EF Core related issues, here's the tip:
Name your Migration's subfolder differently than the Database Context's name.
This will solve it for you.
My error was something like this:
ModelSnapshot.cs error CS0118: Context is a namespace but is used like a type
Please check that your class and namespace name is the same...
It happens when the namespace and class name are the same.
do one thing write the full name of the namespace when you want to use the namespace.
using Student.Models.Db;
namespace Student.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<Student> student = null;
return View();
}
}
if the error is
Line 26:
Line 27: #foreach (Customers customer in Model)
Line 28: {
Line 29:
give the full name space
like
#foreach (Start.Models.customer customer in Model)

ASP.NET Web API POST parameter is null When Properties of Class Defined as Auto-Implemented

Anyone have any idea why the auto-implemented version of the class does not come through on a Post to the Web API?
namespace N_EWA
{
public class testMe
{
public bool Pending { get; set; }
}
}
However.... if I define the class and property as below.... it recognizes the incoming object and it works....
namespace N_EWA
{
public class testMe
{
private bool pending { get; set; }
public bool Pending
{
get { return pending; }
set { pending = value; }
}
}
}
Not possible. The two are identical in function. Show more context of your code - I assure you there's a problem elsewhere.
I was going to put this in comments but I think it warrents its own answer entry.
I thought about this overnight.... since auto-implemented properties are created by the compiler itslef could it be that since I am running this as a standard website and not a web application that Web API is not able to work with the auto-implemented class/properties since the generated private fields used to manage the get/set of the property exist only in compiled code like you get when you have a web application?
The offical answer is user error on my part.... :-)
For some unknown reason the complex object that I was trying to post had the booleans set to True and False (capital T and F)..... simply changing the values to true and false (all lowers) corrected the issue.

'namespace' but is used like a 'type'

My program uses a class called Time2. I have the reference added to TimeTest but I keep getting the error, 'Time2' is a 'namespace' but is used like a 'type'.
Could someone please tell me what this error is and how to fix it?
namespace TimeTest
{
class TimeTest
{
static void Main(string[] args)
{
Time2 t1 = new Time2();
}
}
}
I suspect you've got the same problem at least twice.
Here:
namespace TimeTest
{
class TimeTest
{
}
... you're declaring a type with the same name as the namespace it's in. Don't do that.
Now you apparently have the same problem with Time2. I suspect if you add:
using Time2;
to your list of using directives, your code will compile. But please, please, please fix the bigger problem: the problematic choice of names. (Follow the link above to find out more details of why it's a bad idea.)
(Additionally, unless you're really interested in writing time-based types, I'd advise you not to do so... and I say that as someone who does do exactly that. Use the built-in capabilities, or a third party library such as, um, mine. Working with dates and times correctly is surprisingly hairy. :)
namespace TestApplication // Remove .Controller
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
Remove the controller word from namepsace
The class TimeTest is conflicting with namespace TimeTest.
If you can't change the namespace and the class name:
Create an alias for the class type.
using TimeTest_t = TimeTest.TimeTest;
TimeTest_t s = new TimeTest_t();
All the answers indicate the cause, but sometimes the bigger problem is identifying all the places that define an improper namespace. With tools like Resharper that automatically adjust the namespace using the folder structure, it is rather easy to encounter this issue.
You can get all the lines that create the issue by searching in project / solution using the following regex:
namespace .+\.TheNameUsedAsBothNamespaceAndType
If you're working on a big app and can't change any names, you can type a . to select the type you want from the namespace:
namespace Company.Core.Context{
public partial class Context : Database Context {
...
}
}
...
using Company.Core.Context;
someFunction(){
var c = new Context.Context();
}
I had this problem as I created a class "Response.cs" inside a folder named "Response". So VS was catching the new Response () as Folder/namespace.
So I changed the class name to StatusResponse.cs and called new StatusResponse().This solved the issue.
If you are here for EF Core related issues, here's the tip:
Name your Migration's subfolder differently than the Database Context's name.
This will solve it for you.
My error was something like this:
ModelSnapshot.cs error CS0118: Context is a namespace but is used like a type
Please check that your class and namespace name is the same...
It happens when the namespace and class name are the same.
do one thing write the full name of the namespace when you want to use the namespace.
using Student.Models.Db;
namespace Student.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<Student> student = null;
return View();
}
}
if the error is
Line 26:
Line 27: #foreach (Customers customer in Model)
Line 28: {
Line 29:
give the full name space
like
#foreach (Start.Models.customer customer in Model)

Json Serialization for Windows Phone

I was trying to implement parsing a JSON response as shown here for my Windows Phone 7 project in C#. But I am stuck with a compilation error as "The type or namespace name 'Serializable' could not be found (are you missing a using directive or an assembly reference?)"
I have the imports using System.Runtime.Serialization;
using System.Runtime.Serialization.Json; I am not sure what are import I am missing. I tried to include using System.ServiceModel.Web; But the Web part is not recognized.
I thought my project is not pointing to the right framework from here. But in the Assembly information, there is no option for me to change the target framework.
This looks like a similar problem to mine, but I couldn't find the JSON.NET in .net dlls which is filtered for Windows Phone.
Can someone help me to get this JSON thing working for Windows Phone 7.
Thank in Advance.
EDIT - 7/3/11
My Jason response is
{ "serviceresponse" : { "servicename" : "RequestRegisterUser", .....
And my Response objects are:
[DataContract]
public class serviceresponse
{
[DataMember]
public String servicename { get; set; }
.
.
.
And my Deserialize method:
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
obj = (T)serializer.ReadObject(stream);
return obj;
}
}
Now I am getting this error after Deserializing the response:
servicename Could not evaluate expression string
( I could not import System.ServiceModel.Web though I have the dll in the reference. A compilation error on the .Web part (The type or namespace name 'Web' does not exist in the namespace 'System.ServiceModel') )
EDIT After more research, I found my response when viewed in the debugger is actually
{
\"serviceresponse\": {
\"servicename\": \"RequestRegisterUser\",.....
I searched for this and found this could be a problem. How can I format it to correct JSON String??
You need to add a reference to both System.Runtime.Serialization and System.ServiceModel.Web assemblies. The DataContractJsonSerializer is defined in System.ServiceModel.Web assembly in the Silverlight version of the framework, that's why you need the extra assembly reference.
And by the way JSON.NET is a a popular open-source JSON framework for .Net and you could find more about it here. It's not part of the .Net framework, that's why you can't find it.
Edit:
About the compilation, in Silverlight the DataContractJsonSerializer is in the System.Runtime.Serialization.Json namespace, but in the assembly System.ServiceModel.Web (in System.ServiceModel.Web.dll), which is a bit confusing. So you use it like this - System.Runtime.Serialization.Json.DataContractJsonSerializer, but need the extra assembly reference. You also need to reference the System.Runtime.Serialization assembly as well, because that is where the DataContract attribute is defined. I see you have already successfully compiled the code, but I hope the extra explanation makes it more clear for future readers.
About the serialization itself - as you have already found out, you will need two objects, simply because that's the structure of the json. However, the DataContract and DataMember attributes have a Name property that you can use instead of changing the name of the fields. Also, you can use properties instead of fields if you like.
For example:
[DataContract]
public class ServiceResponse
{
[DataMember(Name = "servicename")]
public string ServiceName { get; set; }
}
[DataContract]
class Response
{
[DataMember(Name = "serviceresponse")]
public ServiceResponse ServiceResponse { get; set; }
}
And one last thing - you don't need the call to Activator.CreateInstance(); in your Deserialise method.
It certainly would help if you posted your code. So I can only guess:
I assume you have something like this:
[Serializable]
public class Response
{
[DataMember]
public string name { get; set; }
...
}
But that's a mix-up of two serialization concepts, one of which is not supported in Phone 7. The correct attributes are DataContract and DataMember:
[DataContract]
public class Response
{
[DataMember]
public string name { get; set; }
...
}
I found the issue. Though my class name is "serviceresponse", I used another wrapper class as
public class Response
{
public serviceresponse serviceres;//Don't Do this....
}
where I used the variable name for serviceresponse as serviceres. But when I changed it to " serviceresponse" its all working.
public class Response
{
public serviceresponse serviceresponse;//This fixed it.
}

How to retrieve the value of a Custom Attribute from a DLL Loaded at runtime?

I have a app that requires a dll to be loaded at runtime and I want to create some Custom Attributes in the dynamically loaded DLL so when it is loaded I can check to make sure that certain attributes have certain values before trying to use it.
I create an attribute like this
using System;
[AttributeUsage(AttributeTargets.Class)]
public class ValidReleaseToApp : Attribute
{
private string ReleaseToApplication;
public ValidReleaseToApp(string ReleaseToApp)
{
this.ReleaseToApplication = ReleaseToApp;
}
}
In the dynamically loaded DLL I set the attribute like this
[ValidReleaseToApp("TheAppName")]
public class ClassName : IInterfaceName
etc... etc....
But when I try and read the Attribute Value I only get the Attribute Name "ValidReleaseToApp" How do I retrieve the Value "TheAppName"?
Assembly a = Assembly.LoadFrom(PathToDLL);
Type type = a.GetType("Namespace.ClassName", true);
System.Reflection.MemberInfo info = type;
var attributes = info.GetCustomAttributes(true);
MessageBox.Show(attributes[0].ToString());
Update:
Since I am Dynamically loading the dll at runtime the definition of the Attribute is not avail. to the Main App. So when I try to do the following as suggested
string value = ((ValidReleaseToApp)attributes[0]).ReleaseToApplication;
MessageBox.Show(value);
I get this error
The type or namespace name 'ValidReleaseToApp' could not be found
Update2:
OK so the problem was that I defined the Attribute within the project of the dynamically loaded DLL. Once I moved the Attribute definitions to it's own project and Added a reference to that project to both the Main Project and that of the Dynamically loaded dll The suggested code worked.
This should work, I don't have an example in front of me right now, but it looks right. You're basically skipping the steps of exposing the property you want access to, and casting to the attribute type to retrieve that property.
using System;
[AttributeUsage(AttributeTargets.Class)]
public class ValidReleaseToApp : Attribute
{
private string _releaseToApplication;
public string ReleaseToApplication { get { return _releaseToApplication; } }
public ValidReleaseToApp(string ReleaseToApp)
{
this._releaseToApplication = ReleaseToApp;
}
}
Assembly a = Assembly.LoadFrom(PathToDLL);
Type type = a.GetType("Namespace.ClassName", true);
System.Reflection.MemberInfo info = type;
var attributes = info.GetCustomAttributes(true);
if(attributes[0] is ValidReleaseToApp){
string value = ((ValidReleaseToApp)attributes[0]).ReleaseToApplication ;
MessageBox.Show(value);
}
Once you have the custom attributes, you can cast them to instances of the attribute class and access their proerties:
object[] attributes = info.GetCustomAttributes(typeof(ValidReleaseToAppAttribute), true);
ValidReleaseToAppAttrigute attrib = attributes[0] as ValidReleaseToAppAttribute;
MessageBox.Show(attrib.ReleaseToApp);

Categories

Resources