I'm new to Json rest full services , how to get methods from json rest service? and how to Parse values to method in api using C# console applications - console

static void Main(string[] args)
{
const string url = "https://test-api.abccc.com/api/Relayxxx.apixxxx?__token=xxxxxxxxxxxxxxxxxx";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
/* using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user\":\"xxxx\"," +
"\"password\":\"yyyy\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}*/
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
Please help me how to call functions using this api and how can i get values from specified functions and send values to specific function.

Related

app crashes when trying to send multiple fcm messages programmatically

i am trying to create a messaging app using xamarin.forms. i created a send button and added the following code:
private async void send_Clicked(object sender, EventArgs e)
{
await Task.Run(() => SendNotification(token, "title", message.Text));
}
and the sendnotification is as follows:
public string SendNotification(string DeviceToken, string title, string msg)
{
var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
httpWebRequest.Method = "POST";
var payload = new
{
//to= "/topics/klm",
to = DeviceToken,
//to = "egjLx6VdFS0:APA91bGQMSSRq_wCzywNC01zJi4FBtHXrXuL-p4vlkl3a3esdH8lxo7mQZUBlrTi7h-6JXx0GrJbwc9Vx6M5Q4OV_3CArcdlP0XMBybervQvfraWvqCgaa75gu9SVzjY4V_qd36JGg4A",
priority = "high",
content_available = true,
data = new
{
text = msg,
},
};
var serializer = new JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(payload);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
this is private string webAddr = "https://fcm.googleapis.com/fcm/send";
when i click send the first time, i receive the message perfectly, when i hit send the second time, the app freezes then crashes and asks me if i want to close the app or wait. why is this happening? thanks in advance

how to call google acknowledge api from wcf service?

i need to add a call to google acknowledge endpoint into existing dotnet web service app.
this is the refence page https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.products/acknowledge
i never worked on this app before, and i can not ask who developed it, He went away.
in the web.config are stored PlayStore ClientId and ClientSecret.
this is existing and working call to check a subscription:
internal PlayStoreSubscriptionPurchaseStatus verifySubscription(string packageName, string subscriptionId, string token, ref long timeMills)
{
Stopwatch watcher = new Stopwatch();
string accessToken = this.generateNewAccessToken(ref timeMills);
string verifySubscriptionAddress = _playStoreApisAddress + packageName + "/purchases/subscriptions/" + subscriptionId + "/tokens/" + token + "?access_token=" + accessToken;
PlayStoreSubscriptionPurchaseStatus playStoreResponse = null;
try
{
HttpWebRequest verifyRequest = WebRequest.Create(verifySubscriptionAddress) as HttpWebRequest;
verifyRequest.Method = "GET";
verifyRequest.ContentType = "application/json; charset=utf-8";
verifyRequest.Accept = "application/json; charset=utf-8";
watcher.Start();
using (HttpWebResponse verifyResponse = verifyRequest.GetResponse() as HttpWebResponse)
{
watcher.Stop();
Stream responseStream = verifyResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string responseAsString = streamReader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
if (verifyResponse.StatusCode == HttpStatusCode.OK)
playStoreResponse = jss.Deserialize<PlayStoreSubscriptionPurchaseStatus>(responseAsString);
else
{
playStoreResponse = new PlayStoreSubscriptionPurchaseStatus() { Success = false, ErrorMessage = responseAsString };
}
}
}
catch (WebException webEx)
{
using (StreamReader streamReader = new StreamReader(webEx.Response.GetResponseStream()))
{
string webExResponse = streamReader.ReadToEnd();
throw new Exception("Errore nella verifica subscription google play.\nErrore restituito dalle api google play:\n" + webExResponse);
}
}
finally
{
if (watcher.IsRunning)
watcher.Stop();
timeMills += watcher.ElapsedMilliseconds;
}
return playStoreResponse;
}
this code generates access_token:
private string generateNewAccessToken(ref long timeMills)
{
Stopwatch watcher = new Stopwatch();
string newAccessToken = string.Empty;
string postDta = string.Format("grant_type={0}&client_id={1}&client_secret={2}&refresh_token={3}",
"refresh_token", Uri.EscapeDataString(_clientId), Uri.EscapeDataString(_clientSecret), Uri.EscapeDataString(_refreshToken));
try
{
HttpWebRequest refreshAccessTokenRequest = WebRequest.Create(_refreshTokenAddress) as HttpWebRequest;
refreshAccessTokenRequest.Method = "POST";
refreshAccessTokenRequest.ContentType = "application/x-www-form-urlencoded";
//refreshAccessTokenRequest.ContentLength = new UTF8Encoding().GetBytes(postDta).Length;
refreshAccessTokenRequest.Accept = "application/json; charset=utf-8";
Stream refreshTokenRequestStream = refreshAccessTokenRequest.GetRequestStream();
StreamWriter streamWriter = new StreamWriter(refreshTokenRequestStream);
streamWriter.Write(postDta);
streamWriter.Close();
watcher.Start();
using (HttpWebResponse refreshAccessTokenResponse = refreshAccessTokenRequest.GetResponse() as HttpWebResponse)
{
watcher.Stop();
Stream responseStream = refreshAccessTokenResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string responseAsString = streamReader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
RenewAccessTokenResponse renewAccessTokenResponse = jss.Deserialize<RenewAccessTokenResponse>(responseAsString);
newAccessToken = renewAccessTokenResponse.access_token;
}
}
catch (WebException webEx)
{
using (StreamReader streamReader = new StreamReader(webEx.Response.GetResponseStream()))
{
string webExResponse = streamReader.ReadToEnd();
throw new Exception(webExResponse);
}
}
finally
{
if (watcher.IsRunning)
watcher.Stop();
timeMills += watcher.ElapsedMilliseconds;
}
return newAccessToken;
}
what i want to know is if i can, using only httpwebrequest, make a call to acknlowelage api,
access token generate from generateNewAccessToken is good for this api?
if yes where do i have to store it? acknlowelage is POST while all existing calls in the project are GET. do i have store the access code in body or into some header?
there is somewhere a working sample?
thanks.

getting data from Web Services c#

I have an issue loading data in the correct format from web services.
Web Service code:
[WebMethod]
public string LoadLearrner(string id)
{
MyFunctions func = new MyFunctions();
DataSet ds;
DataSet dtsta = SQLServer.GetDsBySP("Load_Learner_ForCRM","learnerId", id.ToString());
string[] cntName = new string[dtsta.Tables[0].Rows.Count];
List<string> list = new List<string>();
int i = 0;
foreach (DataRow rdr in dtsta.Tables[0].Rows)
{
list.Add(rdr[0].ToString());
list.Add(rdr[1].ToString());
list.Add(rdr[2].ToString());
list.Add(rdr[3].ToString());
list.Add(rdr[5].ToString());
i++;
}
String[] str = list.ToArray();
string JSONString=string.Empty;
JSONString = JsonConvert.SerializeObject(str);
return JSONString;
}
Code that's used to call the above web service method is:
WebRequest request = (HttpWebRequest)WebRequest.Create("http://abc/Company/CrmLearner.asmx/LoadLearrner?id=" + item.learner_id);
request.Method = "GET";
request.ContentType = "application/text";
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}
Result is:
I don't want the result like that. I want to load proper XML or JSON and store it in an object.

You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse

I tried to upload file on oracle cloud infrastructure iaas but getting the error.I am not sure whether the file that I attached in the body is in
correct format or not. ApI signing is correct and I am doubt only about
whether the code that I wrote is upto mark or not. The code snippet is mentioned below.
The code Snippet :
FileInfo f = new FileInfo(FileUpload1.FileName);
byte[] filebyte =FileUpload1.FileBytes;
var postdata = Encoding.UTF8.GetBytes(filebyte.ToString());
Console.Write(postdata.Length);
var tenancyId = ConfigurationManager.AppSettings["BMCTenancyId"];
var userId = ConfigurationManager.AppSettings["BMCUserId"];
var fingerprint = ConfigurationManager.AppSettings["BMCFingerprint"];
var privateKeyPath = ConfigurationManager.AppSettings["BMCPrivateKeyPath"];
var privateKeyPassphrase = ConfigurationManager.AppSettings["BMCPrivateKeyPassphrase"];
var signer = new RequestSigner(tenancyId, userId, fingerprint, privateKeyPath, privateKeyPassphrase);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/");
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/json";
request.SendChunked = true;
request.ContentType = "text/plain";
request.ContentLength =postdata.Length;
try
{
using (var stream = request.GetRequestStream())
{
stream.Write(postdata, 0, postdata.Length);
stream.Close();
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
request.Headers["x-content-sha256"] = Convert.ToBase64String(SHA256.Create().ComputeHash(postdata));
signer.SignRequest(request);
Console.WriteLine($"Authorization header: {request.Headers["authorization"]}");
ExecuteRequest(request);
Console.WriteLine("The value of 'ContentLength' property after sending the data is {0}", request.ContentLength);
}
private static void ExecuteRequest(HttpWebRequest request)
{
try
{
var webResponse = (HttpWebResponse)request.GetResponse();
var response = new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
Console.WriteLine($"Response: {response}");
}
catch (WebException e)
{
Console.WriteLine($"Exception occurred: {e.Message}");
Console.WriteLine($"Response: {new StreamReader(e.Response.GetResponseStream()).ReadToEnd()}");
}
}
For one thing, you'll need to update the URL to the following format:
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/n/{namespaceName}/b/{bucketName}/o/{objectName}");
Docs: https://docs.cloud.oracle.com/iaas/api/#/en/objectstorage/20160918/Object/PutObject
Also, can you please edit the question to include the complete error you are receiving, that will help with debugging.

ASP .Net Web API downloading images as binary

I want to try to use Web API make a rest call but I want the response to be the actual binary image stored in a database, not a JSON base64 encoded string. Anyone got some pointers on this?
Update-
This is what I ended up implementing:
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(new MemoryStream(profile.Avatar));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "avatar.png";
return result;
You can set the response content to a StreamContent object:
var fileStream = new FileStream(path, FileMode.Open);
var resp = new HttpResponseMessage()
{
Content = new StreamContent(fileStream)
};
// Find the MIME type
string mimeType = _extensions[Path.GetExtension(path)];
resp.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
While this has been marked as answered, it wasn't quite what I wanted, so I kept looking. Now that I've figured it out, here's what I've got:
public FileContentResult GetFile(string id)
{
byte[] fileContents;
using (MemoryStream memoryStream = new MemoryStream())
{
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
image.Save(memoryStream, ImageFormat.Jpeg);
fileContents = memoryStream.ToArray();
}
return new FileContentResult(fileContents, "image/jpg");
}
Granted, that's for getting an image through a URL. If you just want to grab an image off the file server, I'd imagine you replace this line:
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
With this:
using (Bitmap image = new Bitmap(myFilePath))
EDIT: Never mind, this is for regular MVC. for Web API, I have this:
public HttpResponseMessage Get(string id)
{
string fileName = string.Format("{0}.jpg", id);
if (!FileProvider.Exists(fileName))
throw new HttpResponseException(HttpStatusCode.NotFound);
FileStream fileStream = FileProvider.Open(fileName);
HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
response.Content.Headers.ContentLength = FileProvider.GetLength(fileName);
return response;
}
Which is quite similar to what OP has.
I did this exact thing. Here is my code:
if (!String.IsNullOrWhiteSpace(imageName))
{
var savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine(uploadPath, imageName));
var image = System.Drawing.Image.FromFile(savedFileName);
if (ImageFormat.Jpeg.Equals(image.RawFormat))
{
// JPEG
using(var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Jpeg);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
else if (ImageFormat.Png.Equals(image.RawFormat))
{
// PNG
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Png);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
else if (ImageFormat.Gif.Equals(image.RawFormat))
{
// GIF
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Gif);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
}
And then on the client:
var client = new HttpClient();
var imageName = product.ImageUrl.Replace("~/Uploads/", "");
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
Properties.Settings.Default.DeviceMediaPath + "\\" + imageName);
var response =
client.GetAsync(apiUrl + "/Image?apiLoginId=" + apiLoginId + "&authorizationToken=" + authToken +
"&imageName=" + product.ImageUrl.Replace("~/Uploads/","")).Result;
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsByteArrayAsync().Result;
using (var ms = new MemoryStream(data))
{
using (var fs = File.Create(path))
{
ms.CopyTo(fs);
}
}
result = true;
}
else
{
result = false;
break;
}
This task is much easily achieved without using WebAPI. I would implement a custom HTTP handler for a unique extension, and return the binary response there. The plus is that you can also modify the HTTP Response headers and content type, so you have absolute control over what is returned.
You can devise a URL pattern (defining how you know what image to return based on its URL), and keep those URLs in your API resources. Once the URL is returned in the API response, it can be directly requested by the browser, and will reach your HTTP handler, returning the correct image.
Images are static content and have their own role in HTTP and HTML - no need to mix them with the JSON that is used when working with an API.

Resources