Having problems with this code ..
GlodalVariables.SoftID = "55";
WebClient client = new WebClient ();
Uri uri = new Uri ("http://www.example.com/CreateEntry.php");
string folder = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
Android.Content.Context myContext = Android.App.Application.Context;
try{
string smsUri = System.IO.Path.Combine (folder, "SL.db");
string myjson = "";
SQLiteDatabase Mydb = SQLiteDatabase.OpenDatabase(smsUri , null, DatabaseOpenFlags.OpenReadwrite );
ICursor SMScursor = Mydb.Query ("MySMSLog", null,null, null,null, null ,"TheDate ASC");
MySMSLog test = new MySMSLog() ;
if (SMScursor.MoveToFirst ()) {
while (!SMScursor.IsAfterLast){
string number = SMScursor.GetString(SMScursor.GetColumnIndex("TheNumber"));
string name = SMScursor.GetString(SMScursor.GetColumnIndex("TheName"));
string date = SMScursor.GetString(SMScursor.GetColumnIndex("TheDate"));
string direction = SMScursor.GetString(SMScursor.GetColumnIndex("TheDirection"));
string text = SMScursor.GetString(SMScursor.GetColumnIndex("TheText"));
string id = SMScursor.GetString(SMScursor.GetColumnIndex("Id"));
test.Id = int.Parse(id);
test.TheDate = date;
test.TheDirection = direction ;
test.TheName = name;
test.TheNumber = number;
test.TheText = text;
string output = Newtonsoft.Json.JsonConvert.SerializeObject (test);
myjson = myjson + output + " ";
SMScursor.MoveToNext ();
}
}
System.Console.WriteLine (myjson );
System.Console.WriteLine();
SMScursor.Close ();
When i Copy the complete json string into a json test site (http://jsonlint.com/)
It tells me the sting is invalid ...
I'm getting all the record rows and putting them into a single json string before pushing them over to the server..
Shouldn't you get the result in an array form? So the final json should look like :
[{json1},{json2}..]
Probably if you have just {json1} {json2} this is not a valid object.
Could an alternative solution be to build a collection of "MySMSLog" objects, then serialise the collection throught JSonConvert? That way you don't need to worry about getting the structure correct through your own string manipulation.
This would most likely also future proof your code on the ridiculously outlandish chance that JSON standards change, as the NewtonSoft library would be updated as well.
Related
I'm trying to create a HTTP url request to get Amazon items by its ASIN Array. I'm using the same code in my Objective-c code for the same reason and it's work perfectly.
But i'm getting this messeage everytime i try to access the url in my chrome:
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
This is the code i'm using:
private void GetFinalUrlForAsinArray(ArrayList asinArr)
{
String timeStamp = GetTimeStamp();
String amazonAPIUrl = "http://webservices.amazon.com/onca/xml?";
ArrayList param = new ArrayList();
param.Add("AWSAccessKeyId=myawsaccesskeyid");
param.Add("AssociateTag=myassociatetag");
param.Add("IdType=ASIN");
param.Add(string.Join(",", asinArr.ToArray()));
param.Add("Operation=ItemLookup");
param.Add("ResponseGroup=ItemAttributes,Offers");
param.Add("Service=AWSECommerceService");
param.Add(String.Format("Timestamp={0}", timeStamp));
amazonAPIUrl += string.Join("&", param.ToArray());
string queryString = new System.Uri(amazonAPIUrl).Query;
var queryDictionary = HttpUtility.ParseQueryString(queryString);
ArrayList queryItemsNew = new ArrayList();
foreach (var query in queryDictionary)
{
String name = HttpUtility.UrlEncode((string)query);
String value = HttpUtility.UrlEncode((string)queryDictionary.Get((string)query));
queryItemsNew.Add(String.Format("{0}={1}", name,value));
}
String path = string.Join("&", queryItemsNew.ToArray());
String finalPath = String.Format("GET\nwebservices.amazon.com\n/onca/xml\n{0}",path);
string signature = HmacSha256Digest(finalPath);
String finalUrl = String.Format("http://webservices.amazon.com/onca/xml?{0}&Signature={1}", path, signature);
}
private String GetTimeStamp()
{
DateTime d = DateTime.UtcNow;
String str = d.ToString("yyyy-MM-dd''T''HH:mm:ss''Z''");
return str;
}
private static string HmacSha256Digest(string message)
{
UTF8Encoding encoding = new UTF8Encoding();
HMACSHA256 hmac = new HMACSHA256(encoding.GetBytes(mysecret));
string signature = Convert.ToBase64String(hmac.ComputeHash(encoding.GetBytes(message)));
String sigEncoded = Uri.EscapeDataString(signature);
return sigEncoded;
}
Having had a look at the API documentation it looks like you've missed the ItemId key here:
param.Add(string.Join(",", asinArr.ToArray()));
I'm guessing you meant it to be:
param.Add("ItemId=" + string.Join(",", asinArr.ToArray()));
It otherwise looks to comply with the spec, the only other thing I noted was the example had the URL encoding as uppercase i.e. %3A rather than the C# default %3a.
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.
I am trying to get a redirect from Google Maps using a project that is currently only at .Net Framework 4.0.
Take Microsoft's mailing address as an example:
1 Microsoft Way, Redmond, WA
Format a string that replaces Spaces , Commas , with Plus + signs:
https://www.google.com/maps?daddr=1+microsoft+way+redmond+wa
By the time Google finishes processing the page, the final URL has the Latitude and Longitude:
https://www.google.com/maps/dir//1+Microsoft+Way,+Redmond,+WA+98052/#47.6393095,-122.1327333,16z/data=!3m1!4b1!4m8!4m7!1m0!1m5!1m1!1s0x54906d73f7de150b:0x922499d19305e9a0!2m2!1d-122.1283559!2d47.6393096
I need the Latitude and Longitude from this URL.
I found this article already on SO:
Get a collection of redirected URLs from HttpWebResponse
Using the solution there, I created this very similar looking method:
private String latitude, longitude;
private void GetLatLongFromAddress(String p_street_name, String p_city, String p_state, String p_postal_code)
{
var street_name = String.Format("{0}", p_street_name.Replace(' ', '+')).Trim();
var city = String.Format("{0}", p_city).Trim();
var state = String.Format("{0}", p_state).Trim();
var postal_code = String.Format("{0}", p_postal_code).Trim();
var mapUrl = String.Format("http://maps.google.com/?daddr={0}+{1}+{2}+{3}",
street_name, city, state, postal_code);
var location = String.Copy(mapUrl);
while (!String.IsNullOrEmpty(location))
{
var req1 = (HttpWebRequest)HttpWebRequest.Create(location);
req1.AllowAutoRedirect = false;
// give page time to redirect?
// System.Threading.Thread.Sleep(5000);
using (var resp = (HttpWebResponse)req1.GetResponse())
{
location = resp.GetResponseHeader("Location");
if (!String.IsNullOrEmpty(location))
{
var postalIndex = location.IndexOf(postal_code);
var slashAtIndex = location.IndexOf("/#") + 1;
if ((postalIndex < slashAtIndex) && (slashAtIndex < location.Length))
{
var split = location.Substring(slashAtIndex).Split(',');
latitude = split[0];
longitude = split[1];
}
}
}
}
}
You can see where I format the original URL with this line:
var mapUrl = String.Format("http://maps.google.com/?daddr={0}+{1}+{2}+{3}",
street_name, city, state, postal_code);
The problem is with this line:
location = resp.GetResponseHeader("Location");
Every time I get the response, the returned location value is the same as the mapUrl value that I started with because Google does not redirect it immediately.
I tried adding a Sleep(5000) call, but that did not change anything.
How would I go about getting the final redirect?
Im trying to create a settings file with the information for my SQL database, but the issue I am currently having is I cant seem to read each line and save it to a different variable.
private void readFile()
{
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(#"C:\Users\Settings.txt", true))
while (sr.Peek() >= 0)
{
CurrentLine = sr.ReadLine();
}
}
}
Im not sure how I would set it up so that I can write each different line to my 4 variables.
Any help would be appreciated!
I would use an array instead which you can access via index:
string[] lines = File.ReadAllLines(#"C:\Users\Settings.txt");
string firstLine = lines[0];
// and so on, keep in mind that it could have less lines
A StreamReader approach with your four variables is much more cumbersome:
using (System.IO.StreamReader sr = new System.IO.StreamReader(#"C:\Users\Settings.txt", true))
{
string line;
int currentLineNumber = 0;
while ((line = sr.ReadLine()) != null)
{
switch (++currentLineNumber)
{
case 1: first = line; break;
case 2: second = line; break;
case 3: third = line; break;
case 4: fourth = line; break;
}
}
}
When I have needed to store settings in a file, I created a class to hold the information, e.g.
public class Settings{
public string ConnectionString {get;set;}
public string DatabaseName {get;set;}
public DateTime Started {get;set;}
}
Saving settings:
var settings = new Settings(){
ConnectionString = "blah blah blah",
DatabaseName = "blah blah blah",
Started = DateTime.Now,
};
var json = JsonConvert.SerializeObject(settings);
File.WriteAllText(#"C:/Settings.txt", json);
Loading settings:
var json = File.ReadAllText(#"C:/Settings.txt");
var settings = JsonConvert.DeserializeObject(json);
I found this reliable, flexible and stable.
It also means you don't have to worry about converting between (e.g.) DateTime and String. You also don't need to worry about the order of the setting values.
(This uses the Json.NET package.)
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......