So I'm trying to parse a simple arithmetic dynamic expression using System.Linq.Dynamic.
This runs fine when executed in an English environment where the CurrentCulture is English-US (and the decimal separator is a plain "." dot).
Trying to run the code in a non English environment (e.g. Windows7x64 in Bulgarian, where the decimal separator is a "," comma), ParseLambda fails.
If I put "1.0" in my expression, ParseLambda fails in the Bulgarian environment with a PraseExpression, saying "Invalid real literal '1.0'" (but does not fail in the English environment).
If I try to put "1,0" in my expression, ParseLambda fails with a ParseExpression saying "Syntax error" (this one fails in both environments).
Anyone knows a way around this?
Or am I missing something?
Or can I somehow set the culture of the parsed expression?
I need my app to run well on both environments..
My code is running on .NET v4.0 and I have System.Linq.Dynamic.dll (1.0.0.0) added as reference to the project.
Here's the code:
using System;
using System.Linq;
using System.Linq.Dynamic;
namespace DynamicExpressionTest
{
class Program
{
static void Main(string[] args)
{
//FAIL: ParseException: Invalid real literal '1.0' (fails only in non-English environment)
var expression1 = DynamicExpression.ParseLambda(
new System.Linq.Expressions.ParameterExpression[] { },
typeof(double),
"1.0 + 1.0");
var result1 = expression1.Compile().DynamicInvoke();
double resultD1 = System.Convert.ToDouble(result1);
Console.WriteLine(resultD1);
//FAIL: ParseException: Syntax error (fails both in English and non-English environments)
var expression2 = DynamicExpression.ParseLambda(
new System.Linq.Expressions.ParameterExpression[] { },
typeof(double),
"1,0 + 1,0");
var result2 = expression2.Compile().DynamicInvoke();
double resultD2 = System.Convert.ToDouble(result2);
Console.WriteLine(resultD2);
}
}
}
Thanks!
You can set the current culture before running that code. E.g. add this line before your code that only works with an English-style decimal separator:
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Related
I encountered an error in a script I was debugging because somebody had created a variable with a name matching a built-in function, rendering the function inaccessible. I got strange errors when I tried to use the function, like:
incorrect arguments for (-)
incorrect arguments for (by)
incorrect arguments for ([)
incorrect arguments for (=)
Example code:
int length
// ...
// ...
string substr
string str = "big long string with lots of text"
substr = str[0:length(str)-2]
Is there a way to access the original length() function in this situation? I was actually just trying to add debug output to the existing script, not trying to modify the script, when I encountered this error.
For now I have just renamed the variable.
Well, in the case that you had no chance to modify the code, e.g. because it is encrypted you could do sth like
int length_original (string s) { return length s }
<<here is the code of your function>>
int length (string s) {return length_original s }
i have developed a test package using SWTbot and ant to build it , when i run it, it finds that there is a failure however in the test report it shows as an error instead of failure:
my code is :
public static void Check_TargetPack(final SWTWorkbenchBot bot,String configuration,
String targetpack) {
boolean exist=false;
String[] h=bot.comboBoxWithLabel("TargetPack").items();
int i=0;
for (i=0;i<h.length;i++){
if (h[i]==targetpack)exist=true;
assertTrue("target pack"+targetpack+" doesn't exist in targetpack list",exist);
};
bot.sleep(2000);
bot.button("Close").click();
}
and the result is
I can see one problem in your code.
You are matching Strings with "==" operator.
You should use following instead
h[i].equals(targetpack)
I've read a few questions that answer this, and I understand the regular expression I'm required to use, however actually applying it in MVC is where I stumble. I will also preface by saying I am terrible at regular expressions so far.
I'm writing a file upload application in MVC and I want to apply standard windows filename validation. \/:*?"<>| are invalid characters anywhere in the name.
My View Model for this is setup like so, using a different regex I found:
public class FileRenameModel
{
[RegularExpression(#"^[\w\-. ]+$", ErrorMessage="A filename cannot contain \\ / : * ? \" < > |")]
[Required]
public string Filename { get; set; }
[Required]
public int FileID { get; set; }
}
Whenever I try to change the regex to #"^[\\/:?"<>|]+$ the " in the middle kills it and throws an error. I haven't figured out how to properly escape it so that I can include it in the string. When I use the regex without the " it tells me any string I put into the textbox fails. Am I using the ^ incorrectly?
Use double "" to escape quotes after starting a string with #.
To search for anything except you'd want to insert an additional ^ inside the brackets to create an except for match: #"^[^\\/:?""<>|]+$" Keep the ^ at the beginning as well to match the start of line.
Having said that, keep in mind for validation that browsers handle file names differently. Some older browsers sent a path along with the filename, that might break your validation for a legitimate file.
This regular expression should match a more-than-sufficient subset of valid NTFS filenames (bear in mind that an NTFS file name may contain pretty much any Unicode character.)
Regex rxValidFileName = new Regex(#"^[[\p{IsBasicLatin}\p{IsLatin-1Supplement}\p{IsLatinExtended-A}\p{IsLatinExtended-B}]-[\p{C}<>:""/\|?*]]+$" , RegexOptions.IgnorePatternWhitespace|RegexOptions.IgnoreCase);
What this matches:
start-of-line, followed by
1 or more of
any basic latin, latin-1 supplement, or latin extended-A or -B character, unless...
unless it's a C0 or C1 control character or one of the characters otherwise disallowed by NTFS — <>:"/\|?*
terminated by end-of-line.
Note that this matches a file name, not a file path. A file path is more complicated, since it's got a grammar to it, something like this, in crude ABNF:
filepath : relative-path
| absolute-path
| drivespecifier (relative-path|absolute-path)?
| unc-share (absolute-path)?
;
relative-path : filename ( directory-separator filename? )*
absolute-path : directory-separator ( filename? directory-separator )*
directory-separator : [/\]
drivespecifier : [a-zA-Z] ":"
unc-share : "\\" filename "\" filename absolute-path?
I have the following code
this.SafeUpdate(rate, Guid.Parse(import.myGuid), c => c.myGuid);
SafeUpdate basically takes the parsed guid value and applies it to the myGuid property on the rate object. This works fine from my front end, but throws the "CLR detected..." error when run in a unit test. What's odd is the same statement for DateTime.Parse and int.Parse works fine. It just fails for Guid and decimals. I don't believe the error is with the parsing (it has the correct parsed value when extracted into a separate variable). I don't believe it's the mocking either as the statement works fine for all other types other than guid and decimal. Any ideas?
We experienced a similar error yesterday on our build server. Our exception was thrown by the ReadObject() method of a DataContractSerializer.
System.InvalidProgramException: Common Language Runtime detected an invalid program.
at System.Xml.EncodingStreamWrapper..ctor(Stream stream, Encoding encoding)
at System.Xml.XmlUTF8TextReader.SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.Xml.XmlDictionaryReader.CreateTextReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.Xml.XmlDictionaryReader.CreateTextReader(Stream stream, XmlDictionaryReaderQuotas quotas)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(Stream stream)
We've written a console app that does just this one thing. It runs without error, but fails in a simple unit test. We are using Gallio/MbUnit 3.4.11.0 for our test framework with a target of .net 4.0.
using System;
using System.IO;
using System.Runtime.Serialization;
using MbUnit.Framework;
namespace TestApp
{
[TestFixture]
class Program
{
static void Main()
{
FooBar();
Console.ReadKey();
}
public static void FooBar()
{
var type = typeof(string);
var foo = "foo";
using (var stream = new MemoryStream())
{
var serializer = new DataContractSerializer(type);
serializer.WriteObject(stream, foo);
stream.Seek(0, SeekOrigin.Begin);
var deserializer = new DataContractSerializer(type);
var bar = deserializer.ReadObject(stream);
Console.WriteLine(bar);
}
}
[Test]
public void Test()
{
FooBar();
}
}
}
The application runs fine, but the test throws. Strangely, this test passes on my dev box but fails on our build server as well as the dev box of a coworker. Clearly, there is something different about my dev box that allows the test to pass, but I have not located that difference yet.
Update 1
The version of System.dll on my dev box is 4.0.30319.296 but on the build server and the dev box of my coworker it is 4.0.30319.1001. System.Xml.dll and System.Runtime.Serialization.dll are identical at 4.0.30319.1, however.
Update 2
A quick google search for "4.0.30319.1001" returns this security update, http://support.microsoft.com/kb/2742595, which was applied to both our build server and the dev box of my coworker, but not my dev box. I uninstalled the update on the build server, rebooted, and the issue went away! I guess Microsoft doesn't have a unit test for this one yet. :-)
I need to use OGNL for reading some properties from Java object. OGNL is completely new thing to me. The documentation available for OGNL is OGNL's website is really confusing to me.
So anyone can provide a simple HelloWorld example for using OGNL (or any link to a tutorial is also helpful).
Try this:
Dimension d = new Dimension(2,2);
String expressionString = "width";
Object expr = Ognl.parseExpression(expressionString);
OgnlContext ctx = new OgnlContext();
Object value = Ognl.getValue(expr, ctx, d);
System.out.println("Value: " + value);
If the intention is only to read properties from an object then PropertyUtils.getProperty (from commons-beanutils) may suffice. However, if the intention is to evaluate conditionals and such, then Ognl may benefit.
Here is the same Dimension example with a boolean:
Dimension d = new Dimension();
d.setSize(100,200) ;// width and height
Map<String,Object> map = new HashMap<String,Object>();
map.put("dimension", d);
String expression = "dimension.width == 100 && dimension.height == 200";
Object exp = Ognl.parseExpression(expression);
Boolean b = (Boolean) Ognl.getValue(exp,map);
// b would evaluate to true in this case
OGNL allows you to access objects fields and methods via string expressions which becomes very useful when you have lose coupled architecture between data and it's consumers. It's using reflection under the hood but definitely speeds up development compared to a pure reflection approach.
Some one line examples
System.out.println(Ognl.getValue("x", new Point(5,5)));
System.out.println(Ognl.getValue("size", new ArrayList<Object>()));
Documentation already has a number of basic and more advanced ognl expressions.
Here is an example helloworld for jython (python that compiles to java).
from ognl import Ognl, OgnlContext
from java.lang import String
exp = Ognl.parseExpression("substring(2, 5)")
print Ognl.getValue(exp, OgnlContext(), String("abcdefghj"))