Read DynamicJsonArray with razor (mvc4 Umbraco) - json

I'm reading Json from https://demoapi.thismoment.com/v4.1/api/content
Reading it as stream:
Stream stream = wc.OpenRead(url);
using (StreamReader reader = new StreamReader(stream))
{
String request = reader.ReadToEnd();
var requestJson = #Json.Decode(request);
and getting list of results
var resultsList = new List<dynamic>(requestJson.results);
When trying to read next level
var resultsList = new List<dynamic>(requestJson.results.media);
I'm getting this error: System.ArgumentNullException: Value cannot be null.
When I iterate through the list
foreach (var item in resultsList)
{
<a>#item.media</a>
}
each media item is System.Web.Helpers.DynamicJsonArray.
I need to read this array, so I can get url and size of each image.
The above json url is public.
I'm doing it in Umbraco 7, which uses razor code (aps mvc 4).

You can use following method to do it:
private static List<T> GetcollectionFromJason<T>(string jasonUrl) where T : new()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(jasonUrl);
List<T> retCollection = new List<T>();
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string jsonString = reader.ReadToEnd();
JavaScriptSerializer serializer = new JavaScriptSerializer();
retCollection = serializer.Deserialize<List<T>>(jsonString);
}
}
}
catch (WebException exp)
{
WebResponse errorResponse = exp.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
if (responseStream != null)
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
}
}
}
return retCollection;
}
And to call it you can have this:
List<YourModel> technicalIssues = GetcollectionFromJason<YourModel>(YourJsonUrl);

Related

Java save json byte array image to particular location

I have one application that posts json data like below
{
"image": "data:image/png;base64,eAvQPaQEJCABCUjg/wNeEta73J3yXwAAAABJRU5ErkJggg==................"
}
It posts image(png or jpg) base64 byte array in the "image" key.
I want to save that image under the name "datetime.png" into my specified location.
For this I am using the code below:
#POST
#Consumes("application/x-www-form-urlencoded")
#Path("/getImage")
public Response GetImage(String json) {
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
String currentTime = sdf.format(dt);
JSONObject returnJson = new JSONObject();
try {
JSONObject innerJsonObj = new JSONObject(json);
String imageCode=innerJsonObj.getString("image");
String base64Image = imageCode.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
FileOutputStream fos = new FileOutputStream("D:\\image\\" + currentTime + ".png");
try {
fos.write(imageBytes);
} finally {
fos.close();
}
returnJson.put("success", true);
} catch (Exception e) {
JSONObject errorJson = new JSONObject();
errorJson.put("success", false);
return Response.ok(errorJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
But it gives me the following Error
java.io.FileNotFoundException: D:\image\2016-07-15 17:04:34.png (The
filename, directory name, or volume label syntax is incorrect)

Indexing in Elasticsearch

I am having problems indexing in elasticsearch. I have a function which creates an index and another one that creates a type mapping for a json I will be indexing. Both of these work fine but when I try calling the function to index something, it gives me a WebException saying that the remote server returned an error: (503) Server Unavailable. Any help will be greatly appreciated! Thanks!
This is my code:
public static void Main(string[] args)
{
string endpoint = "http://localhost:9200";
string index = "logs";
string type = "activity-log";
createIndex(endpoint, index);
createMapping(endpoint, index, type);
indexEvent(endpoint, index, type);
}
public static void createIndex(string endpoint, string index)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/", endpoint, index));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use POST method when creating an index
string json = "{\"settings\":{\"number_of_shards\":3,\"number_of_replicas\":2}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
public static void createMapping(string endpoint, string index, string type)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/{2}/_mapping", endpoint, index, type));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use POST method when creating an index
string json = "{\"activitylogevent\":{\"properties\":{\"id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"parentId\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"event\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
public static void indexEvent(string endpoint, string index, string type)
{
//build the request URL
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/{2}/", endpoint, index, type);
request.ContentType = "application/json"; //set content type of json
request.Method = "POST"; //use POST method when indexing a record without specifying id, and PUT when you specify an id
string jsonEvent = "{\"id\":\"123546789\",\"parentId\":\"abc123\",\"event\":\"CloseAccount\"}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
Console.WriteLine("after get response");
Console.ReadLine();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
I was doing something wrong in my createIndex function but here is my working function incase anyone finds it helpful:
public static void createIndex(string endpoint, string index)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/", endpoint, index));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use PUT method when creating an index
string json = "{\"settings\":{\"activity-log-events\":{\"number_of_shards\":3,\"number_of_replicas\":2}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
You have at least one error in your indexEvent() function. You are setting the string jsonEvent but then using an undefined string json when setting up byteData:
string jsonEvent = "{\"id\":\"123546789\",\"parentId\":\"abc123\",\"event\":\"CloseAccount\"}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
You'll note that you are doing this correctly in the other two functions, using the string json in both places. From createIndex:
string json = "{\"settings\":{\"number_of_shards\":3,\"number_of_replicas\":2}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
and from createMapping:
string json = "{\"activitylogevent\":{\"properties\":{\"id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"parentId\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"event\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
There may be other things wrong in the code but that's definitely not going to work.
I made a some changes to my createIndex function and it worked. I posted the changes above.

Common class for HttpWebRequests - WP8

For making the http calls I use the functions
private void DoneClicked(object sender, RoutedEventArgs e)
{
string emailText = emailTBox.Text;
string oldPass = oldPasswordPBox.Password;
string newPass = newPasswordPBox.Password;
if (emailText == "" || oldPass == "" || newPass == "")
{
PassDiaTB1.Text = "Oops..";
PassDiaTB2.Text = "Some field is empty";
PassiveDialogs.Visibility = System.Windows.Visibility.Visible;
}
else
{
var data = new { user = new { email = emailText, old_password = oldPass, new_password = newPass } };
jsonStringChild = JsonConvert.SerializeObject(data, Formatting.Indented);
Debug.WriteLine(jsonStringChild);
string uri = CycleManager.HTTP_URI + "change-password";
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = CycleManager.HTTP_PUT;
request.ContentType = "application/json";
request.Accept = "application/json";
bool IsNetWork = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (!IsNetWork)
{
PassDiaTB1.Text = "Oops..";
PassDiaTB2.Text = "Check your internet connectivity";
PassiveDialogs.Visibility = System.Windows.Visibility.Visible;
}
else
{
request.BeginGetRequestStream(new AsyncCallback(PostCallBack), request);
}
}
}
void PostCallBack(IAsyncResult result)
{
// End the stream request operation
HttpWebRequest request = result.AsyncState as HttpWebRequest;
Stream postStream = request.EndGetRequestStream(result);
byte[] byteArray = Encoding.UTF8.GetBytes(jsonStringChild);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseStreamCallBack), request);
}
void GetResponseStreamCallBack(IAsyncResult callBackResult)
{
try
{
HttpWebRequest request = callBackResult.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callBackResult);
statusCode = (int)response.StatusCode;
if (statusCode == 200)
{
string result = "";
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
result = httpWebStreamReader.ReadToEnd();
}
string json = result;
Dictionary<string, string> token = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
string email = token["email"];
string auth_token = token["auth_token"];
CycleManager cycMan = CycleManager.Instance;
cycMan.AuthToken = auth_token;
Dispatcher.BeginInvoke(ShowPassiveDialog);
}
}
catch (WebException e)
{
if (e.Response != null)
{
HttpWebResponse aResp = e.Response as HttpWebResponse;
if (aResp != null)
{
statusCode = (int)aResp.StatusCode;
}
if (statusCode == 401)
{
string result = "";
using (StreamReader httpWebStreamReader = new StreamReader(aResp.GetResponseStream()))
{
result = httpWebStreamReader.ReadToEnd();
}
string json = result;
var definition = new { message = "" };
var parsedStrings = JsonConvert.DeserializeAnonymousType(json, definition);
message = parsedStrings.message;
Dispatcher.BeginInvoke(ShowPassiveDialog);
}
if (statusCode == 500)
{
string result = "";
using (StreamReader httpWebStreamReader = new StreamReader(aResp.GetResponseStream()))
{
result = httpWebStreamReader.ReadToEnd();
}
string json = result;
var definition = new { message = "" };
var parsedStrings = JsonConvert.DeserializeAnonymousType(json, definition);
message = parsedStrings.message;
Dispatcher.BeginInvoke(ShowPassiveDialog);
}
}
}
}
The same three calls are made in several pages, changing the parameters and methods. I am trying to create a common class which can be called to make http calls. But these functions have differnt return types and I'm not able generalize all this??
Any help would be appreciated.
May this will guide you. I create a wrapper class for such kind of work, its help me a lot and reduce lots of code and effort.
public class CommanHttpRequest
{
private string ACCEPT="application/json";
private string ContentType ="application/json";
private string POST_METHOD="POST";
private string GET_METHOD="GET";
public string IsException { get; set; }
public HttpWebRequest GetHttpRequest(string url,string header1, string header2)
{
HttpWebRequest getRequest = HttpWebRequest.CreateHttp(url);
getRequest.Accept =this.ACCEPT;
getRequest.ContentType = this.ACCEPT;
getRequest.Headers["Header1"] = header1;
getRequest.Headers["Header2"] = header2;
getRequest.Method = this.POST_METHOD;
return getRequest ;
}
public void GetRequestResponse(Action<your type> callback, IAsyncResult asyncResult, string envelop)
{
try
{
UTF8Encoding encoding = new UTF8Encoding();
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
Stream body = request.EndGetRequestStream(asyncResult);
//write body if any
byte[] formBytes = encoding.GetBytes(envelop);
body.Write(formBytes, 0, formBytes.Length);
body.Close();
request.BeginGetResponse(result =>
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
string jsonString = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(your type));
var parseddata = dataContractJsonSerializer.ReadObject(memoryStream) as your type;
callback(parseddata );
}
}
}
catch (WebException ex)
{
IsException = ex.Message;
//I asume your type =List<abc>();
callback(new List<abc>());
}
}, request);
}
catch (Exception ex)
{
IsException = ex.Message;
callback(new List<abc>());
}
}
}
public class abc
{
public void TestRequest()
{
string url="some url";
CommanHttpRequest requestObj = new CommanHttpRequest();
HttpWebRequest testRequest = _requestObj.GetHttpRequest(url, password, email);
//if there some body in request
string envelope = "{\"requestType\":" + requestType + "}";
testRequest .BeginGetRequestStream(result =>
{
requestObj.GetRequestResponse(resultData =>
{
ProcessServiceResponse(resultData);
}, result, envelope);
}, testRequest );
}
public void ProcessServiceResponse(List<abc> abcdata)
{
//abcdata is your data
}
}

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.

Pass a jsonstring to the service and convert it to stream on the server side

i have this
{"invoices":{"POSWorkstationID":"POS7","POSClerkID":"admin","CustomerName":"Alice in Wonderland Tours","IsFreightOverwrite":true},"invoiceDetails":[{"ItemDescription":"Old World Lamppost","QuantityOrdered":"1","SalePriceRate":" $107.99","ExtPriceRate":"107.99","ItemType":"Stock","LineNum":1,"WarehouseCode":"Main"}]}
Now i want to pass this on my server using rest and convert it to stream. My service code is here. https://stackoverflow.com/questions/9594382/convert-json-to-stream-in-wcf
Please find some sample code to get your scenario working:
On my Server:
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public string CreateInvoice(Stream xmlStream)
{
byte[] buffer = new byte[WebOperationContext.Current.IncomingRequest.ContentLength];
int read = -1;
while (read != 0)
{
read = xmlStream.Read(buffer, 0, buffer.Length);
}
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string jsonobjectstring = enc.GetString(buffer);
JavaScriptSerializer json = new JavaScriptSerializer();
object jsonobject = json.DeserializeObject(jsonobjectstring);
return "Recieved the json text on server";
//MaintainInvoice(xmlStream, InvoiceMaintainance.CreateInvoice);
}
I have modified the server method logic so that i can test it. Once you get the stream on the server you can use your logic to return the invoice object as needed.
Now on client side to invoke the rest service i use the below code:
private string UseHttpWebApproachByteArray(string serviceUrl, string resourceUrl, string method, byte[] requestBody)
{
string responseMessage = null;
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/octet-stream";
request.Method = method;
}
if (method == "POST" && requestBody != null)
{
request.ContentLength = requestBody.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBody, 0, requestBody.Length);
}
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
return responseMessage;
}
private void Test()
{
string jsonText = "{\"invoices\":{\"POSWorkstationID\":\"POS7\",\"POSClerkID\":\"admin\",\"CustomerName\":\"Alice in Wonderland Tours\",\"IsFreightOverwrite\":true},\"invoiceDetails\":[{\"ItemDescription\":\"Old World Lamppost\",\"QuantityOrdered\":\"1\",\"SalePriceRate\":\" $107.99\",\"ExtPriceRate\":\"107.99\",\"ItemType\":\"Stock\",\"LineNum\":1,\"WarehouseCode\":\"Main\"}]}";
System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] jsonBytes = enc.GetBytes(jsonText);
UseHttpWebApproachByteArray(serviceBaseUrl, resourceUrl, method, jsonBytes);
}