How can I read this json on windows phone 8? - json

I'm trying to read the following json in a windows phone app using newtonsoft.json
I can't read anything. the also looks pretty strange to me.
{"type": "Menu","menu":
[{"0":"antipasto","tipo_piatto":"antipasto","1":"porchetta","nome_piatto":"porchetta","2":"1","prezzo":"1"},
{"0":"primo","tipo_piatto":"primo","1":"matriciana","nome_piatto":"matriciana","2":"5","prezzo":"5"},
{"0":"secondo","tipo_piatto":"secondo","1":"salsicce","nome_piatto":"salsicce","2":"4","prezzo":"4"},
{"0":"contorno","tipo_piatto":"contorno","1":"patate","nome_piatto":"patate","2":"2","prezzo":"2"},
{"0":"dolce","tipo_piatto":"dolce","1":"gelato","nome_piatto":"gelato","2":"6","prezzo":"6"}]}
this is my c# code for now
public class piatto_menu_giorno
{
public string tipo_piatto { get; set; }
public string nome_piatto { get; set; }
public string prezzo { get; set; }
}
public menu()
{
InitializeComponent();
WebClient webClient = new WebClient();
Uri uri = new Uri("http://www.stepapp.it/areacli/extDevice/getMenuOdierno_101.php");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(fine_lettura_web);
webClient.OpenReadAsync(uri);
}
private void fine_lettura_web(object sender, OpenReadCompletedEventArgs e)
{
DataContractJsonSerializer json = null;
json = new DataContractJsonSerializer(typeof(ObservableCollection<piatto_menu_giorno>));
ObservableCollection<piatto_menu_giorno> menu = json.ReadObject(e.Result) as ObservableCollection<piatto_menu_giorno>;
if(menu==null)
menu_giorno.Text = "null";
else
foreach (piatto_menu_giorno piatto in menu)
{
menu_giorno.Text += piatto.nome_piatto + "\n";
}
}
sorry for all the variables name that are in italian

I am writing a code for you it will help you to deserialize the object from json to yourClassCustomObject.
private async Task<List<piatto_menu_giorno>> MyDeserializerFunAsync()
{
List<piatto_menu_giorno> book = new List<piatto_menu_giorno>();
try
{
//I am taking my url from appsettings. myKey is my appsetting key. You can write direct your url.
string url = (string)appSettings["mykey"];
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
var factory = new TaskFactory();
var task = factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse, null);
var response = await task;
Stream responseStream = response.GetResponseStream();
string data;
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<piatto_menu_giorno>));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
book = (List<piatto_menu_giorno>)json.ReadObject(ms);
return book;
}
}
Above code is working in my wp8 application it is faster you can try, it will help you. I am performing asynchronous operation but you can create your simple method with piatto_menu_giorno return type.

Related

ClosedXML - Method of returning workbook via API in latest version no longer functions

returning a workbook via an httpresponse in a get call, the method used for an older version of ClosedXML, now returns an empty workbook - workbook tabs are created and correctly named, but are empty.
Sample code - trimmed down for basic response
public HttpResponseMessage Get([FromUri]ControlReportsView model)
{
string client = "EU";
ClosedXML.Excel.XLWorkbook workbook = CreateWorkbook(model, client);
MemoryStream stream = new MemoryStream();
workbook.SaveAs(stream);
stream.Position = 0;
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition.FileName = string.Format("{0}_{1:yyyyMMdd hhmmtt} to {2:yyyyMMdd hhmmtt}.xlsx", model.Type.ToString(), model.StartDate, model.EndDate);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
Private = true,
MaxAge = TimeSpan.FromSeconds(300)
};
return response;
}
private static ClosedXML.Excel.XLWorkbook CreateWorkbook(ControlReportsView model, string client)
{
using (var workbook = new ClosedXML.Excel.XLWorkbook())
{
CreateTestTab(model, client, workbook);
return workbook;
}
}
private static void CreateTestTab(ControlReportsView model, string client, XLWorkbook workbook)
{
var worksheet = workbook.Worksheets.Add("Sample Sheet");
var firstRow = worksheet.FirstRow();
firstRow.Cell("A").Value = "Hello World!";
}
public class ControlReportsView
{
public enum ControlReportType
{
[Description("R")]
Inbound,
[Description("S")]
Outbound
}
public ControlReportType Type { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
I suspect there's a more elegant tool to do the response now, of which I'm unaware.
I have another file I'm returning successfully via another method, but I'm loath to make this big a change to the set up of the current file:
var stream = new MemoryStream();
workbook.SaveAs(stream);
byte[] fileArray = stream.ToArray();
//build file name
DashObject FarmInfo = (DashObject)MySession.Info;
string ProjName = FarmInfo.ProjectName;
string datemade = DateTime.Now.ToString("yyyyMMdd-HHmmss");
string docName = String.Format("Subscribers_{0}_{1}.xlsx", ProjName, datemade);
Response.ContentType = "application/octet-stream";
string attachVal = "attachment; filename=" + docName;
Response.AppendHeader("Content-Disposition", attachVal);
Response.BinaryWrite(fileArray);
Response.End();
Wow, that was weird.
The data was never making it into the worksheets, even tho they were getting created.
Removing the Using clause somehow sorted it:
private static ClosedXML.Excel.XLWorkbook CreateWorkbook(ControlReportsView model, string client)
{
ClosedXML.Excel.XLWorkbook workbook = new ClosedXML.Excel.XLWorkbook();
CreateTestTab(model, client, workbook);
return workbook;
}
I suspect somehow the worksheet in the using didn't pass back and forth properly for some reason - can anyone confirm?

How to send data from libgdx project to web?

I would like to work on moving the json data from libgdx to my web server, but I am not sure how to do it. The method below was created by referring to libgdx's documentation.
private void httpPostJson(){
final Json json = new Json();
final String requestJson = json.toJson(requestObject);
Net.HttpRequest request = new Net.HttpRequest("POST");
final String url = "http://localhost:8080/data";
request.setUrl(url);
request.setContent(requestJson);
request.setHeader("Content-Type", "application/json");
Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String responseJson = httpResponse.getResultAsString();
Gson gson = new Gson();
data = gson.fromJson(responseJson, Person.class);
//'Person' is just sample class. data is class Person's object.
data.StoreData("",1);//successed to receive json data from web server.
//StoreData is just getter method.
}
#Override
public void failed(Throwable t) {
Gdx.app.log("failed!");
}
#Override
public void cancelled() {
Gdx.app.log("cancelled!");
}
});
}
It is possible to receive data transmitted from a web server.
But, this method can't send data to web server.
Can you tell me how to move data from libgdx project to web server?
This is the data transmitted to the web server:
final String requestJson = json.toJson(requestObject);
We are using the following Code (as you have more control over the request as opposed to using gdx.net), works like a charm, just don't execute on the main thread - body is your JSON as String
URL url = new URL(<your url>);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type",
"application/json; charset=utf-8");
if (body != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
os, "UTF-8"));
writer.write(body);
writer.close();
os.close();
}
conn.connect();
String s = stringFromStream(conn.getInputStream(), 4096);
Method stringFromStream:
public static String stringFromStream(final InputStream is,
final int bufferSize) {
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(is, "UTF-8");
try {
for (; ; ) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
} finally {
in.close();
}
} catch (Exception ex) {
}
return out.toString();
}

Posting JSON to WebAPI2 function

I have the following code in an MVC app controller to send some data to be stored in an Archive table using EF6 via a WebAPI2 call.
I'm getting a "Cannot send a content-body with this verb-type" even though I'm setting to POST and the api call is defined to accept only POST.
What in the world am I doing wrong and how can I fix it?
ArchiveUploadModel.ArchiveUpload obj = new ArchiveUploadModel.ArchiveUpload();
obj.LT = LT;
obj.PID = PID.ToString();
obj.Title = "Ex Review";
obj.HTML = message.Body; // the HTML is a rendered HTML email message
if (!string.IsNullOrEmpty(obj.HTML))
{
HttpWebRequest req = HttpWebRequest.Create("http://example.com/MyApp/api/UploadToArchive") as HttpWebRequest;
request.ContentType = "application/json";
request.Method = "POST";
string json = JsonConvert.SerializeObject(obj);
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
}
using (HttpWebResponse webresponse = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(webresponse.GetResponseStream()))
{
string response = reader.ReadToEnd();
}
}
This is the code for my WebAPI call:
[HttpPost]
[Route("api/UploadToArchive")]
[EnableCors("http://example.com", // Origin
"Accept, Origin, Content-Type, Options", // Request headers
"POST", // HTTP methods
PreflightMaxAge = 600 // Preflight cache duration
)]
public IHttpActionResult UploadToArchive(ArchiveUpload upload)
{
string HTML = upload.HTML;
string Title = upload.Title;
string LT = upload.LT;
string lt = getLT(upload.PID); // essentially secure checking to see if it matches passed LT.
if (lt == LT)
{
// Upload the file to the archive using the ArchiveRepository's UpdateArchive() function:
_ArchiveRepository.UpdateArchive(HTML, System.Web.HttpUtility.HtmlDecode(Title), "", upload.PID);
return Ok(PID);
}
else
{
return BadRequest("Invalid LT");
}
}
ArchiveUpload model definition in both applications:
public class ArchiveUpload
{
public string LT { get; set; }
public string PID { get; set; }
public string Title { get; set; }
public string HTML { get; set; }
}
Better try to use the Microsoft Http Client Libraries. You can install it from nuget and here you find examples calling Web API using different HTTP verbs

How to perform POST operation on Windows Phone 8.1

I am struggling to successfully implement a POST operation within Windows Phone 8.1.
PostMessage method executes without any exceptions being caught.
However, the POST method within MessagesController never gets invoked.
How do I perform a POST for Windows Phone 8.1?
The code is below:
internal async Task PostMessage(string text)
{
Globals.MemberId = 1;
int memberId = 2;
// server to POST to
string url = #"http://localhost:17634/api/messages";
try
{
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
//create some json string
var message = new Message() { FromId = Globals.MemberId, ToId = memberId, Content = text, Timestamp = DateTime.Now };
var json = string.Format("{0}{1}", "action=", JsonConvert.SerializeObject(message));
// convert json to byte array
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
// Write the bytes to the stream
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
public class MessagesController : ApiController
{
public HttpResponseMessage Post(Message message)
{
throw new NotImplementedException();
}
}
public class Message
{
public int MessageId { get; set; }
public int FromId { get; set; }
public int ToId { get; set; }
public DateTime Timestamp { get; set; }
public string Content { get; set; }
}
The following link resolved my issue.
The updated client is as follows:
using (var client = new System.Net.Http.HttpClient())
{
// New code:
client.BaseAddress = new Uri(Globals.URL_PREFIX);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var message = new Message() { MessageId = 0, FromId = Globals.MemberId, ToId = memberId, Content = text, Timestamp = DateTime.Now };
var json_object = JsonConvert.SerializeObject(message);
var response = await client.PostAsync("api/messages", new StringContent(json_object.ToString(), Encoding.UTF8, "application/json"));
Debug.Assert(response.StatusCode == System.Net.HttpStatusCode.Accepted);
}
This works fine for me. The function accepts an payload of type T. The server accepts a JSON object and returns a JSON response.
public async static Task SendRequestPacket<T>(object payload)
{
Uri theUri = new Uri("the_uri");
//Create an Http client and set the headers we want
HttpClient aClient = new HttpClient();
aClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
aClient.DefaultRequestHeaders.Host = theUri.Host;
//Create a Json Serializer for our type
DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(T));
// use the serializer to write the object to a MemoryStream
MemoryStream ms = new MemoryStream();
jsonSer.WriteObject(ms, payload);
ms.Position = 0;
//use a Stream reader to construct the StringContent (Json)
StreamReader sr = new StreamReader(ms);
StringContent theContent = new StringContent(sr.ReadToEnd(), Encoding.UTF8, "application/json");
//Post the data
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);
if (aResponse.IsSuccessStatusCode)
{
string content = await aResponse.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(content);
}
else
{
// show the response status code
}
}
Just dont use HttpWebRequest if you are not forced to in any way.
This example is using HttpClient() and it is good to always have the client created once and not every time you make a request.
So in your class add:
private static HttpClient _client;
public static Uri ServerBaseUri
{
get { return new Uri("http://localhost:17634/api"); }
}
public ClassConstructor()
{
_client = new HttpClient();
}
internal async Task<ResponseType> PostMessage(string text)
{
Globals.MemberId = 1;
int memberId = 2;
try
{
var js = "{ JSON_OBJECT }";
var json = new StringContent(js);
json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await Client.PostAsync(new Uri(ServerBaseUri, "/messages"), json);
var reply = await response.Content.ReadAsStringAsync();
} catch (Exception)
{
return null;
}
}
More on HttpClient.

WebClient event firing order

I'm new to WP7 app development and I'm having trouble passing parameters to an API on a website.
It's my understanding that the onNavigatedTo() is fired first when a page is open on the WP7, however when I try to grab the parameters the webClient_DownloadStringCompleted() is fired first.
public partial class Ranks : PhoneApplicationPage
{
private WebClient webClient;
private string pageType;
private string pagePosition;
public Ranks()
{
InitializeComponent();
this.webClient = new WebClient();
string header_auth = "application/json";
this.webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
this.webClient.Headers[HttpRequestHeader.Authorization] = header_auth;
Uri serviceUri = new Uri(#"http://www.example.com/api/API.php?type=" + pageType + "&position=" + pagePosition);
this.webClient.DownloadStringAsync(serviceUri);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string type, position;
if (NavigationContext.QueryString.TryGetValue("type", out type))
{
pageType = type;
}
if (NavigationContext.QueryString.TryGetValue("pos", out position))
{
pagePosition = position;
}
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string myJsonString = e.Result;
List<PlayerDetails> dataSource = new List<PlayerDetails>();
//load into memory stream
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(myJsonString)))
{
//parse into jsonser
var ser = new DataContractJsonSerializer(typeof(PlayerDetails[]));
PlayerDetails[] obj = (PlayerDetails[])ser.ReadObject(ms);
foreach (PlayerDetails plyr in obj)
{
dataSource.Add(plyr);
}
playerList.ItemsSource = dataSource;
}
}
Whenever the URI string is built it's missing the parameters 'pageType' and 'pagePosition'
Any help would be greatly appreciated!
The class constructor will always get called before OnNavigatedTo. you should move that code from the constructor, and into OnNavigatedTo (or Loaded).
I'm guessing that you have that code in the constructor because you only want it to happen once per page load (i.e. not when the user navigates Back onto the page). If that's the case, you can check the NavigationMode.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (e.NavigationMode == NavigationMode.New)
{
string type, position;
if (NavigationContext.QueryString.TryGetValue("type", out type))
{
pageType = type;
}
if (NavigationContext.QueryString.TryGetValue("pos", out position))
{
pagePosition = position;
}
this.webClient = new WebClient();
string header_auth = "application/json";
this.webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
this.webClient.Headers[HttpRequestHeader.Authorization] = header_auth;
Uri serviceUri = new Uri(#"http://www.example.com/api/API.php?type=" + pageType + "&position=" + pagePosition);
this.webClient.DownloadStringAsync(serviceUri);
}
}