I want to check if my variable(crphoto1) is null. If crphoto1 is null, crPhoto1Data should be null and when crphoto1 is not null crPhoto1Data should be like this byte[] crPhoto1Data = File.ReadAllBytes(crphoto1);. The code belows gives me error how can I fix it?
if (string.IsNullOrEmpty(crphoto1))
{
string crPhoto1Data = "";
}
else
{
byte[] crPhoto1Data = File.ReadAllBytes(crphoto1);
}
var ph1link = "http://" + ipaddress + Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Contact=" + contact + "&Request=tWyd43";
string ph1contentType = "application/json";
JObject ph1json = new JObject
{
{ "ContactID", crcontactID },
{ "Photo1", crPhoto1Data }
};
The problem is that you're trying to use a variable that is declared inside a block with a narrower scope (you define crPhoto1Data inside the if block). Another problem is that you're trying to set it to more than one type.
One way solve this is to create the JObject in an if/else statement (or using the ternary operator as in my sample below):
JObject ph1json = string.IsNullOrEmpty(crphoto1)
? new JObject
{
{"ContactID", crcontactID},
{"Photo1", ""}
}
: new JObject
{
{"ContactID", crcontactID},
{"Photo1", File.ReadAllBytes(crphoto1)}
};
Related
So, i'm calling the method to update the primary "sendAs" object of a google account, without results. The documentation from google at users.settings.sendAs/update indicates all i need and did:
i've set the domain wide account and scopes
i'm generating a token and accessing it no problem
i'm calling the "list" method first (with that token) as shown in users.settings.sendAs/list documentation, and finding the one that is the primary (the "isPrimary" attribute is true)
After that, changing the "signature" value to "Its a Test Signature", and sending the PUT request with it doesn't do anything.
The JSON sent to the update API (via PUT method) is the exact one i collected from the list (the primary one), but with the signature changed.
There is no error at all, and i receive an "sendAs" object back as a response (as the documentation says i should in case of sucess), but the signature is unchanged.
What can i be?
EDIT (adding the code section for the call, again - no errors)
public bool Update()
{
string json = null;
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
wc.Headers["Authorization"] = "Bearer " + GenerateServerToServerToken(this.OwnerMail, this.scope);
json = wc.DownloadString("https://gmail.googleapis.com/gmail/v1/users/" + this.OwnerMail + "/settings/sendAs");
JSon.Query response = JSon.Parse(ref json);
json = null;
response = response["sendAs"];
List<JSon.Query> mailAs = null;
if (response.TryParseList(out mailAs))
{
JSon.Query main = null;
bool prim = false;
foreach (JSon.Query q in mailAs)
{
if (q["isPrimary"].TryParseBoolean(out prim) && prim)
{
if (q["sendAsEmail"].TryParseString(out json)) { main = q; }
break;
} else { json = null; }
}
if (main != null)
{
JSon.ObjectValue mainO = (JSon.ObjectValue)main.Value;
if (mainO.ContainsKey("signature"))
{
((JSon.StringValue)mainO["signature"]).Data = this.HtmlSignature.Replace("<", ("\\" + "u003c")).Replace(">", ("\\" + "u003e"));
mainO["verificationStatus"] = new MdIO.JSon.StringValue("accepted");
json = wc.UploadString("https://gmail.googleapis.com/gmail/v1/users/" + this.OwnerMail + "/settings/sendAs/" + json, "PUT", main.Value.ToJSON());
response = JSon.Parse(ref json);
if (response["sendAsEmail"].TryParseString(out json) && !string.IsNullOrEmpty(json)) { return true; }
}
}
}
}
return false;
}
So I would like to read out all occurrences in C# in one string and work with it. Means I need the position of the part string, but I don't know how. Example:
The main string can look like this:
Currently there are %count{"only_groups":"1, 2, 3","ignore_channels":"1, 2, 3"}% supporters online, %count{"ignore_channels":"1, 2, 3","querys":"false"}% of them are afk. These are the active supporters: %list{"querys":"false","only_groups":"1, 2, 3"}%
Contentwise this string makes no sense, but I think you can understand what I mean by these strings. There are also more possible variables besides %count% and %list%
Now I want to keep all these variables and replace something instead.
I already have the following code, but it would only replace one variable and it would only recognize the %count% variable if it is completely lower case:
int pFrom = channel_name.IndexOf("%count{") + "%count{".Length;
int pTo = channel_name.LastIndexOf("}%");
string result = channel_name.Substring(pFrom, pTo - pFrom);
Logger.Info(result);
string json2 = #"{" + result + "}";
JObject o2 = JObject.Parse(json2);
foreach (JProperty property in o2.Properties())
{
var pname = property.Name;
if (pname == "only_groups")
{
only_groups = property.Value.ToString();
}
else if (pname == "ignore_groups")
{
ignore_groups = property.Value.ToString();
}
else if (pname == "only_channels")
{
only_channels = property.Value.ToString();
}
else if (pname == "ignore_channels")
{
ignore_channels = property.Value.ToString();
}
else if (pname == "away")
{
away = property.Value.ToString();
}
else if (pname == "querys")
{
query = property.Value.ToString();
}
}
var serverVar = (await fullClient.GetServerVariables()).Value;
if (query.Equals("only"))
{
channel_name = "User online: " + serverVar.QueriesOnline;
}
else if (query.Equals("ignore"))
{
channel_name = "User online: " + (serverVar.ClientsOnline - serverVar.QueriesOnline);
}
else
{
channel_name = "User online: " + serverVar.ClientsOnline;
}
I hope people understand what I'm about to do. My English is not the best
Use Regex.Matches() to get a list of all occurences.
This pattern will find all variables including configuration json:
(?s)%.*?%
Then you just need to extract the 2 parts out of the matched value.
This will find only the variable name within the matched value:
(?s)(?<=%).+?(?=({|%))
This will find the JSON configuration within the matched value if there is any:
(?s){.*}
Only caveat is you can't use % character anywhere in text outside of variables.
I want to use the below list globally in my aspx page whose name is lstUMSGroupDetails. Currently I am getting its value from a function.
I want to use that list values in other functions too. SO how should I make it global.
its code is below
private void Get_AuthenticateUser_Ums(string strUName)
{
string strCurrentGroupName = "";
int intCurrentGroupID = 0;
try
{
if (!string.IsNullOrEmpty(strUName))
{
List<IPColoBilling.App_Code.UMS.UMSGroupDetails> lstUMSGroupDetails = null;
List<IPColoBilling.App_Code.UMS.UMSLocationDetails> lstUMSLocationDetails = null;
objGetUMS.GetUMSGroups(strUserName, out strCurrentGroupName, out intCurrentGroupID, out lstUMSLocationDetails, out lstUMSGroupDetails);
if (strCurrentGroupName != "" && intCurrentGroupID != 0)
{
strCurrentGrp = strCurrentGroupName;
intCurrentGrpId = intCurrentGroupID;
}
else
{
Response.Redirect("~/NotAuthorize.aspx", false);
}
}
}
catch (Exception ex)
{
string strErrorMsg = ex.Message.ToString() + " " + "StackTrace :" + ex.StackTrace.ToString();
CommonDB.WriteLog("ERROR:" + strErrorMsg, ConfigurationManager.AppSettings["IPCOLO_LOG"].ToString());
}
You can store it in Session.
Session["lstUMSGroupDetails"] = lstUMSGroupDetails;
Then you can get this by.
List<IPColoBilling.App_Code.UMS.UMSGroupDetails> lstUMSGroupDetails = (List<IPColoBilling.App_Code.UMS.UMSGroupDetails>)Session["lstUMSGroupDetails"];
For more information please see MSDN Reference.
Could you not assign it to a slot in the Session Dictionary?
For example:
var myList = new List<int>();
Session["groups"] = myList;
So I'm trying to get the weather from the Yahoo's weather Json, but the thing is I keep getting this error
{"Cannot access child value on Newtonsoft.Json.Linq.JValue."}
Right now I have no idea why is this happening. I checked the parenting a few times already, the spelling and all that.
public String GetWeather() {
StringBuilder theWebAddress = new StringBuilder();
theWebAddress.Append("https://query.yahooapis.com/v1/public/yql?");
theWebAddress.Append("q=" + System.Web.HttpUtility.UrlEncode("select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='"+ city + ", "+ state + "') and u='" + units +"'"));
theWebAddress.Append("&format=json");
theWebAddress.Append("&diagnostics=false");
string results = "";
using (WebClient wClient = new WebClient())
{
results = wClient.DownloadString(theWebAddress.ToString());
}
JObject dataObject = JObject.Parse(results);
JArray jsonArray = (JArray)dataObject["query"]["results"]["channel"]; //This is the line that is generating the error.
foreach (var woeid in jsonArray)
{
//stocheaza informatiile in variabile
condition = woeid["item"]["condition"]["text"].ToString();
//System.Diagnostics.Debug.WriteLine(condition);
return condition;
}
return null;
}
The link to the API is here. So as far as I see, there is problem with getting the child of query or results. Any ideas? Thanks in advance.
I solved it by changing the code. Instead of using that code, I changed it with this
public string GetWeather(string info)
{
string results = "";
using (WebClient wc = new WebClient())
{
results = wc.DownloadString("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%27galati%2C%20ro%27)%20and%20u%3D%22c%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
}
dynamic jo = JObject.Parse(results);
if (info == "cond")
{
var items = jo.query.results.channel.item.condition;
condition = items.text;
return condition;
}
}
Now it works as intended.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
In the below code i have a string value it has a path.I want to place the String value inside the static method But i get Object reference not set to an instance of an object.if i write path in that code it works but not string value which has path .pls help me to solve the issue.
var projectname = name.ProjectName;
var batchname = name.BatchName;
var imagename = name.ImageName;
string concatenatedStr = "/"+ projectname + "/" + batchname + "/Input/" + imagename;
[WebMethod]
public static string buttonclickImage(string pageNo)
{
int iPageNo = 0;
if (pageNo != string.Empty && pageNo != "undefined")
iPageNo = Int32.Parse(pageNo);
FileTransfer.FileTransferClient fileTranz = new FileTransfer.FileTransferClient();
FileDto file = fileTranz.GetTifftoJPEG("concatenatedStr", iPageNo, "gmasdll");
var fileData = Convert.ToBase64String(file.Content);//throws error
return fileData;
}
it means that either file is null or file.Content is null. You can avoid the exception by
if(file!=null && file.Content!=null)
{
//your remaining code
}
ideally though you should first check the reason why it is null
Edit:
From your comments i infer that you want to pass your varible. Either make your string static, or make your method not static or pass the string to your method
[WebMethod]
public static string buttonclickImage(string pageNo)
{
int iPageNo = 0;
if (pageNo != string.Empty && pageNo != "undefined")
iPageNo = Int32.Parse(pageNo);
FileTransfer.FileTransferClient fileTranz = new FileTransfer.FileTransferClient();
//note the change here. no double quotes.
FileDto file = fileTranz.GetTifftoJPEG(concatenatedStr, iPageNo, "gmasdll");
var fileData = Convert.ToBase64String(file.Content);//throws error
return fileData;
}
You're not passing in the value stored in the concatenatedStr variable... you're passing in the literal string "concatenatedStr".
Change this:
FileDto file = fileTranz.GetTifftoJPEG("concatenatedStr", iPageNo, "gmasdll");
To this:
FileDto file = fileTranz.GetTifftoJPEG(concatenatedStr, iPageNo, "gmasdll");
You'll also need to make your variables static, since your method is static. Or leave the variables as they are, and make the method non-static, if that's an option.
I'm a little confused about where those variables are located though. They appear to be class-level in scope, but then you wouldn't be able to use var in that location.
I guess you could also modify your method to accept an additional parameter, and then pass in the value from wherever you're calling this.
public static string buttonclickImage(string pageNo, string concatenatedStr)
{
...
This works
[WebMethod]
public static string buttonclickImage(string pageNo)
{
var name = (name)HttpContext.Current.Session["Projectname"];
var projectname = name.ProjectName;
var batchname = name.BatchName;
var imagename = name.ImageName;
string concatenatedStr = "/" + projectname + "/" + batchname + "/Input/" + imagename;
int iPageNo = 0;
if (pageNo != string.Empty && pageNo != "undefined")
iPageNo = Int32.Parse(pageNo);
FileTransfer.FileTransferClient fileTranz = new FileTransfer.FileTransferClient();
FileDto file = fileTranz.GetTifftoJPEG(concatenatedStr, iPageNo, "gmasdll");
var fileData = Convert.ToBase64String(file.Content);
return fileData;
}
First of all construct value of "concatenatedStr" variable using String.Format.
For Eg:-
var projectname = name.ProjectName;
var batchname = name.BatchName;
var imagename = name.ImageName;
string concatenatedStr = string.Format("/{0}/{1}/Input/{2}", projectname, batchname, imagename);
Put debug point here and check what value "concatenatedStr" has.
If "concatenatedStr" is null then definitely you will get "Nullreference exception"....
So may be there is a problem with "concatenatedStr".....So deeply check concatenation variables too...
Hope this works......