Google vision connection to API without external google DLL - c#

How to connect to google cloud vision without using external dlls?

First, you will have to generate JSON request, simple example:
Request req = new Request();
req.addFeature("DOCUMENT_TEXT_DETECTION"); //Add here all the feature types
req.Image.content = Convert.ToBase64String(qq);//qq is a byte[]
Requests reqList = new Requests(req);
json = JsonConvert.SerializeObject(reqList);
Secondly, you need to post simple HTTP request:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://vision.googleapis.com/v1/images:annotate?key="PLACE_YOURKEY_HERE"");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
Memebers of the JSON classes (The methods should be implemented):
class Requests
{
public List<Request> Request { get; set; }
}
class Request
{
public Image1 Image { get; set; }
public List<Feature> Features { get; set; }
}
public class Feature
{
public string Type { get; set; }
}
public class Image1
{
public string content { get; set; }
}
Relevant to the topic links
Google Vision API Document_Text_Detection
Feature types
Google vision

Related

Problems with Getting Response on the deployed bot;

I've got some problems with getting REST API response that allows to get members of the group( GET {serviceUrl}/v3/conversations/{conversationId}/members). I'm debugging my bot in Bot Emulator, and it runs fine here
- that's what it shows in the Bot Simulator
- But that's how it shows on Azure.
The main problem is that i really can't recognize the problem.I know that the problem is in requesting because the getResponse method crash all programm when it is on server(but why this works in the bot emulator?).Here is the code(I'm using .NET CORE, Microsoft Bot Framework). P.S.{id} in Authorization is correct, and i get it from another request(but unlike the problem request that request works everywhere), the {url} is turnContext.Activity.ServiceUrl
HttpWebRequest webRequest23 = (HttpWebRequest)WebRequest.Create($"{url}/v3/conversations/{turnContext.Activity.Conversation.Id}/members");
await turnContext.SendActivityAsync($"{url}/v3/conversations/{turnContext.Activity.Conversation.Id}/members");
await turnContext.SendActivityAsync(turnContext.Activity.Conversation.Id);
webRequest23.ContentType = "application/json";
webRequest23.Headers["Authorization"] = $"Bearer {id}";
WebResponse response2 = webRequest23.GetResponse();//crash here
await turnContext.SendActivityAsync("3");
string smth25 = "";
using (StreamReader stream = new StreamReader(response2.GetResponseStream(), true))
{
smth25 = stream.ReadToEnd();
}
JArray jsonArray = JArray.Parse(smth25);
List<string> names = new List<string>();
foreach(var x in jsonArray)
{
var name = JObject.Parse(x.ToString())["name"].ToString();
names.Add("#" + name);
}
string s = "This group consists of - ";
foreach (var x in names){
s += "" + x + ",";
}
await turnContext.SendActivityAsync(s);
Here is how i get id:
string stringData = "grant_type=client_credentials&client_id=66b16ef5-d086-40b7-ae9c-2f50a1f028c6&client_secret=yRUYg4g.:ANuw3Y_01V=#.JkAv=#g3EE&scope=https%3A%2F%2Fapi.botframework.com%2F.default";
var data = Encoding.Default.GetBytes(stringData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token");
webRequest.Host = "login.microsoftonline.com";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
var newStream = webRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
WebResponse response = webRequest.GetResponse();
string line = string.Empty;
string smone = "";
using (StreamReader stream = new StreamReader(response.GetResponseStream(), true))
{
smone = stream.ReadToEnd();
}
var id = JObject.Parse(smone)["access_token"].ToString();
I don't understand exactly what your "turnContext.SendActivityAsync" lines are supposed to do, but it might be working in the bot emulator because the emulator doesn't require a proper authenticated session like Teams does. Anyway, something like this should actually help you:
First, define this class somewhere:
public class MicrosoftTeamUser
{
public string Id { get; set; }
public string ObjectId { get; set; }
public string GivenName { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string UserPrincipalName { get; set; }
public string TenantId { get; set; }
}
then use:
List<ChannelAccount> teamMembers = (await turnContext.TurnState.Get<IConnectorClient>().Conversations.GetConversationMembersAsync(
turnContext.Activity.GetChannelData<TeamsChannelData>().Team.Id).ConfigureAwait(false)).ToList();
List<MicrosoftTeamUser> teamsUsers = new List<MicrosoftTeamUser>();
foreach (var item in teamMembers)
{
var teamsUser = JsonConvert.DeserializeObject<MicrosoftTeamUser>(item.Properties.ToString());
teamsUser.Id = item.Id;
teamsUsers.Add(teamsUser);
}
Then you'll have the list of members in the teamMembers variable

Streaming Api consumption

I have an api http://oversea-download.hikvision.com/uploadfile/Leaflet/ISAPI/HIKVISION%20ISAPI_2.0-IPMD%20Service.pdf I want to receive which uses a HTTP get and wants connection keep-alive.
Once connected it sends XML responses which I want to deserialise. I've created a class to represent the data structure, but I'm not sure how to continually update a list or similar as and when the data is sent back, for example the response (from wireshark) looks like:
I'm not concerned with the parsing of data and updating the list, more how I can keep listening on a socket and see that its XML data and needs to be serialised.. without processing the stream into a buffer and looking for delimiters?
So far the code I had been unsuccessfully playing with looks like:
public static async Task NewTask()
{
var client = new RestClient("http://192.168.0.152:80/");
client.Authenticator = new HttpBasicAuthenticator("admin", "ThePassword");
client.Encoding = Encoding.UTF8;
var request = new RestRequest("ISAPI/Event/notification/alertStream", Method.GET);
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Content-Type", "application/xml");
IRestResponse<EventNotificationAlert> response2 = client.Execute<EventNotificationAlert>(request);
var name = response2.Data.eventType;
Console.WriteLine(name);
//var asyncHandle = client.ExecuteAsync<EventNotificationAlert>(request, response => {
// Console.WriteLine(response.Data.eventDescription);
//});
}
and the class:
public class EventNotificationAlert
{
public string version { get; set; }
public string ipAddress { get; set; }
public string portNo { get; set; }
public string protocol { get; set; }
public string macAddress { get; set; }
public string channelID { get; set; }
public string dateTime { get; set; }
public string activePostCount { get; set; }
public string eventType { get; set; }
public string eventState { get; set; }
public string eventDescription { get; set; }
}
disregard my comment, can't format it.. this kind of works.. but given I get boundary and content-type text I've got crude processing in...
var messageBuffer = string.Empty;
var request = WebRequest.Create("http://192.168.0.152:80/ISAPI/Event/notification/alertStream");
request.Credentials = new NetworkCredential("admin", "ThePassword");
request.BeginGetResponse(ar =>
{
var req = (WebRequest)ar.AsyncState;
// TODO: Add exception handling: EndGetResponse could throw
using (var response = req.EndGetResponse(ar))
using (var reader = new StreamReader(response.GetResponseStream()))
{
// This loop goes as long as the api is streaming
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line == xmlEndStr)
{
messageBuffer += line;
GotMessage(messageBuffer);
messageBuffer = string.Empty;
}
else if (line.StartsWith("<"))
{
messageBuffer += line;
}
}
}
}, request);
static void GotMessage(string msg)
{
var mySerializer = new XmlSerializer(typeof(EventNotificationAlert));
var stringReader = new StringReader(msg);
var eventAlert = (EventNotificationAlert)mySerializer.Deserialize(stringReader);
Console.WriteLine($"DateTime: {eventAlert.dateTime} Channel: {eventAlert.channelID} Type: {eventAlert.eventType} Description: {eventAlert.eventDescription}");
}
Happy to hear of better ways (as you can tell I'm not great with c#!)

Invalidcastexception JsonConvert.DeserializeObject

I am getting an invalid cast exception that the specified cast is not valid. On this line:
RootObject mountain = JsonConvert.DeserializeObject<RootObject>(json1);
From the documentation this should be fine? I can see the console output is fine?
Response: [{"Height_ft": 2999.0, "Height_m": 914.0, "ID": "c1",
"Latitude": 57.588007, "Longitude": -5.5233564, "Name": "Beinn Dearg",
"humidity": 0.81, "snowCover": 4.99, "temperature": 63.0}]
Spinner spinner = (Spinner)sender;
string urlmountain = "http://removed.azurewebsites.net/api/Mountains?name=";
JsonValue json1 = FetchMountain(urlmountain+string.Format("{0}", spinner.GetItemAtPosition(e.Position)));
//below.................................
RootObject mountain = JsonConvert.DeserializeObject<RootObject>(json1); //this line
string toast = mountain.Name;
Toast.MakeText(this, toast, ToastLength.Long).Show();
private JsonValue FetchMountain(string urlmountain)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(urlmountain));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = request.GetResponse())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc1 = JsonObject.Load(stream);
Console.Out.WriteLine("Response: {0}", jsonDoc1.ToString());
// Return the JSON document:
return jsonDoc1;
}
}
}
public class RootObject
{
public string ID { get; set; }
public double? Latitude { get; set; }
public double? Longitude { get; set; }
public string Name { get; set; }
public double? Height_m { get; set; }
public double? Height_ft { get; set; }
public double? temperature { get; set; }
public double? humidity { get; set; }
public double? snowCover { get; set; }
public override string ToString()
{
return Name;
}
}
The json data being returned is an array of objects, not a single object, as denoted by the opening and closing brackets []. You need to deserialize to an array or a list:
var mountains = JsonConvert.DeserializeObject<List<RootObject>>(json);
To access the first mountain from the deserialized payload, use .FirstOrDefault().
var mountain = mountains.FirstOrDefault();
if (mountain != null)
{
string toast = mountain.Name;
Toast.MakeText(this, toast, ToastLength.Long).Show();
}
It looks like your JSON is an Array of objects. You should be able to deserialize the array and get the first one like so:
RootObject mountain = JsonConvert.DeserializeObject<RootObject[]>(json1)[0];
One thing to note is that you are sort of mixing technologies here. JsonValue is from the System.Json namespace, whereas JsonConvert is from the Newtonsoft.Json (i.e. JSON.Net) namespace. If you wanted to go strictly with JSON.Net, you could do something like this:
private RootObject FetchMountain(string urlmountain)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(urlmountain));
request.ContentType = "application/json";
request.Method = "GET";
using (WebResponse response = request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader streamReader = new StreamReader(stream))
{
JsonSerializer serializer = new JsonSerializer();
RootObject[] mountains = (RootObject[])serializer.Deserialize(streamReader, typeof(RootObject[]));
return (mountains.Length > 0) ? mountains[0] : null;
}
}

Unsupported Media Type error when posting to Web API

Making a windows phone application and although I may easily pull from my Web Api I am having trouble posting to it. Whenever posting to the api I get the "Unsupported Media Type" error message and I'm not sure as to why it is happening considering the class I using as the base for my JSON post is the same as the one used in the api.
PostQuote (Post Method)
private async void PostQuote(object sender, RoutedEventArgs e)
{
Quotes postquote = new Quotes(){
QuoteId = currentcount,
QuoteText = Quote_Text.Text,
QuoteAuthor = Quote_Author.Text,
TopicId = 1019
};
string json = JsonConvert.SerializeObject(postquote);
if (Quote_Text.Text != "" && Quote_Author.Text != ""){
using (HttpClient hc = new HttpClient())
{
hc.BaseAddress = new Uri("http://rippahquotes.azurewebsites.net/api/QuotesApi");
hc.DefaultRequestHeaders.Accept.Clear();
hc.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await hc.PostAsync(hc.BaseAddress, new StringContent(json));
if (response.IsSuccessStatusCode)
{
Frame.Navigate(typeof(MainPage));
}
else
{
Quote_Text.Text = response.StatusCode.ToString();
//Returning Unsupported Media Type//
}
}
}
}
Quotes and Topic (Model)
public class Quotes
{
public int QuoteId { get; set; }
public int TopicId { get; set; }
public string QuoteText { get; set; }
public string QuoteAuthor { get; set; }
public Topic Topic { get; set; }
public string QuoteEffect { get; set; }
}
//Topic Model//
public class Topic
{
public int TopicId { get; set; }
public string TopicName { get; set; }
public string TopicDescription { get; set; }
public int TopicAmount { get; set; }
}
You should set the media type when creating StringContent
new StringContent(json, Encoding.UTF32, "application/json");
I found this question while working on a quick and dirty reverse proxy. I needed form data and not JSON.
This did the trick for me.
string formData = "Data=SomeQueryString&Foo=Bar";
var result = webClient.PostAsync("http://XXX/api/XXX",
new StringContent(formData, Encoding.UTF8, "application/x-www-form-urlencoded")).Result;
To fix the unsupported media type I had to use HttpRequestMessage and add header to accept json with MediaTypeWithQualityHeaderValue like bellow.
var httpRequestMessage = new HttpRequestMessage
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var httpResponse = await _client.PostAsync("/contacts", httpRequestMessage.Content);

Calling WebApi with complex object parameter using WebClient

I need to call a WebApi using WebClient where have to pass an object as parameter. I have my WebApi method as similar to bellow code:
example URI: localhost:8080/Api/DocRepoApi/PostDoc
[HttpPost]
public string PostDoc (DocRepoViewModel docRepo)
{
return string.enpty;
}
and then DocRepoViewModel is:
public class DocRepoViewModel
{
public string Roles { get; set; }
public string CategoryName { get; set; }
public List<AttachmentViewModel> AttachmentInfo { get; set; }
}
AttachmentViewModel is:
public class AttachmentViewModel
{
public string AttachmentName { get; set; }
public byte[] AttachmentBytes { get; set; }
public string AttachmentType { get; set; }
}
New I need to call PostDoc method from my MVC controller (not javascript ajax). How can I pass this specific parameter that I can make the call and get all data in my WebApi method. Can we do it by WebClient? Or there are better way. Please help.
You could use the PostAsJsonAsync method as follows:
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("localhost:8080/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var docViewModel = new DocRepoViewModel() { CategoryName = "Foo", Roles= "role1,role2" };
var attachmentInfo = new List<AttachmentViewModel>() { AttachmentName = "Bar", AttachmentType = "Baz", AttachmentBytes = File.ReadAllBytes("c:\test.txt" };
docViewModel.AttachmentInfo = attachmentInfo;
response = await client.PostAsJsonAsync("DocRepoApi/PostDoc", docViewModel);
if (response.IsSuccessStatusCode)
{
// do stuff
}
}
}
Asp .net reference
Check out following code.
string url = "Your Url";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.KeepAlive = false;
request.ContentType = "application/json";
request.Method = "POST";
var entity = new Entity(); //your custom object.
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(entity));
request.ContentLength = bytes.Length;
Stream data = request.GetRequestStream();
data.Write(bytes, 0, bytes.Length);
data.Close();
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string message = reader.ReadToEnd();
var responseReuslt = JsonConvert.Deserialize<YourDataContract>(message);
}
}

Categories

Resources