Subscribe to Topics using AWS-IOT with .NET - aws-sdk

I have spent many hours looking for a way to subscribe to a topic using the AWSSDK.IoT library. I can publish easily enough, but can't figure out the subscription part.
I am using the AmazonIotDataClient (AWSSDK.IotData), but have also tried the AmazonIotClient (AWSSDK.Iot). I am not having any luck with either. Just doesn't seem to be in the .NET SDK?
Code to publish:
public void SendMessage(string topic, PropertyCollection collection)
{
var json = collection.ToJson();
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var request = new PublishRequest
{
Topic = topic,
Payload = stream
};
_client.Publish(request);
}
}

Related

Update text block from downloaded text file = RPC_E_WRONG_THREAD WP8.1

I am learning Windows Phone 8.1 development, I have probably done something utterly incorrectly programming wise
The need: I want to download a text file from the web using HttpClient() and display it in the TextBlock1
From variety of tutorials I have found the following:
public async void DownloadDataAsync()
{
string data = "some link to Textfile.txt";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(data);
HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();
UpdateTextBlock1(result);
}
Then the other functions.
public void UpdateTextBlock1(string result)
{
TextBlock1.Text = result;
}
private void BtnDownloadData_Click(object sender, RoutedEventArgs e)
{
Task t = new Task(DownloadDataAsync);
t.Start();
}
The code starts well enough - on button pressed, I receive RPC_E_WRONG_THREAD.
Is it that I'm trying to call the method when all threads haven't finished? How can I code that efficently so the TextBlock1 is updated with txt data?
Thanks for understanding, baby steps here in programming, and I couldn't find a relevant answer over google. (Maybe I don't yet know how to ask?)
You need to update the textblock on the UI thread like so:
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
TextBlock1.Text = result;
});
There are many posts on this subject.

OCR on Windows Phone 8 WP8

I'm new to the world of programming, and am trying to develop an app that uses OCR.
I want the app to convert a singular receipt into text (nothing too complex).
However my problem is that i'm finding a lack of information for OCR on WP8, and how to implement it.
I would have though that it's a built in function of WP and that information would be easily accessible as to how to implement it.
Anyone know where I could look, or a simple example snippet of code I could use?
Not wanting a subscription based service.
Microsoft recently released the OCR Library for Windows Runtime. Jerry Nixon has posted a video guiding you though it, and there is also an msdn article.
Jerry Nixon's Blog
MSDN
You can try using the same OCR service that the Bing Lens uses. If you haven't tried it: open camera, change lens to bing lens and try it out
The service endpoint is http://ocrrest.bingvision.net/V1. It also gives you information about the location of the detected text with their bounding boxes
Probably some fiddler analysis will help you to send your image in a similar fashion.
I have a little snippet below which expects the image as byte array
public static readonly string ocrServiceUrl = "http://ocrrest.bingvision.net/V1"; // was: "platform.bing.com/ocr/V1";
public static readonly string ocrLanguage = "en";
public static async Task<JsonObject> MakeOcrJSON(byte[] image)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/Recognize/{1}", ocrServiceUrl, ocrLanguage));
request.Method = "POST";
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(image, 0, image.Length);
}
try
{
using (HttpWebResponse response = (HttpWebResponse) (await request.GetResponseAsync()))
{
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
var json = JsonObject.Parse(responseStream.ReadToEnd());
return json;
}
}
}
catch (WebException we)
{
using (Stream responseStream = we.Response.GetResponseStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OcrResponse));
OcrResponse ocrResponse = (OcrResponse)serializer.ReadObject(responseStream);
string ErrorMessage = "Unknown Error";
if (ocrResponse.OcrFault.HasValue)
{
ErrorMessage = string.Format(
"HTTP status code: {0} Message: {1}",
ocrResponse.OcrFault.Value.HttpStatusCode,
ocrResponse.OcrFault.Value.Message);
}
throw new Exception(ErrorMessage);
}
}
}

Returning and displaying a JSON Object which is an associate array in a Windows 8 App

I am using a online tutorial to lean how to create a web service, generate a JSON object, send it back to my Win 8 App and display it. The web service is working however I am struggling to return a value to the APP. My code in the app is:
WinJS.xhr({
url: 'http://localhost/filmgloss/web-service.php?termID=1&format=JSON'
})
.done(
function complete(result) {
// terms is the key of the object
for (var terms in result) {
for (var term in terms) {
if (result.hasOwnProperty(term)) {
//here you have to acess to
var termName = result[term].termName;
var def = result[term].definition;
}
//Show Terms
testDef.innerText = definition;
}
}
},
And he code in my web service is:
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('terms'=>$terms));
}else...
The JSON output itself looks like:
{"terms":[{"term":{ "termName":"Focus","definition":"A Focus..."}}]}
I am using a for..in but whilst I can look inside terms' I can't work out how to look interm`
I usually build my own data structure that represents the JSON structure.
In your case it would be something like this:
public class TermsList
{
public List<Term> terms { get; set; }
}
public class Term
{
public string termName { get; set }
public definition termName { get; set }
...
}
Then you can just deserialize your string into your object. There are different ways to do this. I would use Json.Net.
Here is one way:
Parse JSON in C#
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms); // <== Your missing line
return obj;
}
}
If you wanna keep it dynamic, that should work too:
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
I have managed to resolve my issue with the help of a developer friend. My problem was that I had not realised that the result of WinHS.xhr was not already a JSON Array. Although my web-service outputs a JSON Array when it is consumed through WinHS.xhr it appears to be returned as an XMLHttpRequest object.
The solution was therefore to process the result using:
JSON.parse(result.responseText)
I could then use a For...In loop as expected:
for (terms in responseTerms) {
//terms will find key "terms"
var termName = responseTerms.terms[0].term.termName;
var termdefinition = responseTerms.terms[0].term.definition;
testTerm.innerText = termName;
testDef.innerText = termdefinition;
}
Thanks for everyone that commented, hopefully this may help others in the future if they're starting out with Win 8 app development.

Can RestSharp send a List<string> in a POST request?

I am trying to get RestSharp to work with a restful service that I have. Everything seems to be working fine, except when my object being passed via POST contains a list (in this particular case a list of string).
My object:
public class TestObj
{
public string Name{get;set;}
public List<string> Children{get;set;}
}
When this gets sent to the server the Children property gets sent as a string with the contents System.Collections.Generic.List`1[System.String].
This is how I am sending the object:
var client = new RestClient();
var request = new RestRequest("http://localhost", Method.PUT);
var test = new TestObj {Name = "Fred", Children = new List<string> {"Arthur", "Betty"}};
request.AddObject(test);
client.Execute<TestObj>(request);
Am I doing something wrong, or is this a bug in RestSharp? (If it makes a difference, I am using JSON, not XML.)
It depends on what server you're hitting, but if you're hitting an ASP.NET Web API controller (and probably other server-side technologies), it'll work if you add each item in the collection in a loop:
foreach (var child in test.Children)
request.AddParameter("children", x));
Use AddJsonBody
var client = new RestClient();
var request = new RestRequest("http://localhost", Method.PUT);
request.AddJsonBody(new TestObj {
Name = "Fred",
Children = new List<string> {"Arthur", "Betty"}
});
client.Execute(request);
Api Side
[AcceptVerbs("PUT")]
string Portefeuille(TestObj obj)
{
return String.Format("Sup' {0}, you have {1} nice children",
obj.Name, obj.Children.Count());
}
I had a similar problem with a list of Guids. My post would work but the list would never have the correct data. I hacked it abit and used the json.net to serialize the object
Issue I had on another stackoverflow post
I know this isn't perfect but does the trick

Transfer JSON from Server to Client via WCF RIA Service

I am complete newbie to Silverlight and the WCF platform. I want to get some data from a server using a Silverlight client. The solution has a WCF RIA service class library for reading the data and serializing it into a JSON string, but I can't figure out how to create the request for the data, run the server method and return the JSON string for Deserialization at the client side.
I have spent hours searching and no reasonable solution. Till now I have done this:
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "data/{id}")]
public string getLogs(string server)
{
EventLog[] remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName);
ObservableCollection<string> logs = new ObservableCollection<string>();
for (int i = 0; i < remoteEventLogs.Length; i++)
{
logs.Add(remoteEventLogs[i].Log);
}
return serializer(logs); //helper function using DataContractJsonSerializer
}
But I can't wrap my head around what is going on. Any help please!
If you are using RIA Services, you just need to do this:
[Invoke]
public string getLogs(string server)
{
...
return serializer(logs);
}
And now you can call the getLogs from the Silverlight. But you can too use:
[Invoke]
public IEnumerable<string> getLogs(string server)
{
...
return logs;
}
this way, you return the list without having to serialize it to json.