Some context, I'm still rather new at c# but I've been updating c# code that someone else wrote that is incomplete. I've come across this code that seems to be giving me an error.
gblnEnableSSL = Convert.ToBoolean(Convert.ToInt32(Utils.GetSetting("Program", "Configuration", "SSL", "0")));
Utils.GetSetting("Program", "Configuration", "SSL", "0") returns a string "false" currently.
I've found that removing Convert.ToInt32() solves my problem. But, I was unconvinced that someone simply added Convert.ToInt32() that broke the code. I checked in the repo and was surprised to find that the previous code of the same line use to be:
gblnEnableSSL = Utils.GetSetting("Program", "Configuration", "SSL", "0").ToUpper() == "TRUE";
Which seemed to work as well. The checkbox checked value is set by using chkEnableSSL.Value = gblnEnableSSL;
My question is whether or not there is a difference between setting the value using a bool value or a string value. Also, is a difference between chkEnableSSL.value vs chkEnableSSL.Checked?
Edit: I'm not getting a compiler or run-time error with the previous code. It does not perform the code afterwards. For example, i have txtDataSource.Text = strDataSource; immediately after and it does not set the text unless i comment out gblnEnableSSL = ... or remove the Convert.ToInt32().
Edit:Convert.ToInt32() throws an exception but it did not break in VS because i didn't have "Common Language Runtime Exceptions" checked off.
It looks like GetSetting is returning a string. The first code example you gave is converting this string to an integer and then converting it to a boolean. The only way this would work is if the string values stored for that key are either 0 or 1. On your second code block it looks as if the values being used were not string values of 0 or 1 but actual string values of true or false. If the values stored in your config file are still in the format of true or false then this would be why your first line is breaking. You can't convert false or true strings to an int. It does look like someone just added something to break the code.
Also you don't mention what technology you are using. You could be using winforms, wpf, webforms, or MVC. I'm going to assume this is a web technology you are using because checbox.value is something I usually see in javascript. General consensus in setting checkbox values in javascript is by using the .prop() property which takes in a string as the property you want to change and a value as the second parameter. E.G.
$( "input" ).prop( "checked", true );
http://api.jquery.com/prop/
Moral of the story is remove the conversion to the int32 and use .prop() to set that checkbox :)
Related
I have some code in c# which needs to increment a number by 1 if a certain boolean value is true, but else it needs to say the same. The only method i've found using the Immediate window in VS 2012 is by + Convert.ToInt32(boolean).
Am I missing something obvious in here somewhere? I thought since a boolean is basically true (1) or false(0) (let's forget about FileNotFound), it would be easier to coerce a boolean to an Int value.
edit:
false is 0, not 1
edit2: my original edit got swallowed up. I'm currently doing a nullcheck on the number (the number is a nullable int field from a Dynamics CRM 2011 entity). Is it possible to keep that nullcheck?
I don't think that adding boolean flag to some value is very readable solution. Basically you want to increment (i.e. add 1) value if flag is true. So, simple if check will clearly describe your intent add do the job:
if (flag) value++;
UPDATE: According to your edit, you want to do two things:
Set default value to your nullable value
Increment value if some condition is true.
To make your code clear, I would not try to put both things in one line. Make your intent explicit:
value = value ?? 0; // 1
if (flag) // 2
value++;
The simple solution would be like so:
val += flag ? 1 : 0;
The fact is that a .NET boolean is simply a completely different type from integer (unlike in, say, C++, where it's a "renamed" integer). The fact, that it is actually implemented using an integer value, is implementation detail and not to be relied upon. In fact, you can do a lot of strange things when you mess with the actual value of the boolean (for example, using direct memory manipulation or overlapping structure fields) - the consistency goes away.
So, don't work with the "actual value of boolean". Simply expect the two possible values, true and false, and work with those.
You can still use the null-check and add the value according to the boolean, like this:
obj.Variable = (obj.Variable ?? 0) + (yourBoolean ? 1 : 0);
//obj is the instance of your object
//Variable is the nullable integer
//yourBoolean is the bool to check against
Object.variable is int variable OR Nullable? If Int varable it's default value is 0, and you can just write like this: Object.variable+=bool?1:0, else can use it: Object.variable=Object.variable??0+bool?1:0
I have a report that outputs 4 labels per page.
The data are correctly retrieved from an ArrayList of a class that I have made only for the report and are correctly displayed.
In my class there are also 4 booleans named: Show1, Show2, Show3, Show4, that I'm using for adjust the visibility of 4 Text Objects with a White background, 1 for each label:
if isnull({MyModel.Show1}) then
false
else
if {MyModel.Show1} then
true
else
false
The problem is that the report throws an exception, asking me for a Boolean. But these variables are never null, always false and true when necessary. I have put the null-check for avoid problems, but the exception is thrown without the null check too.
I have tried to change the type of the variables, using an int instead of a bool and checking the number, returning true or false if 1 or 0: nothing changes, in this case the exception asks me for an integer.
The exception is ErrorKind with the message A boolean is required here or A number is required here in the 2nd case.
I can't understand what is happening...
Any suggestion?
Thanks all
Ok, I've solved the problem.
I have realized that the formula wants the condition, not the return value. So the correct formula, in Crystal syntax, is:
{MyModel.Show1} = true
If the condition is true, the return will be true, else the return will be false, and all work fine.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Is there a global variable (across web pages) I can use in C# WebMatrix, that actually works?
I have a rather odd (to me) problem. I have tested and tried many things and traced the problem down to one simple fact.
When I try to compare an AppState["uniqueName"] to a string value, it always evaluates to false. Here are a couple of snippets so you can see what I have:
On the first page:
AppState["gAdmitsMembership"] = AdmitsMembership;
On the second page:
if(AppState["gAdmitsMembership"]=="true"){checkBoxes[0]="checked='checked'";}else{checkBoxes[0]="";}
As you can probably tell the point is to keep a checkbox checked after submitting a form (and subsequently bringing the data back up in another form for possible editing)
Now, as I stated, I have tested many things and this is what I have done.
I plotted the value of AppState["gAdmitsMembership"] directly to a text input field (in the second page), in order to see what the actual value being tested was. It was indeed "true", however it still always equates to false (which I determined with another test by manipulating what happens with the "else".
Why is this failing the if condition?
It is important to note that nowhere in the code is this value "true" a boolean value. It is always the string "true". I have to do it this way because when I try:
if(AppState["gAdmitsMembership"]==true){checkBoxes[0]="checked='checked'";}else{checkBoxes[0]="";}
(same thing only with boolean true)
I get an error that says '== cannot be compared to objects or boolean' or something to that effect.
For this reason the compared string value must remain as "true" so that when it is added to the database it will be converted to the database as the necessary boolean value, true.
Anyway, any help that gets me through this will be quickly accepted and definitely appreciated. Thanks!
The syntax you use to assign a value to the AppState variable on the first page is not the right one.
Try with
App.gAdmitsMembership = AdmitsMembership;
as stated in this previous thread: Webmatrix 2: Storing static values.
here are 2 screen shots when i try to debug my code in visual studio 2005
i want to save string value in variable check in variable a but it saves -1 not the actual string which is something like that "<username>admin</username>"
If you want to save the value of check in a, then your assignment is the wrong way round. Currently it's converting the value of a to a string, and storing the result in check.
Of course, you haven't specified the type of a - it may be converted to a string one way in the debugger, but the actual ToString method may be overridden to do something different.
If you actually meant to describe the question the other way round, you need to provide a lot more information - a short but complete program to demonstrate the problem would be ideal.
String assignment very definitely works in C# - so the chances are incredibly high that you're doing something strange in the code that you haven't shown us.
I have a new laptop at work and code that worked earlier in the week does not work today.
The code that worked before is, simplified:
while (dr.Read())
{
int i = int.Parse(dr.GetString(1))
}
Now it fails when the database value is 0. Sometimes, but not reliably, this will work instead:
while (dr.Read())
{
int i = Convert.ToInt32(dr["FieldName"]))
}
Am I missing something stupid?
Oddly enough, ReSharper is also having tons of weird errors with the same error message that I am getting with the above code: "input string was not in the correct format." (Starts before I even load a project.)
Any ideas? Anyone having any SP issues? I did try to make sure all my SPs were up-to-date when I got the machine.
EDIT: I understand how to use Try.Parse and error-handling. The code here is simplified. I am reading test cases from a database table. This column has only 0, 1, and 2 values. I have confirmed that. I broke this down putting the database field into a string variable s and then trying int.Parse(s). The code worked earlier this week and the database has not changed. The only thing that has changed is my environment.
To completely simplify the problem, this line of code throws an exception ("input string was not in the correct format"):
int.Parse("0");
EDIT: Thanks to everyone for helping me resolve this issue! The solution was forcing a reset of my language settings.
A possible explanation:
Basically, the problem was the
sPositiveSign value under
HKEY_CURRENT_USER\Control
Panel\International being set to 0,
which means the positive sign is '0'.
Thus, while parsing the "positive sign
0" is being cut off and then the rest
of the string ("") is parsed as a
number, which doesn't work of course.
This also explains why int.Parse("00")
wasn't a problem. Although you can't
set the positive sign to '0' through
the Control Panel, it's still possible
to do it through the registry, causing
problems. No idea how the computer of
the user in the post ended up with
this wrong setting...
Better yet, what is the output of this on your machine:
Console.WriteLine(System.Globalization.NumberFormatInfo.GetInstance(null).PositiveSign);
I'm willing to bet yours prints out a 0... when mine prints out a + sign.
I suggest checking your Control Panel > Regional and Language Options settings... if they appear normal, try changing them to something else than back to whatever language you're using (I'm assuming English).
I think it's generally not considered a good idea to call Convert.ToInt32 for the value reading out of database, what about the value is null, what about the value cannot be parsed. Do you have any exception handling code here.
Make sure the value is not null.
Check the value can be parsed before call Int32.Parse. Consider Int32.TryParse.
consider use a nullable type like int? in this case.
HTH.
Edit:
#Mike's response made me think that is extremely odd behavior and a simple google search yielded this result: int.Parse weird behavior
An empty string would also cause this issue.
You could check for dbnull before parsing, also it is good to validate parsed data.
You could use a default value and TryParse..
int i = -1;
if(!int.TryParse(dr["MyColumn"] as string, out i))
//Uh Oh!
Edit:
I posted this as a comment in #Chris' answer, but if the sql datatype is int then why not just use the GetInt32 method on the DataReater instead of retrieving it as a string and manual parsing it out?
Are you sure it's "0" and not "null"? What exception do you get?
EDIT:
Just out of curiosity, if it is really faulting on int.Parse("0"), can you try int.Parse("0", CultureInfo.InvariantCulture);?
Otherwise, post your query. Any joins?
you should check dr["FieldName"] != DBNull.Value and you should use TryParse if it passes the DBNull test...
if ( dr["FieldName"] != DBNull.Value )
{
int val = 0;
if ( int.TryParse( dr["FieldName"], out val ) )
{
i = val;
}
else
{
i = 0; // or some default value
}
}
I have seen this issue crop up with .NET Double class, parsing from string "0" as well.
Here's the really wacky part: you can get past the issue by using a different user account to run the program, and sometimes if you destroy and re-create the current user account on the machine, it will run fine.
I have yet to track this down, but you might get past it this way at least.
This is way out of left field, but check your localization settings. I had a number of "input string was not in a correct format" when I moved a web site to a Canadian server. The problem was in a DateTime.Parse method, and was fixed by setting the culture to "en-US".
Yes, your situation is different — but hey, you never know.
are you checking for null ?
if(!dr.IsNull("FieldName")){
int i = Convert.ToInt32(dr["FieldName"]))
}