String from response object cannot be converted to string - c#
I am trying to convert a json response object into a string but I have an issue
This is the documentation I am using to convert to a c# nuget package
https://craftyclicks.co.uk/docs/postcode-lookup/#full-address-rapidaddress
More specifically this bit to do with returning any errors.
https://craftyclicks.co.uk/docs/postcode-lookup/#debugging
public void GetRapidAddressByPostCode(string mPostCode)
{
mApiKey = ConfigurationManager.AppSettings["CraftyClicksApiKey"];
string urlToApi = ConfigurationManager.AppSettings["CraftyClicksApiUrl"];
if (!String.IsNullOrEmpty(urlToApi))
{
url = String.Format(urlToApi + "?postcode={0}&response=data_formatted&key={1}",
mPostCode, mApiKey);
}
else
{
url = String.Format("http://pcls1.craftyclicks.co.uk/json/rapidaddress?postcode={0}&response=data_formatted&key={1}",
mPostCode, mApiKey);
}
//Complete XML HTTP Request
WebRequest request = WebRequest.Create(url);
//Complete XML HTTP Response
WebResponse response = request.GetResponse();
//Declare and set a stream reader to read the returned XML
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
// Get the requests json object and convert it to in memory dynamic
// Note: that you are able to convert to a specific object if required.
var jsonResponseObject = JsonConvert.DeserializeObject<dynamic>(reader.ReadToEnd());
// check that there are delivery points
if (jsonResponseObject !=null || jsonResponseObject.delivery_points !=null)
{
//If the node list contains address nodes then move on.
int i = 0;
foreach (var node in jsonResponseObject.delivery_points)
{
ClsAddress address = new ClsAddress()
{
AddressID = i,
AddressLine1 = node.line_1,
AddressLine2 = node.line_2,
County = jsonResponseObject.postal_county,
PostCode = jsonResponseObject.postcode,
Town = jsonResponseObject.town
};
addressList.Add(address);
i++;
}
}
else
{
foreach (var node in jsonResponseObject)
{
// Get the details of the error message and return it the user.
switch ((string)node.Value)
{
case "0001":
mStatus = "Post Code not found";
break;
case "0002":
mStatus = "Invalid Post Code format";
break;
case "7001":
mStatus = "Demo limit exceeded";
break;
case "8001":
mStatus = "Invalid or no access token";
break;
case "8003":
mStatus = "Account credit allowance exceeded";
break;
case "8004":
mStatus = "Access denied due to access rules";
break;
case "8005":
mStatus = "Access denied, account suspended";
break;
case "9001":
mStatus = "Internal server error";
break;
default:
mStatus = (string)node.Value;
break;
}
}
}
}
But the problem I am getting is it says it cannot convert array to string at the switch statement. I think the problem is when i accessing delivery points when it does not exist i think my null check
Edit to show valid json
When A post code is not found the following json will be returned
{"error_code":"0001","error_msg":"No data was found for the requested
postcode."}
However when a valid property post code is found it will return the following.
{"delivery_points":[{"organisation_name":"","department_name":"","line_1":"1
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488593","dps":"1A"},{"organisation_name":"","department_name":"","line_1":"3
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488604","dps":"1B"},{"organisation_name":"","department_name":"","line_1":"5
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488606","dps":"1D"},{"organisation_name":"","department_name":"","line_1":"7
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488608","dps":"1E"},{"organisation_name":"","department_name":"","line_1":"9
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488610","dps":"1F"},{"organisation_name":"","department_name":"","line_1":"11
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488595","dps":"1G"},{"organisation_name":"","department_name":"","line_1":"15
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488598","dps":"1H"},{"organisation_name":"","department_name":"","line_1":"17
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488600","dps":"1J"},{"organisation_name":"","department_name":"","line_1":"2
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488603","dps":"1L"},{"organisation_name":"","department_name":"","line_1":"4
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488605","dps":"1N"},{"organisation_name":"","department_name":"","line_1":"6
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488607","dps":"1P"},{"organisation_name":"","department_name":"","line_1":"8
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488609","dps":"1Q"},{"organisation_name":"","department_name":"","line_1":"10
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488594","dps":"1R"},{"organisation_name":"","department_name":"","line_1":"12
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488596","dps":"1S"},{"organisation_name":"","department_name":"","line_1":"14
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488597","dps":"1T"},{"organisation_name":"","department_name":"","line_1":"16
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488599","dps":"1U"},{"organisation_name":"","department_name":"","line_1":"18
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488601","dps":"1W"},{"organisation_name":"","department_name":"","line_1":"19
HUNTINGDALE
CRESCENT","line_2":"","udprn":"03488602","dps":"1X"}],"delivery_point_count":18,"postal_county":"COUNTY
ANTRIM","traditional_county":"COUNTY
ANTRIM","town":"BALLYCLARE","postcode":"BT39 9YY"}
System.ArgumentException: 'Can not convert Array to String.'
the json in question is as follows
Showing My Debugging at present.
I think that there is a problem in your code that is caused by the following check:
if (jsonResponseObject !=null || jsonResponseObject.delivery_points !=null)
Since this check will return true whether the JSON response returns error object or the expected object that contains delivery_points.
Your code should be like the following:
if (jsonResponseObject !=null)
{
if(jsonResponseObject.delivery_points !=null)
{
//If the node list contains address nodes then move on.
int i = 0;
foreach (var node in jsonResponseObject.delivery_points)
{
ClsAddress address = new ClsAddress()
{
AddressID = i,
AddressLine1 = node.line_1,
AddressLine2 = node.line_2,
County = jsonResponseObject.postal_county,
PostCode = jsonResponseObject.postcode,
Town = jsonResponseObject.town
};
addressList.Add(address);
i++;
}
}
else
{
foreach (var node in jsonResponseObject)
{
// Get the details of the error message and return it the user.
switch ((string)node.Value)
{
case "0001":
mStatus = "Post Code not found";
break;
case "0002":
mStatus = "Invalid Post Code format";
break;
case "7001":
mStatus = "Demo limit exceeded";
break;
case "8001":
mStatus = "Invalid or no access token";
break;
case "8003":
mStatus = "Account credit allowance exceeded";
break;
case "8004":
mStatus = "Access denied due to access rules";
break;
case "8005":
mStatus = "Access denied, account suspended";
break;
case "9001":
mStatus = "Internal server error";
break;
default:
mStatus = (string)node.Value;
break;
}
}
}
}
Related
Creating a magic 8 ball program c#
I need help with a homework I have in school. These are the requirements from my teacher. Program requirements: Accept user input of a question. Output a result based upon a real "magic 8-ball" (do not add any of your own) use a switch statement Create a Method with the following signature: public static string responses () All user input and output should be done in your main method. This is my code and I have a problem with returning the value and Visual Studio highlights the command break and reports an CS0162 Unreachable code detected. using System; public class Magic8Ball { public static void Main(string[] args) { Console.WriteLine("Ask you question to the Magic 8 Ball: "); Console.ReadLine(); string response; response = responses(response); Console.WriteLine(response); } public static string responses(string response) { string affirmativeResponse1 = "It is certain."; string affirmativeResponse2 = "It is decidedly so."; string affirmativeResponse3 = "Without a doubt."; string affirmativeResponse4 = "Yes definitely."; string affirmativeResponse5 = "You may rely on it."; string affirmativeResponse6 = "As I see it, yes."; string affirmativeResponse7 = "Most likely."; string affirmativeResponse8 = "Outlook good."; string affirmativeResponse9 = "Yes."; string affirmativeResponse10 = "Signs point to yes."; string nonCommittalResponse1 = "Reply hazy, try again."; string nonCommittalResponse2 = "Ask again later."; string nonCommittalResponse3 = "Better not tell you now."; string nonCommittalResponse4 = "Cannot predict now."; string nonCommittalResponse5 = "Concentrate and ask again."; string negativeResponse1 = "Don't count on it."; string negativeResponse2 = "My reply is no."; string negativeResponse3 = "My sources say no."; string negativeResponse4 = "Outlook not so good."; string negativeResponse5 = "Very doubtful."; int numberOfResponse; Random var = new Random(); numberOfResponse = var.Next(20); switch (numberOfResponse) { case 0: response = affirmativeResponse1; return response; break; case 1: response = affirmativeResponse2; return response; break; case 2: response = affirmativeResponse3; return response; break; case 3: response = affirmativeResponse4; return response; break; case 4: response = affirmativeResponse5; return response; break; case 5: response = affirmativeResponse6; return response; break; case 6: response = affirmativeResponse7; return response; break; case 7: response = affirmativeResponse8; return response; break; case 8: response = affirmativeResponse9; return response; break; case 9: response = affirmativeResponse10; return response; break; case 10: response = nonCommittalResponse1; return response; break; case 11: response = nonCommittalResponse2; return response; break; case 12: response = nonCommittalResponse3; return response; break; case 13: response = nonCommittalResponse4; return response; break; case 14: response = nonCommittalResponse5; return response; break; case 15: response = negativeResponse1; return response; break; case 16: response = negativeResponse2; return response; break; case 17: response = negativeResponse3; return response; break; case 18: response = negativeResponse4; return response; break; case 19: response = negativeResponse5; return response; break; } } }
the "return" keyword pretty much ends the method so you don't really need to add the "break;" in this instance. Also you need to a default condition when using switch statements and lastly your string response needs to be set to the console.readline. { public static void Main(string[] args) { Console.WriteLine("Ask you question to the Magic 8 Ball: "); string response = Console.ReadLine(); response = Responses(response); Console.WriteLine(response); } public static string Responses(string response) { string affirmativeResponse1 = "It is certain."; string affirmativeResponse2 = "It is decidedly so."; string affirmativeResponse3 = "Without a doubt."; string affirmativeResponse4 = "Yes definitely."; string affirmativeResponse5 = "You may rely on it."; string affirmativeResponse6 = "As I see it, yes."; string affirmativeResponse7 = "Most likely."; string affirmativeResponse8 = "Outlook good."; string affirmativeResponse9 = "Yes."; string affirmativeResponse10 = "Signs point to yes."; string nonCommittalResponse1 = "Reply hazy, try again."; string nonCommittalResponse2 = "Ask again later."; string nonCommittalResponse3 = "Better not tell you now."; string nonCommittalResponse4 = "Cannot predict now."; string nonCommittalResponse5 = "Concentrate and ask again."; string negativeResponse1 = "Don't count on it."; string negativeResponse2 = "My reply is no."; string negativeResponse3 = "My sources say no."; string negativeResponse4 = "Outlook not so good."; string negativeResponse5 = "Very doubtful."; int numberOfResponse; Random var = new Random(); numberOfResponse = var.Next(20); switch (numberOfResponse) { case 0: response = affirmativeResponse1; return response; case 1: response = affirmativeResponse2; return response; case 2: response = affirmativeResponse3; return response; case 3: response = affirmativeResponse4; return response; case 4: response = affirmativeResponse5; return response; case 5: response = affirmativeResponse6; return response; case 6: response = affirmativeResponse7; return response; case 7: response = affirmativeResponse8; return response; case 8: response = affirmativeResponse9; return response; case 9: response = affirmativeResponse10; return response; case 10: response = nonCommittalResponse1; return response; case 11: response = nonCommittalResponse2; return response; case 12: response = nonCommittalResponse3; return response; case 13: response = nonCommittalResponse4; return response; case 14: response = nonCommittalResponse5; return response; case 15: response = negativeResponse1; return response; case 16: response = negativeResponse2; return response; case 17: response = negativeResponse3; return response; case 18: response = negativeResponse4; return response; case 19: response = negativeResponse5; return response; default: response = affirmativeResponse1; return response; } } } ```
When you return a value from a function, nothing after that return can be ran - you're leaving the function. Therefore the breaks will never be reached because there is always a return right before them. You also don't need to assign the return value to the response variable, you can just write return affirmativeResponseX;
This is because when you return, you exit the function. It will never reach the break because you return right before it. The fix is simple. Just remove the breaks.
Bad Request: Shopify pagination
I would like to ask about shopify pagination version 2020-01 First request query: URL: https://klevarange.myshopify.com/admin/api/2020-01/orders.json?fulfillment_status=unfulfilled&limit=250&financial_status=paid&created_at_min=2019-08-27T16:15:47-04:00 Return Header: "<https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info=eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzIxNzM2NTIsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjA5OjUyIiwiZGlyZWN0aW9uIjoibmV4dCJ9>; rel=\"next\"" 2nd Request Query: "https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info=eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzI1MzQxMDAsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjEwOjA3IiwiZGlyZWN0aW9uIjoibmV4dCJ9>; rel=\"next\"" Result: Bad Request What should I put in page_info? Do I need to include the rel=\"next\"" in the page_info? Thank you.
Remove > from your page_info variable var page_info = "eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzI1MzQxMDAsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjEwOjA3IiwiZGlyZWN0aW9uIjoibmV4dCJ9" and Make your request URL like below. https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info={page_info} Digging Deeper You need to iterate your while loop until there is no Link Parameter in the response header and this parameter is not a static value it is the address of last object you get and saying next will give you next 250 objects. you need to update your pageInfo parameter in every request with newly generated next reference ( pageInfo ) When you do not get this parameter that means there is no next or previous page . Have a look in this below code...( written in php ) How to create pagination in shopify rest api using php
You should use only this part: https://klevarange.myshopify.com/admin/api/2020-01/orders.json?limit=250&page_info=eyJmaW5hbmNpYWxfc3RhdHVzIjoicGFpZCIsImZ1bGZpbGxtZW50X3N0YXR1cyI6InVuZnVsZmlsbGVkIiwiY3JlYXRlZF9hdF9taW4iOiIyMDE5LTA4LTI3IDIwOjE1OjQ3IFVUQyIsImxhc3RfaWQiOjIxMDQ4NzI1MzQxMDAsImxhc3RfdmFsdWUiOiIyMDIwLTAyLTI3IDAwOjEwOjA3IiwiZGlyZWN0aW9uIjoibmV4dCJ9 i.e. without rel="next" In the 2nd and all next requests, you can only pass up to 3 query parameters: page_info limit fields So if you want to get results from the next page you need to extract page_info value from the first response headers. The idea is that you can move only forward or backwards while requesting the results and you can get the link (page_info token) to the next (or previous) page only after retrieving the current page results.
Maybe in the last 2 years, Shopify has made some modifications to their API, then I use GetNextPageFilter method. This is my approach. public async Task<IEnumerable<Product>> ProductsGetList(string shopUrl, string accessToken) { var products = new List<Product>(); var service = new ProductService(shopUrl, accessToken); var filter = GetFilters(shopUrl); var productList = await service.ListAsync(filter); if (productList != null && productList.Items.Any()) { products.AddRange(productList.Items); bool hasMorePages = productList.HasNextPage; if (hasMorePages) { do { var filterList = productList.GetNextPageFilter(filter.Limit, filter.Fields); productList = await service.ListAsync(filterList); if (productList != null && productList.Items.Any()) { products.AddRange(productList.Items); hasMorePages = productList.HasNextPage; } } while (hasMorePages); } } return products; } private ProductListFilter GetFilters(string url) { ProductListFilter filters = new ProductListFilter(); string queryString = new System.Uri(url).Query; var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString); foreach (var parameter in queryDictionary) { var key = (string)parameter; var value = queryDictionary.Get(key); switch (key) { case "published_status": filters.PublishedStatus = value; break; case "published_at_max": filters.PublishedAtMax = DateTimeOffset.Parse(value); break; case "published_at_min": filters.PublishedAtMin = DateTimeOffset.Parse(value); break; case "updated_at_max": filters.UpdatedAtMax = DateTimeOffset.Parse(value); break; case "updated_at_min": filters.UpdatedAtMin = DateTimeOffset.Parse(value); break; case "created_at_max": filters.CreatedAtMax = DateTimeOffset.Parse(value); break; case "presentment_currencies": filters.PresentmentCurrencies = value.Split(',').AsEnumerable(); break; case "created_at_min": filters.CreatedAtMin = DateTimeOffset.Parse(value); break; case "status": filters.Status = value; break; case "product_type": filters.ProductType = value; break; case "handle": filters.Handle = value; break; case "vendor": filters.Vendor = value; break; case "title": filters.Title = value; break; case "since_id": filters.SinceId = long.Parse(value); break; case "collection_id": filters.CollectionId = long.Parse(value); break; case "ids": filters.Ids = value.Split(',').AsEnumerable().Cast<long>(); break; case "limit": filters.Limit = int.Parse(value); break; } } return filters; } Where shopUrl is the entire URL (https://{apiKey}:{password}#{hostname}/admin/api/{version}/{resource}.json) and accessToken is the URL {password} atribute
Not able to redirect on server using AngulaJS and MVC C#
I'm writing this simple code in html:- <a id="{{L.ID}}" target="_blank" href="/Home/RedirectToMaterialView?MaterialTypeID={{L.MaterialTypeID}}&SearchListID={{L.SearchListID}}&Category={{L.Category}}" style="cursor:pointer">Open</a> Now this goes to my HomeController and works perfect in my local machine, where I redirect it to some other actionlink. c# controller actionresult is like this:- public ActionResult RedirectToMaterialView(string MaterialTypeID, string SearchListID, string Category) { if (!string.IsNullOrEmpty(SearchListID)) { dbundle.MaterialFetchID = Convert.ToInt32(SearchListID); dbundle.MaterialIndicator = Convert.ToInt32(MaterialTypeID); dbundle.MaterialFor = Convert.ToString(Category); string queryString = string.Empty; TempData["DBundle"] = dbundle; switch (dbundle.MaterialFor) { case "Class": switch (dbundle.MaterialIndicator) { case 1: TempData["ClassMaterialHeading"] = Constants.EBook; break; case 2: TempData["ClassMaterialHeading"] = Constants.Notes; break; default: TempData["ClassMaterialHeading"] = ""; break; } return RedirectToAction(Constants.ClassMaterial, new { id= dbundle.MaterialFetchID, MatFor =dbundle.MaterialFor}); case "Degree": switch (dbundle.MaterialIndicator) { case 1: TempData["DegreeMaterialHeading"] = Constants.EBook; break; case 2: TempData["DegreeMaterialHeading"] = Constants.Notes; break; default: TempData["DegreeMaterialHeading"] = ""; break; } return RedirectToAction(Constants.DegreeMaterial, new { id = dbundle.MaterialFetchID, MatFor = dbundle.MaterialFor }); default: return RedirectToAction(Constants.School); } } else return RedirectToAction(Constants.Degree); } But when I run this code on server. It's redirecting to a blank page. I don't know what's creating problem. Maybe I'm missing something in the link. But I can't figure out what's the problem on server which is not on my machine. Help Appreciated.
How does OAuth Work in mvc4 C#
I'm using Oauth to get users to register through Facebook etc. I got all the dlls. but how does it work ? This is a code i found on the internet but it doesn't work. Any ideas how it works?.. I'm lost :/ Thanks for reading this! using DotNetOpenAuth.Messaging; public ActionResult LogOn() { var openid = new OpenIdRelyingParty(); IAuthenticationResponse response = openid.GetResponse(); if (response != null) { switch (response.Status) { case AuthenticationStatus.Authenticated: FormsAuthentication.RedirectFromLoginPage( response.ClaimedIdentifier, false); break; case AuthenticationStatus.Canceled: ModelState.AddModelError("loginIdentifier", "Login was cancelled at the provider"); break; case AuthenticationStatus.Failed: ModelState.AddModelError("loginIdentifier", "Login failed using the provided OpenID identifier"); break; } } return View(); } [System.Web.Mvc.AcceptVerbs(HttpVerbs.Post)] public ActionResult LogOn(string loginIdentifier) { if (!Identifier.IsValid(loginIdentifier)) { ModelState.AddModelError("loginIdentifier", "The specified login identifier is invalid"); return View(); } else { var openid = new OpenIdRelyingParty(); IAuthenticationRequest request = openid.CreateRequest( Identifier.Parse(loginIdentifier)); // Require some additional data request.AddExtension(new ClaimsRequest { BirthDate = DemandLevel.NoRequest, Email = DemandLevel.Require, FullName = DemandLevel.Require }); return request.RedirectingResponse.AsActionResult(); } }
DotNetOpenId - Open Id get some data
I'm using OpenId on a new website and am trying to get some basic information about the user, see the code below. Why is the following allways null? var myData = response.GetExtension<ClaimsResponse>(); And the main code [System.Web.Mvc.AcceptVerbs(HttpVerbs.Get)] public ActionResult LogOn() { var openid = new OpenIdRelyingParty(); IAuthenticationResponse response = openid.GetResponse(); if (response != null) { switch (response.Status) { case AuthenticationStatus.Authenticated: FormsAuthentication.RedirectFromLoginPage( response.ClaimedIdentifier, false); var myData = response.GetExtension<ClaimsResponse>(); break; case AuthenticationStatus.Canceled: ModelState.AddModelError("loginIdentifier", "Login was cancelled at the provider"); break; case AuthenticationStatus.Failed: ModelState.AddModelError("loginIdentifier", "Login failed using the provided OpenID identifier"); break; } } return View("Register"); } [System.Web.Mvc.AcceptVerbs(HttpVerbs.Post)] public ActionResult LogOn(string loginIdentifier) { if (!Identifier.IsValid(loginIdentifier)) { ModelState.AddModelError("loginIdentifier", "The specified login identifier is invalid"); return View(); } else { var openid = new OpenIdRelyingParty(); IAuthenticationRequest request = openid.CreateRequest( Identifier.Parse(loginIdentifier)); // Require some additional data request.AddExtension(new ClaimsRequest { Email = DemandLevel.Request, FullName = DemandLevel.Request }); return request.RedirectingResponse.AsActionResult(); } }
http://www.dotnetopenauth.net/developers/help/the-axfetchassregtransform-behavior/