C# authorization in HTTP request Plivo API - c#

I am trying to use Plivo to send text messages from within my WindowsStore Application. Here is what almost works:
// These first 3 lines don't do what I want
var unamepass = AuthID + ":" + AuthToken;
var auth = new HttpCredentialsHeaderValue("Basic", unamepass);
httpClient.DefaultRequestHeaders.Authorization = auth;
string textBody = "sample message";
var plivoText = new
{
src = plivoNumber,
dst = phoneNumber,
text = textBody
};
string Serial = JsonConvert.SerializeObject(plivoText);
IHttpContent PlivoJsonContent = new HttpJsonContent(JsonValue.Parse(Serial));
HttpResponseMessage PlivoResponse =
await httpClient.PostAsync(
new Uri("https://api.plivo.com/v1/Account/<AuthID>/Message/")
, PlivoJsonContent);
Now, this code works... technically. I get a 202 response back. However, before it sends the text, a large authentication pops onto the screen.
If I enter the correct data I get a 202 and the text sends, otherwise I can't send the data. I want to know how to programmatically add this to the request, so I don't have to do it manually. I'm pretty sure it has something to do with the first 3 lines of the snippet, but the documentation I found online wasn't very helpful to me. I can't use RestSharp because it isn't supported for windows store projects, so I would prefer an HttpClient solution.
What "scheme" does Plivo use? How should I construct HttpCredentialsHeaderValue? Is the 3rd line correct?

The answer was startlingly simple. You must convert the string to base64 in order to send it to the header.
See: Convert UTF-8 to base64 string

Related

Microsoft cognitive service Recognize Text api

I call the microsoft recognize text api by passing the image that I had taken from my phone, there no error occur but every time the api will return me empty string as result doesn't matter what image I post . I try those image with the microsoft ocr api and it return me result, can anyone help ?
I call the microsoft recognize text api by passing the image that I had taken from my phone, there no error occur but every time the api will return me empty string as result doesn't matter what image I post.
In documentation of Recognize Text API, we can find:
The service has accepted the request and will start processing later.
It will return Accepted immediately and include an “Operation-Location” header. Client side should further query the operation status using the URL specified in this header.
I suspect that you directly get/extract content from the response after you made a request to recognize text, so the content would be string.Empty.
To get recognize text operation result, you need to make a further request using the URL specified in response header "Operation-Location".
In following test code, we can find the content is indeed empty.
Test Code:
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{Subscription_Key_here}");
queryString["mode"] = "Printed";
var uri = "https://{region}.api.cognitive.microsoft.com/vision/v2.0/recognizeText?" + queryString;
HttpResponseMessage response;
var imagePath = #"D:\xxx\xxx\xxx\testcontent.PNG";
Stream imageStream = File.OpenRead(imagePath);
BinaryReader binaryReader = new BinaryReader(imageStream);
byte[] byteData = binaryReader.ReadBytes((int)imageStream.Length);
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
var contentString = await response.Content.ReadAsStringAsync();
var operation_location = response.Headers.GetValues("Operation-Location").FirstOrDefault();
Console.WriteLine($"Response content is empty({contentString == string.Empty}).\n\rYou should further query the operation status using the URL ({operation_location}) specified in response header.");
}
}
Test Result:
Note: Recognize Text API is currently in preview and is only available for English text. As you mentioned, OCR technology in Computer Vision can also help detect text content in an image, and OCR currently supports 25 languages, sometimes we can use OCR as an alternative solution.

Twilio Authy 2FA for OneCode C# Implementation

I am developing a web application using C# that uses 2 factor authentication during Sign Up. I have already tried 2FA using Nexmo's API. It worked fine. All I had to do was call their API and speciy the 'to' number. Here is the code:
public ActionResult Start(string to)
{
var start = NumberVerify.Verify(new NumberVerify.VerifyRequest
{
number = to,
brand = "NexmoQS"
});
Session["requestID"] = start.request_id;
return View();
}
Now, I decided to give Twilio a try. I came across Authy and it's process. I found their 2FA API here. But I don't understand where should I enter the 'to' number as specified in Nexmo. I am a beginner and using .NET(C#) code snippet. Here is the code snippet. Please help me configure this code as I am able to do in Nexmo.
public static async Task VerifyPhoneAsync()
{
// Create client
var client = new HttpClient();
// Add authentication header
client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);
// https://api.authy.com/protected/$AUTHY_API_FORMAT/phones/verification/check?phone_number=$USER_PHONE&country_code=$USER_COUNTRY&verification_code=$VERIFY_CODE
HttpResponseMessage response = await client.GetAsync("https://api.authy.com/protected/json/phones/verification/check?phone_number=5558675309&country_code=1&verification_code=3043");
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine(await reader.ReadToEndAsync());
}
}
They have given a cURL implementation of their api here, please help me configure it in C#.
curl "http://api.authy.com/protected/json/users/new?api_key=d57d919d11e6b221c9bf6f7c882028f9" \
-d user[email]="user#domain.com" \
-d user[cellphone]="317-338-9302" \
-d user[country_code]="54"
Twilio developer evangelist here.
When making a call to the API, you do need to add the X-Authy-API-Key header as well as a URL parameter api_key. Also, to start the process of verifying a number you should be making a POST request with the data you need to send to the API.
The two bits of data that you need are the phone number and the country code for that phone number. Though you can set some other values, like the way you want to send the verification code (via sms or call).
I would update your code to look like this:
public static async Task StartVerifyPhoneAsync()
{
// Create client
var client = new HttpClient();
var AuthyAPIKey = 'YOUR AUTHY API KEY';
// Add authentication header
client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);
var values = new Dictionary<string, string>
{
{ "phone_number", "PHONE NUMBER TO VERIFY" },
{ "country_code", "COUNTRY CODE FOR PHONE NUMBER" }
};
var content = new FormUrlEncodedContent(values);
var url = $"https://api.authy.com/protected/json/phones/verification/start?api_key={AuthyAPIKey}";
HttpResponseMessage response = await client.PostAsync(url, content);
// do something with the response
}
Then when the user enters the code, you need to check it. Again you should add the API key as a header and send as a URL parameter too, along with the phone number, country code and the verification code the user entered, this time as a GET request.
public static async Task CheckVerifyPhoneAsync()
{
// Create client
var client = new HttpClient();
var AuthyAPIKey = 'YOUR AUTHY API KEY';
// Add authentication header
client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);
var phone_number = "PHONE NUMBER TO VERIFY";
var country_code = "COUNTRY CODE FOR PHONE NUMBER";
var verification_code = "THE CODE ENTERED BY THE USER";
var url = $"https://api.authy.com/protected/json/phones/verification/start?api_key={AuthyAPIKey}&phone_number={phone_number}&country_code={country_code}&verification_code={verification_code}";
HttpResponseMessage response = await client.GetAsync(url);
// do something with the response
}
Let me know if that helps at all.

How to write nested Json web services in c# for windows store app

I'm working on windows store app where i am using a web service which have parameter which are nested like this
userData, #"user_login",
email, #"email",password, #"password",
user_login key contains to key email and password with their value .I Hit the web service in the fiddler and if works i am getting the response the parameter string i used
{
"user_login":{"email" : "mmmmmmmm#fdhfgh.co","password" : "pass1234"}
}
when i am using this parameter string in my code i am getting error of status code 400 bad request due to the parameter string .
here is my code
string content = string.Empty;
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
httpClient.DefaultRequestHeaders.Date = DateTime.Now;
var httpContent = new System.Net.Http.StringContent("{'user_login':[{'email':"mmmmmmmm#fdhfgh.co",'password':'pass1234'}}]", Encoding.UTF8,"application/json");
var httpResponse = await httpClient.PostAsync(" http://localhost/appi/pupil/log_in", httpContent);
content = await httpResponse.Content.ReadAsStringAsync();
help me out with your valuable suggestions.
In your C# code, you're passing in an array (as denoted by the [ ]'s). It doesn't look like your were doing that in Fiddler. It also looks like the [ ]'s aren't formatted properly. I'd try just taking that out.
EDIT:
"{\"user_login\":{\"email\":\"mmmmmmmm#fdhfgh.com\",\"password\":\"pass1234\"}}"
If this is the correct signature, the above JSON would work.
EDIT 2:
var httpResponse = await httpClient.PostAsync(" http://localhost/appi/pupil/log_in", httpContent);
Couldn't help but notice that you had "localhost/appi" instead of "localhost/api". That could possibly be a typo? Along with that leading space.

Access JSON values from URL

I am trying to get data from a URL that contains JSON values. These values are to be used in my windows 8 desktop app. The code I have tried is seen below.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(App.DataServiceUrl + "/productcategory");
var Groups = new List<GroupList>();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var prods = JsonConvert.DeserializeObject<dynamic>(content);
foreach (var data in prods)
{
var dataGroup = new GroupList
(
data.term_id,
data.name,
data.slug,
data.description,
data.taxonomy
);
Groups.Add(dataGroup);
}
}
The URL I am accessing is actually a page in a website where I call some fucntions to get some data in php and then use json_encode($all); to return json data. When I access the url, I can see all the JSON data.
One example of the data from URL is:
[{"term_id":"64","name":"Argentina","slug":"argentina","term_group":"0","term_taxonomy_id":"64","taxonomy":"product_cat","description":"","parent":"13","count":"20","meta_id":"154","woocommerce_term_id":"64","meta_key":"order","meta_value":"0","cat_ID":"64","category_count":"20","category_description":"","cat_name":"Argentina","category_nicename":"argentina","category_parent":"13"},...]
But the application doesn't recognize the json values when I try to access them such as term_id, name etc. (as seen in code above)
Instead when I run the application I get this error:
Unexpected character encountered while parsing value: <. Path", line 4, position 2
How do I get and use the values from the url in my C# code?
You could use the DynamicJson class to parse the JSON, as far as I know it's the best option.
Your page produces some random text in front of JSON. You can take any HTTP debugger (my favorite is Fiddler, but anything would do) to confirm. Here are first several lines of the response from http://cbbnideas.com/brydens-website/api/ - note that JSON starts at 8th line:
37
<!--All Categories (And Sub Categories)-->
6bd8
[{"term_id":"64","name":"Argentina","slug":"argentina","term_gr...

How to initiate an outgoing call with message?

I'm trying to notify the caller with an automated message. Here is my code below.
string
string AccountSid = "***************";
string AuthToken = "**************";
var doc = new XDocument();
var call = new XElement("call");
call.Add(new XElement("Say", Message));
doc.Add(call);
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var options = new CallOptions();
options.Url = doc.ToString(); //Don't have URL need to add XML doc instead
options.To = Phone;
options.From = "********";
var callnow = twilio.InitiateOutboundCall(options);
Twilio Developer Evangelist here.
You cannot add the XML into the CallOptions as shown in the code above. You do need to find a way to place your TwiML into an XML document on a URI accessible by Twilio.
If the message is not dynamic to the call, you could host a static XML file containing TwiML on a service such as Amazon's S3. I have occasionally used Dropbox Public URLs, but only for testing at low volume. But there are lots of options available, including the TwiMLBin service. But if your message is dynamic in any way, you are going to need an application that can respond to HTTP requests.
Is there some particular constraint you have, maybe I can suggest a work around?
Hope this helps!

Categories