"Bool" not found in .NET application running on Mono/XPS - asp.net

I am incredibly new to .NET and Mono. I have a .NET 4 application that I am trying to run locally, and I'm getting a compilation error when I try to run it (using xps4 on Ubuntu). At the end of the stacktrace it says:
/tmp/jeremy-temp-aspnet-0/3b8f3547/App_Web_635c7158_48.cs(32,21): error CS0246: The type or namespace name `bool' could not be found. Are you missing a using directive or an assembly reference?
Does that mean that it doesn't recognize the boolean type? A Google search wasn't much help.
Update - Here's the code:
public virtual #bool ShowRecentPlans {
get {
return ((#bool)(this.GetPropertyValue("ShowRecentPlans")));

When you prefix an identifier (like a type name) with #, you're telling the compiler that, even though it looks like a reserved word, it refers to something defined in your program.
Unless you have something defined somewhere like
public class #bool
{
...
}
then this isn't going to work.
Try
public virtual bool ShowRecentPlans {
get {
return (bool)(this.GetPropertyValue("ShowRecentPlans"));
}
}
For instance, if you wanted to use the keyword new as an identifier, you could:
int new = 5; /// error!
int #new = 5; /// compiles
# is of course also used to tell the compiler how a string should be interpreted.
// throws an error because \p and \m look like formatting sequences
var path = "c:\pub\myFile.txt";
// compiles
var path = #"c:\pub\myFile.txt";
Also, I just have to ask: what made you use #bool instead of bool to start with?
(And, for the record, using a keyword as an identifier is a very, very bad idea.)

Your return type should be bool instead of #bool.

Related

CamelCase property names with NJsonSchema C# CodeGeneration

does anybody know a way to configure NJsonSchema to use CamelCase property naming durching code generation? I've a JSON schema with property names like message_id which lead to C# property name 'Message_id' where i.e. 'MessageId' whould be a more C#-like way.
With an attribute like '[JsonProperty("message_id"]' it would be no problem to specified the connection between the different names.
So, you asked about code generation. I was having trouble with the schema it generated not matching what was getting sent to my Angular app. So, while this isn't exactly what you were looking for, perhaps it helps you find an answer (maybe?).
To generate the schema with the camel case property names, I'm setting the Default Property Name Handling to CamelCase, but this is using the deprecated call to set these settings directly. There should be some way to use the SerializerSettings directly, but I wasn't quite able to make that work. This isn't production code for me, so it will do.
internal class SchemaFileBuilder<T>
{
public static void CreateSchemaFile()
{
CreateSchemaFile(typeof(T).Name);
}
public static void CreateSchemaFile(string fileName)
{
JsonSchemaGeneratorSettings settings = new JsonSchemaGeneratorSettings();
settings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
var schema = NJsonSchema.JsonSchema.FromType<T>(settings);
var json = schema.ToJson();
Directory.CreateDirectory("Schemas");
File.WriteAllText($"Schemas\\{fileName}.schema.json", json);
}
}
I set this up as a generic function so I could pass multiple schemas in to either createSchemaFile functions. Here's are some example calls which would generate a Person.schema.json file and a Persons.schema.json file:
SchemaFileBuilder<Person>.CreateSchemaFile();
SchemaFileBuilder<Dictionary<string, Person>>.CreateSchemaFile("Persons");

Localization for "the value {0} is invalid" in case of int overflow

I've read answers about localization of validation errors by specifying DefaultModelBinder.ResourceClassKey, basically it's when entering string values in int field or not a datetime in datetime field.
But when I'm typing "111111111111111111111111111111" for an int field I get System.OverflowException and it looks like "The value '{0}' is invalid.".
Is there a way to localize (translate that message to other languages) that validation error in a way similar to other MVC-validation?
I had the same issue, and I finally managed to find the solution. Yes, that message can be localized, and luckily it's pretty easy when you figure it out.
You have to create a resource file and put it in the App_GlobalResources folder. You can call the file whatever you want, but I usually call it MvcValidationMessages.
Open the resource file and create a string with the name InvalidPropertyValue and write whatever message you want in the value field.
Now, open the Global.asax file and add the following line to the method Application_Start():
System.Web.Mvc.Html.ValidationExtensions.ResourceClassKey = "MvcValidationMessages";
"MvcValidationMessages" should of course be the correct name of the resource file you just created.
And voĆ­la! That's all there is to it. The message shown will now be your own instead of the default one.
I ended up overriding ModelBinder for int and supplying a localized error-message there:
public class IntModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
double parsedValue;
if (double.TryParse(value.AttemptedValue, out parsedValue))
{
if ((parsedValue < int.MinValue || parsedValue > int.MaxValue))
{
var error = "LOCALIZED ERROR MESSAGE FOR FIELD '{0}' HERE!!!";
bindingContext.ModelState.AddModelError(bindingContext.ModelName, string.Format(error, value.AttemptedValue, bindingContext.ModelMetadata.DisplayName));
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
Then I simply registered it: ModelBinders.Binders.Add(typeof(int), new IntModelBinder()); and it now works fine.
P.S. sure, my localized errormessages are not hardcoded in model binder, this is just a simplified example :)

JVM crashes when attempting to modify String value using reflection

This is my first question I hopefully don't make any terrible mistake.
Assuming no SecurityManager is preventing me from doing this :
public static void main(String[] args) {
String str = "1";
System.out.println("str value before invoke fillStringValueWithX method: " + str);
fillStringValueWithX(str);
System.out.println("str value before invoke fillStringValueWithX method: " + str);
}
private static void fillStringValueWithX(String str) {
if (str != null) {
try {
Field fieldValue = String.class.getDeclaredField("value");
fieldValue.setAccessible(true);
char[] charValue = (char[]) fieldValue.get(str);
Arrays.fill(charValue, 'x');
fieldValue.setAccessible(false);
} catch (Exception e) {}
}
}
If the size of the string is 1 (the example above) the JVM crash (the crash dump shows an EXCEPTION_ACCESS_VIOLATION error) however if the size of the string is greater than 1 this code snippet works for me.
Note: I assume that the appropiate use for setting a field's value via reflection is using valueField.set(obj, value) Field method but I want to know why the JVM crash...
Thanks
Patient: Doctor, doctor, it hurts when I do this (bangs arm with hammer).
Doctor: Don't do that then.
You really shouldn't be trying to mess with the contents of a string. Strings are designed to be immutable. Now I dare say it's a JVM bug that it crashes so dramatically (it doesn't on my box, btw - it would be useful if you'd tell us which operating system and JVM version you're using) but the simple answer is not to try to go behind the system's back.
it looks like that array of chars for "1" and a number of other interned Strings (like "true", "false", "root", "class", etc) cannot be changed in Windows JVM. I.e. you cannot assign new values to array elements. But you can assign new array for that String object. Example

Can somebody please explain this common binding pitfall to me? (using the wrong bindable event name)

I refer to this site link text
Using the wrong event name in the
[Bindable] tag can cause your
application to not bind your property,
and you will not even know why. When
you use the [Bindable] tag with a
custom name, the example below looks
like a good idea:
public static const EVENT_CHANGED_CONST:String = "eventChangedConst";
private var _number:Number = 0;
[Bindable(event=EVENT_CHANGED_CONST)]
public function get number():Number
{
return _number;
}
public function set number(value:Number) : void
{
_number = value;
dispatchEvent(new Event(EVENT_CHANGED_CONST));
}
The code above assigns a static
property to the event name, and then
uses the same assignment to dispatch
the event. However, when the value
changes, the binding does not appear
to work. The reason is that the event
name will be EVENT_CHANGED_CONST and
not the value of the variable.
The code should have been written as
follows:
public static const EVENT_CHANGED_CONST:String = "eventChangedConst";
private var _number:Number = 0;
[Bindable(event="eventChangedConst")]
public function get number():Number
{
return _number;
}
public function set number(value:Number) : void
{
_number = value;
dispatchEvent(new Event(EVENT_CHANGED_CONST));
}
I agree, the wrong example does look like a good idea and I would do it that way because I think it's the right way and avoids the possibility of a typing error. Why is the name of the constant used instead of it's value? Surely this can't be right?
I appreciate your insights
Because the standard Flex compiler isn't that clever at times... and I feel your pain! I've complained about this exact problem more than a few times.
If I remember correctly, it's because the compiler does multiple passes. One of the early passes changes the Metadata into AS code. At this point in the compiler it hasn't parsed the rest of the AS code, so its not capable of parsing Constants or references to static variables in other files.
The only thing I can suggest is sign up to the Adobe JIRA, vote for the bug, and hope that the compiler fixes in 4.5 bring some relief.

best way to store / lookup name value pairs

I have a list of error codes I need to reference, kinda like this:
Code / Error Message
A01 = whatever error
U01 = another error
U02 = yet another error type
I get the Code returned to me via a web service call and I need to display or get the readable error. So I need a function when passed a Code that returns the readable description. I was just going to do a select case but thought their might be a better way. What is the best way / most effieient way to do this?
Use a Dictionary, (in C#, but the concept and classes are the same):
// Initialize this once, and store it in the ASP.NET Cache.
Dictionary<String,String> errorCodes = new Dictionary<String,String>();
errorCodes.Add("A01", "Whatever Error");
errorCodes.Add("U01", "Another Error");
// And to get your error code:
string ErrCode = errorCodes[ErrorCodeFromWS];
You would use a dictionary. A dictionary uses a hashmap internally for performance, so it is good in that regard. Also, because you want this to go as quickly as possible by the sounds of it, I would statically initialize it in its own class instead of, for example, in an XML file or slimier. You would probably want something like:
public static class ErrorCodes
{
private static Dictonary<string, string> s_codes = new Dicontary<string, string>();
static ErrorCodes()
{
s_codes["code"] = "Description";
s_codes["code2"] = "Description2";
}
public static string GetDesc(string code)
{
return s_codes[code];
}
}
That way, if you wanted to move the back end to a file instead of being static, then you could.

Resources