I'm trying to send some string from a service to a webmethod service with the following code:
private void SendRequest(string filePath, string webService)
{
try
{
using (var wb = new WebClient())
{
string data = File.ReadAllText(filePath);
data = "data=" + data;
string res = wb.UploadString(webService, data);
}
}
catch (Exception e)
{
logEvents.Write(MyLogClass.LogLevel.Info, "Data not sent " + e.Message);
}
}
For some reason I don't know res is returning the html code of the frontpage.
I was doing this previously with node and my webservice would accept the string without a problem and return 200.
The code of the web service starts as follows:
[WebMethod]
public static string Data(string data)
I've tried formatting the data in several ways and changing the arguments and the URLs are well. The problem is not in the web service since it works fine with my node request. What could it be?
Solved this by serializing the data being sent and using WebRequest instead of WebClient.
Edit
var webRequest = WebRequest.Create(webService);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
string data = File.ReadAllText(filePath);
var jsonObject = new { data };
var serializedObject = JsonConvert.SerializeObject(jsonObject);
var bytes = Encoding.ASCII.GetBytes(serializedObject);
var requestStream = webRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Try specifying Headers explicitly.
using (var wb = new WebClient())
{
wb.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string data = File.ReadAllText(filePath);
data = "data=" + data;
string res = wb.UploadString(webService, /*"POST",*/ data);
}
I am trying to return the response of productRating in this HTTP call. I have tried several ways but haven't been successful. Any idea? The response is a json with an object that I want to get access to the streamInfo>avgRatings>_overall
public double GetRatings(string productId)
{
const string URL = "https://comments.au1.gigya.com/comments.getStreamInfo";
var apiKey = "3_rktwTlLYzPlqkzS62-OxNjRDx8jYs-kV40k822YlHfEx5VCu93fpUo8JtaKDm_i-";
var categoryId = "product-ratings";
var urlParams = "?apiKey=" + apiKey + "&categoryID=" + categoryId + "&streamID=" + productId + "";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = JsonConvert.DeserializeObject(client.GetAsync(urlParams).Result.Content.ReadAsStringAsync().Result);
var productrating = (response["streamInfo"]["avgRatings"]["_overall"]);
return;
}
GetRatings Erroe: not all code paths return a value.
Productrating Error:can not apply indexing with [] to an expression of type HttpResponseMessage
return Error: an object of a type convertable to double is required
ApiCall has to return something. Looking at the example below.
#functions {
public static string ApiCall()
{
return "Hello World!";
}
}
#{
var ratings = ApiCall();
}
#if (ratings != null)
{
<div class="gig-rating-stars" content=#ratings></div>
}
I am using this function for POST API Call and it returns response string and if you want to add security features you can send it in JObject because its the secure channel to send Jobject as a parameter on URL
## Code Start ##
protected string RemoteApiCallPOST(JObject elements, string url)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
// JObject jsonResult = new JObject();
string id;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(elements);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
id = (streamReader.ReadToEnd()).ToString();
return id;
}
}
catch (Exception EX)
{
return "";
}
}
Code End
The only change I needed to do is changing "var" to "dynamic" in :
dynamic response = JsonConvert.DeserializeObject(client.GetAsync(urlParams).Result.Content.ReadAsStringAsync().Result);
I have the following Delete WebAPI implemented, which is working fine and tested through swagger:
//Delete IVR Paycode Profiles
[System.Web.Http.HttpDelete, System.Web.Http.Route("PayCodeProfile")]
public System.Threading.Tasks.Task<ConfirmResponse> DeleteIVRPaycodeProfile(string profileIds)
{
string orgoid = HttpContext.Current.Request.Headers["ORGOID"];
SetContext(orgoid);
return _implementation.DeleteIVRPaycodeProfileAsync(orgoid, profileIds);
}
And I am calling from client like below:
var endpointURL = new Uri("http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile/1,2,3");
var request = WebRequest.Create(endpointURL) as HttpWebRequest;
if (request != null)
{
request.Headers.Add("ORGOID", "G344G4GEJXDJJ9M5");
// sending comma separated string of ids like 1,2,
// not sure if the ContentType is correct
request.ContentType = "text/html";
request.Method = "DELETE";
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
var resp = JsonConvert.DeserializeObject<ConfirmResponse>(result);
}
}
}
But I am getting 404:Not Found error, I believe that somewhere I am making a mistake for ContentType.
the problem is your url. at first you need to send the request to this address: "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile". then depend on your content type(by default it is json) create your request. if your content type is json try this:
private static T Call<T>(string url, string body, int timeOut = 60)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeOut * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "DELETE";
request.ContentType = #"application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
reader.BaseStream.ReadTimeout = timeOut * 1000;
responseString = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(responseString);
}
then call it like this:
var url = "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile";
var body = JsonConvert.SerializeObject(new { profileIds = "1,2,3" });
var output = Call<dynamic>(url, body);
I'm new to all Android GCM push notifications and I have read stack posts but couldn't get a straight answer.I have also read Create push notification in android to get a better understanding of how GCM works. I have also used the gcm-demo-server and gcm-demo-client provided by the SDK. However, here are my doubts and what I have tried so far:
Regarding the link I have put, the phone which has the app registers to get the registration key. Is this a unique key for all phones which uses the same app?
Does this registration key expires in any case? (E.g. App running on background)
Assuming that I have the registration key, I have tried the following code snippet to push notification via GCM to my app. This is written on c# .net. Please let me know whether what I have mentioned above can be achieved using the following code snippet:
private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
{
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
// MESSAGE CONTENT
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// CREATE REQUEST
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = postDataContentType;
Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
// SEND MESSAGE
try
{
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadToEnd();
Reader.Close();
return responseLine;
}
catch (Exception e)
{
}
return "error";
}
Is there a direct way of sending push notifications without the phone first being registered in our custom server?
Refer Code:
public class AndroidGCMPushNotification
{
public AndroidGCMPushNotification()
{
//
// TODO: Add constructor logic here
//
}
public string SendNotification(string deviceId, string message)
{
string SERVER_API_KEY = "server api key";
var SENDER_ID = "application number";
var value = message;
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + deviceId + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
}
Referance Link:
http://www.codeproject.com/Tips/434338/Android-GCM-Push-Notification
Code looks bit long but it works. I just sent a push notification to my phone after struggling 2 days by implementing the following code in C# project. I referred a link regarding this implementation, But couldn't find it to post here. So will share my code with you. If you want to test the Notification online you may visit to this link.
note : I have hardcorded apiKey, deviceId and postData, please pass
the apiKey,deviceId and postData in your request and remove them from
the method body. If you want pass message string also
public string SendGCMNotification(string apiKey, string deviceId, string postData)
{
string postDataContentType = "application/json";
apiKey = "AIzaSyC13...PhtPvBj1Blihv_J4"; // hardcorded
deviceId = "da5azdfZ0hc:APA91bGM...t8uH"; // hardcorded
string message = "Your text";
string tickerText = "example test GCM";
string contentTitle = "content title GCM";
postData =
"{ \"registration_ids\": [ \"" + deviceId + "\" ], " +
"\"data\": {\"tickerText\":\"" + tickerText + "\", " +
"\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
//
// MESSAGE CONTENT
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//
// CREATE REQUEST
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = postDataContentType;
Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//
// SEND MESSAGE
try
{
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadToEnd();
Reader.Close();
return responseLine;
}
catch (Exception e)
{
}
return "error";
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
You may not familiar with words like apiKey, deviceId. Dont worry i will explain what are they and how to create those.
apiKey What & why :This a key that will be used when sending requests to GCM server. How to create : Refer this post
deviceId What & why : This id also known as RegistrationId. This is a unique id to identify the device. When you want to send a
notification to a specific device you need this id. How to
create: This depends on how you implement the application. For cordova
i used a simple pushNotification Plugin You can simply create a
deviceId/RegistrationId using this plugin. To do that you need to have
a senderId. Google how to create a senderId it is really simple =)
If anyone needs some help leave a comment.
Happy Coding.
-Charitha-
Just for the information for new visitors on this post, if you want to send same message to multiple devices then simply send comma separated device ids in registration_id parameter of request.
Here is a nice article on this
http://www.codewithasp.net/2015/11/send-message-gcm-c-sharp-single-multiple.html
This never worked for me and it is hard to debug plus passing a list of registration token is not clear -would expect passing a string array instead of comma separated string - , the fact that this is very simple post request i created my own class with a method that return the server response, and it works very well:
Usage
//Registration Token
string[] registrationIds ={"diks4vp5......","erPjEb9....."};
AndroidGcmPushNotification gcmPushNotification = new
AndroidGcmPushNotification(
"API KEY", registrationIds, "Hello World"
);
gcmPushNotification.SendGcmNotification();
Class
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
public class AndroidGcmPushNotification
{
private readonly string _apiAccessKey;
private readonly string[] _registrationIds;
private readonly string _message;
private readonly string _title;
private readonly string _subtitle;
private readonly string _tickerText;
private readonly bool _vibrate;
private readonly bool _sound;
public AndroidGcmPushNotification(string apiAccessKey, string[] registrationIds, string message, string title = "",
string subtitle = "", string tickerText = "", bool vibrate = true, bool sound = true )
{
_apiAccessKey = apiAccessKey;
_registrationIds = registrationIds;
_message = message;
_title = title;
_subtitle = subtitle;
_tickerText = tickerText;
_vibrate = vibrate;
_sound = sound;
}
public string SendGcmNotification()
{
//MESSAGE DATA
GcmPostData data = new GcmPostData()
{
message = _message,
title = _title,
subtitle = _subtitle,
tickerText = _tickerText,
vibrate = _vibrate,
sound = _sound
};
//MESSAGE FIELDS
GcmPostFields fields = new GcmPostFields();
fields.registration_ids = _registrationIds;
fields.data = data;
//SERIALIZE TO JSON
JavaScriptSerializer jsonEncode = new JavaScriptSerializer();
//CONTENTS
byte[] byteArray = Encoding.UTF8.GetBytes(jsonEncode.Serialize(fields));
//REQUEST
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
request.Method = "POST";
request.KeepAlive = false;
request.ContentType = "application/json";
request.Headers.Add($"Authorization: key={_apiAccessKey}");
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//SEND REQUEST
try
{
WebResponse response = request.GetResponse();
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseLine = reader.ReadToEnd();
reader.Close();
return responseLine;
}
}
catch (Exception e)
{
return e.Message;
}
}
private class GcmPostFields
{
public string[] registration_ids { get; set; }
public GcmPostData data { get; set; }
}
private class GcmPostData
{
public string message { get; set; }
public string title { get; set; }
public string subtitle { get; set; }
public string tickerText { get; set; }
public bool vibrate { get; set; }
public bool sound { get; set; }
}
}
There is package PushSharp.
Allows to communicate with almost every popular notification api.
Example code:
// Configuration
var config = new GcmConfiguration ("GCM-SENDER-ID", "AUTH-TOKEN", null);
// Create a new broker
var gcmBroker = new GcmServiceBroker (config);
// Wire up events
gcmBroker.OnNotificationFailed += (notification, aggregateEx) => {
aggregateEx.Handle (ex => {
// See what kind of exception it was to further diagnose
if (ex is GcmNotificationException) {
var notificationException = (GcmNotificationException)ex;
// Deal with the failed notification
var gcmNotification = notificationException.Notification;
var description = notificationException.Description;
Console.WriteLine ($"GCM Notification Failed: ID={gcmNotification.MessageId}, Desc={description}");
} else if (ex is GcmMulticastResultException) {
var multicastException = (GcmMulticastResultException)ex;
foreach (var succeededNotification in multicastException.Succeeded) {
Console.WriteLine ($"GCM Notification Failed: ID={succeededNotification.MessageId}");
}
foreach (var failedKvp in multicastException.Failed) {
var n = failedKvp.Key;
var e = failedKvp.Value;
Console.WriteLine ($"GCM Notification Failed: ID={n.MessageId}, Desc={e.Description}");
}
} else if (ex is DeviceSubscriptionExpiredException) {
var expiredException = (DeviceSubscriptionExpiredException)ex;
var oldId = expiredException.OldSubscriptionId;
var newId = expiredException.NewSubscriptionId;
Console.WriteLine ($"Device RegistrationId Expired: {oldId}");
if (!string.IsNullOrWhitespace (newId)) {
// If this value isn't null, our subscription changed and we should update our database
Console.WriteLine ($"Device RegistrationId Changed To: {newId}");
}
} else if (ex is RetryAfterException) {
var retryException = (RetryAfterException)ex;
// If you get rate limited, you should stop sending messages until after the RetryAfterUtc date
Console.WriteLine ($"GCM Rate Limited, don't send more until after {retryException.RetryAfterUtc}");
} else {
Console.WriteLine ("GCM Notification Failed for some unknown reason");
}
// Mark it as handled
return true;
});
};
gcmBroker.OnNotificationSucceeded += (notification) => {
Console.WriteLine ("GCM Notification Sent!");
};
// Start the broker
gcmBroker.Start ();
foreach (var regId in MY_REGISTRATION_IDS) {
// Queue a notification to send
gcmBroker.QueueNotification (new GcmNotification {
RegistrationIds = new List<string> {
regId
},
Data = JObject.Parse ("{ \"somekey\" : \"somevalue\" }")
});
}
// Stop the broker, wait for it to finish
// This isn't done after every message, but after you're
// done with the broker
gcmBroker.Stop ();
I have worked with Android Applications and IOS application using Firebase's FCM.
This code is working .Middle layer is ASP.NET API.You start a project in visual studio and select API.To be create a controller.Your server_api_key and sender id adding Web.config file.
Adding user fcm server_api_key and sender id.
<appSettings>
<add key="SERVER_API_KEY" value=""/>
<add key="SENDER_ID" value=""/>
</appSettings>
The below code to add your controller
using System;
using System.Net;
using System.Web.Http;
using System.Web.Script.Serialization;
using System.Configuration;
using System.IO;
namespace pushios.Controllers
{
public class HomeController : ApiController
{
[HttpGet]
[Route("sendmessage")]
public IHttpActionResult SendMessage()
{
var data = new {
to = "Device Token",
data = new
{
//To be adding your json data
body="Test",
confId= "",
pageTitle= "test",
pageFormat= "",
dataValue= "",
title= "C#",
webviewURL= "",
priority = "high",
notificationBlastID = "0",
status = true
}
};
SendNotification(data);
return Ok();
}
public void SendNotification(object data)
{
var Serializer = new JavaScriptSerializer();
var json = Serializer.Serialize(data);
Byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(json);
SendNotification(byteArray);
}
public void SendNotification(Byte[] byteArray)
{
try
{
String server_api_key = ConfigurationManager.AppSettings["SERVER_API_KEY"];
String senderid = ConfigurationManager.AppSettings["SENDER_ID"];
WebRequest type = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
type.Method = "post";
type.ContentType = "application/json";
type.Headers.Add($"Authorization: key={server_api_key}");
type.Headers.Add($"Sender: id={senderid}");
type.ContentLength = byteArray.Length;
Stream datastream = type.GetRequestStream();
datastream.Write(byteArray, 0, byteArray.Length);
datastream.Close();
WebResponse respones = type.GetResponse();
datastream = respones.GetResponseStream();
StreamReader reader = new StreamReader(datastream);
String sresponessrever = reader.ReadToEnd();
reader.Close();
datastream.Close();
respones.Close();
}
catch (Exception)
{
throw;
}
}
}
}
Suppose I have the following web method using C# and .NET:
[WebInvoke(UriTemplage="/users", Method="POST")]
[OperationContract]
public User AddNewUser(User u);
It is expected that when you implement POST web method you will accept a request body as part of the incoming HTTP request message. The parameter u is expected to be deserialized from the incoming HTTP message body.
My question is: how do we set this request body on the client side ? It's got to be set somewhere. It really confuses me.
Besides if I added "ResponseFormat = WebMessageFormat.Json" to WebInvoke, how can I deserialize from the returned json string into the User object ?
Thanks.
Your question doesn't reveal what you have tried. If you are using .net on the client then you can use the DataContractSerializer to get the serialized data.
You can then use an HttpWebRequest with the method set to POST.
Add the serialized data to the web request and use the GetResponse() method.
Alternatively you could use Fiddlr to test your web service using requests that you create. It gives you a concise view of exactly what is going up to the server.
To perform a POST request to your WCF Rest method:
private string UseHttpWebApproach<T>(string serviceUrl, string resourceUrl, string method, T requestBody)
{
string responseMessage = null;
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/json";
request.Method = method;
}
if(method == "POST" && requestBody != null)
{
byte[] requestBodyBytes = ToByteArrayUsingJsonContractSer(requestBody);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.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 static byte[] ToByteArrayUsingJsonContractSer<T> (T requestBody)
{
byte[] bytes = null;
var serializer1 = new DataContractJsonSerializer(typeof(T));
var ms1 = new MemoryStream();
serializer1.WriteObject(ms1, requestBody);
ms1.Position = 0;
var reader = new StreamReader(ms1);
bytes = ms1.ToArray();
return bytes;
}
Now Assuming your User object as shown below:
Public Class User
{
Public int UserId {get;set;}
Public string UserName {get;set;}
Public string Password {get;set;}
}
The to call the above method i do:
User objUser = new objUser();
objUser.Username = "Test";
objUser.Password = "Test";
UseHttpWebApproach<User>(serviceBaseUrl, "users", "POST", objUser);