Checking if json key exists for a given array index? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
This code throws an exception if the key does not exist.
For example, if the key exists for a position in an array index the code is okay, even if the value is null. But, if the key does not exist the code throws an exception`. The code in the select token parenthesis is dynamic (a string variable).
r["Value"] = json.SelectToken($.Objectives[x].state).ToString() ?? "";

You can't call ToString() on a null value.
JToken value = json.SelectToken("$.Objectives[x].state");
r["Value"] = (value != null) ? value.ToString() : "";

You could use the tenary operator to return a default value if x doesn't exist
r["Value"] = $.Objectives[x] ?
json.SelectToken($.Objectives[x].state).ToString() ?? "
: '';
OR
r["Value"] = x >= $.Objectives.Length ?
json.SelectToken($.Objectives[x].state).ToString() ?? "
: '';
I'm not sure why you end the line with a double quote. Maybe a typo? But I didn't fix it, that code is what you started with.

In javascript, if a given variable has a value, it will return true to the following:
if(r["Value"]){
//this only runs if r["Value"] exists
}

Related

C# - Convert String/Null to decimal [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a method and argument as a string or null. So I am trying to convert the arguments into decimal.. I am trying to use decimal.Parse to convert string to decimal.
If the argument has a null value don't want to convert as a decimal..
public void abcd(string price)
{
decimal result = string.IsNullOrEmpty(price) ? null : decimal.Parse(price);
//error - cannot convert null as decimal
//I tried few other options also.
decimal result = price is null ? 0 : decimal.Parse(price);
// error - VAlue cannot be null
//have other logic here
}
abcd("123");
abcd(null);
If you want a null to represent the absence of value, you can use a nullable variable:
decimal? result = string.IsNullOrEmpty(price) ? null : decimal.Parse(price);
This is a better option than representing a lack of data by a zero as proposed by others.
You may have to check if result is null before using it for certain purposes. However, the usual operations are supported:
See Math operations with null
string i = null;
decimal result;
decimal.TryParse(i, out result);
Console.WriteLine(result.ToString()); // 0
You can set 0 when the string is null or empty.
Please follow the below answer.
public void abcd(string price)
{
decimal result = string.IsNullOrEmpty(price) ? 0: decimal.Parse(price);
}
Try -
public static void abcd(string price)
{
decimal result = string.IsNullOrEmpty(price) ? 0 : decimal.Parse(price);
decimal result2 = price is null ? 0 : decimal.Parse(price);
//have other logic here
}

convert php script to c# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
i want to connect my site(mvc5) to payeer payment proccessor .i read payeers document but all script of document is in php .please help me to convert this script to c#.
<?php if (!in_array($_SER VER['REMOTE_AD DR'], array('185.71.65.92', '185.71.65.189','149.202.17.210'))) return; if isset($_POST['m_operation_id']) && isset($_POST['m_sign'])){ $m_key = 'Your secret key';$arHash = array($_POST['m_operation_id'],$_POST['m_operation_ps'],$_POST['m_operation_date'],$_POST['m_operation_pay_date'],$_POST['m_shop'],$_POST['m_orderid'],$_POST['m_amount'],$_POST['m_curr'],$_POST['m_desc'],$_POST['m_status']);if isset($_POST['m_params'])){$arHash[] = $_POST['m_params'];}$arHash[] = $m_key;$sign_hash = strtoupper(hash('sha256', implode(':', $arHash)));if $_POST['m_sign'] == $sign_hash && $_POST['m_status'] == 'success'){exit($_POST['m_orderid'].'|success');}exit($_POST['m_orderid'].'|error');}?>
if (!in_array($_SERVER['REMOTE_AD DR'], array('185.71.65.92', '185.71.65.189','149.202.17.210'))) return;
in this line code checks if the client address is in white list, if it is not in white list so block request, you can do this in c# using this code:
string[] whiteListIps = new string[]{'185.71.65.92', '185.71.65.189','149.202.17.210'};
var clientIp = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if(!whiteListIps.Contains(clientIp))
return Redirect("/UnAuthorized");
in the next line you should check if m_operation_id and m_sign exists in Request.Body
the below is in php:
if isset($_POST['m_operation_id']) && isset($_POST['m_sign']))
in c#:
if(Request.Form["m_operation_id"] != null && Request.Form("m_sign") != null)
$m_key and $arHash just are variables that declared based on posted values and a key that will used in SHA256 algorithm to decode message to ensure if received message hash is equal with parameters value

Safely access and parse a bool from a Dictionary [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have an application that uses a Dictionary<String,String> to store configuration.
I want to:
Check if the dictionary contains "Key"
Parse the Value of "Key" as a bool
Default to false if not found
Presently I am doing the following
bool settingBool = false
if (configDictionary.ContainsKey("Key")) {
bool.Tryparse(configDictionary["Key"], out settingBool)
}
// Do some stuff with settingBool
Are there any pitfalls or obvious issues with the above approach especially from a readability/maintainability aspect?
Are there any pitfalls or obvious issues with the above approach especially from a readability/maintainability aspect?
As an addition to #Cetin Basoz answer.
Since you want to do something with your settingsBool I personally would go with configDictionary.TryGetValue("Key", out value), because
TryGetValue
This method combines the functionality of the ContainsKey method and the Item[TKey] property.
So for your example:
var configDictionary = new Dictionary<string,string>() { { "Key" , "Value"} };
string value;
bool settingBool;
if ( configDictionary.TryGetValue("Key", out value)
&& bool.TryParse(value, out settingBool) )
{
// Do something with your settingBool
}
else
{
// Do something if "Key" is not present or Value could not be parsed.
}
Hint: You did not need to set your settingBool to false, since false is the default value. Try default(bool)
If one liner is needed or adding if the value parseable as bool then you can use && :
bool settingBool = false;
if (configDictionary.ContainsKey("Key") && bool.TryParse(configDictionary["Key"], out settingBool)
{
}
else {} // what if not? Then wouldn't you accept as false?
If default would be false when not found or not parseable to bool:
bool settingBool = false;
settingBool = configDictionary.ContainsKey("Key") &&
bool.TryParse(configDictionary["Key"], out settingBool)
&& settingBool;
The latter could be used to get with Linq to get multiple bool settings.
Note: bool.TryParse can parse limited strings as bools (it doesn't parse Yes, No, Y/N, 1/0 ... as bools).

"use of unassigned local variable" error when passing ref parameter [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This code generates the error:
used of unassigned local variable 'namespace2'
XNamespace namespace2;
string partText = Declaration.partText;
Declaration.partText = string.Empty;
string str = "";
IEnumerable<XElement> source = InputXDoc.Descendants(Function.GetNamespace(ref namespace2, "").GetName("body"));
if (source.Descendants<XElement>(Function.GetNamespace(ref namespace2, "").GetName("div")).Count<XElement>() > 0)
{
IEnumerable<XElement> introduced5 = InputXDoc.Descendants(Function.GetNamespace(ref namespace2, "").GetName("body"));
if (introduced5.Descendants<XElement>(Function.GetNamespace(ref namespace2, "").GetName("div")).First<XElement>().Attributes("id").Count<XAttribute>() > 0)
{
IEnumerable<XElement> introduced6 = InputXDoc.Descendants(Function.GetNamespace(ref namespace2, "").GetName("body"));
this.ChapterName = introduced6.Descendants<XElement>(Function.GetNamespace(ref namespace2, "").GetName("div")).First<XElement>().Attributes("id").First<XAttribute>().Value;
}
}
Why did I encounter this?
From MSDN for ref:
An argument that is passed to a ref parameter must be initialized
before it is passed. This differs from out parameters, whose arguments
do not have to be explicitly initialized before they are passed. For
more information, see out.
so you need to write:
XNamespace namespace2 = null;
Its always good practice to initialize your variables anyways!
Note: I initialized to null because I don't know what your parameter actually needs to be initialized to. Check the documentation for the function you are calling, you will likely need it to be something else.

left hand side of an assignment must be a variable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Trying to put an integer data from database(Linq to sql) into a label getting this error exception:
left-hand side of an assignment must be a variable property or
indexer
Code:
protected void Page_Load(object sender, EventArgs e)
{
DataClassesDataContext data = new DataClassesDataContext();
var visit = (from v in data.SeeSites where v.Date == todaydate select v).FirstOrDefault();
int seennow = visit.See; // On This line I can put data in seenow variable, no problem
Convert.ToInt64(lblSeeNow.Text) = visit.See; // exception error appears here
}
Try:
if (visit.See != null) {
lblSeeNow.Text = visit.See.ToString();
}
You cannot assign something to a function result. In your case lblSeeNow.Text is of type String hence usage of ToString(); method of your Int value.
You need to use
lblSeeNow.Text = visit.See.ToString();
Convert.ToInt64(lblSeeNow.Text) = visit.See;
As you mentioned, this is the issue.
Convert.ToInt64 is a method. But you're trying to save a value to it.
You can't.
Just do this
lblSeeNow.Text = visit.See.ToString();
I think you want
lblSeeNow.Text = visit.See.ToString();
You can't assign anything to
Convert.ToInt64(lblSeeNow.Text)
because it evaluates to a number.
Convert.ToInt64(lblSeeNow.Text) isn't a variable. It takes the value in lblSeeNow.Text and converts it to a long. There isn't a variable to store stuff in anymore.
You probably want this:
lblSeeeNow.Text = visit.See.ToString();
You should convert the integer to string, also add a check for being sure that visit is not null
lblSeeNow.Text = visit != null ? visit.See.ToString() : string.Empty

Categories