I am using exchange api Push notification in C#.
I receive exchange api push notification on .aspx page(C#) in Request.InputStream.
Now I Need to send OK response. But my problem is that where i Have to send this response. I mean which URL and how.
Please help me with C# code.
Below is my code :
I have see some example on google so i try to send SOAP message :
string oRequest = "";
oRequest = "<?xml version=\"1.0\" encoding=\"UTF - 8\"?>";
oRequest += "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";
oRequest += "<soap:Body><m:SendNotificationResult><m:SubscriptionStatus>Ok</m:SubscriptionStatus></m:SendNotificationResult></soap:Body>";
oRequest += "</soap:Envelope>";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("This is the URL which i provide to exchange when i create subsricption. Is this wrong, What will be the URL");
req.Headers.Add("SOAPAction", "http://schemas.microsoft.com/exchange/services/2006/messages/SendNotification")
req.ContentType = "text/xml; charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
//Passes the SoapRequest String to the WebService
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(oRequest);
}
}
//Gets the response
WebResponse response = req.GetResponse();
//Writes the Response
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream);
string s = sr.ReadToEnd();
Push notifications are automatically sent to the web service listener (the callback URL specified in the subscription request).
when push notifications send events to your web service listener. your can send your response (OK or Unsubscribe).
You do not need to call the url of exchange.
You can refer:
https://msdn.microsoft.com/en-us/library/office/dn458791(v=exchg.150).aspx
Related
I am using exchange managed API and using push notification.
I am using below code
Uri uri = new Uri("http://domain.io/MyPage.aspx");
PushSubscription ps = service.SubscribeToPushNotifications(folder, uri, 1, "", EventType.Created, EventType.Modified, EventType.Deleted);
Now i get a hit on domain.io/MyPage.aspx when i change a event from calendar.
But now how i process that response ?
There is limited value in request header.
how could i know that which calendar, which service this request come.
Here is my answer. Using API Call is more simple.
public HttpResponseMessage ExchangeCalendar()
{
string itemId = string.Empty;
string subscriptionId = string.Empty;
string pushResponse = "OK";
string RESPONSE_OK = string.Empty;
HttpContent requestContent = Request.Content;
string eventData = requestContent.ReadAsStringAsync().Result;
XmlDocument doc = new XmlDocument();
doc.LoadXml(eventData);
subscriptionId = GetNodeValue(doc.GetElementsByTagName("t:SubscriptionId"));
itemId = GetNodeValue(doc.GetElementsByTagName("t:ItemId"));
calendarId = GetNodeValue(doc.GetElementsByTagName("t:FolderId"));
RESPONSE_OK = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\"><soap:Body><SendNotificationResult xmlns=\"http://schemas.microsoft.com/exchange/services/2006/messages\"><SubscriptionStatus>" + pushResponse + "</SubscriptionStatus></SendNotificationResult></soap:Body></soap:Envelope>";
return new HttpResponseMessage()
{
Content = new StringContent(RESPONSE_OK, Encoding.UTF8, "text/xml")
};
}
In very basic terms, after the SubscribeToPushNotifications call returns the PushSubscription there will be a subscription id that links the folder you subscribed to. Any notifications for that folder will contain the subscription id and the ItemId, as well as the type of notification, New, Changed, Moved, etc. You will need to maintain some kind of mapping of subscription id-to-folder, and then call EWS via GetItem to find the item in question.
HTTP "POST" data with login credentials to the BASEn server using API URL, in response it is giving a status 200, OK.
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("mode", "login"),
new KeyValuePair<string, string>("user", logintxtbx.Text),
new KeyValuePair<string, string>("password", passtxtbx.Text)
};
httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync("https://xx-yyy.com/auth", new FormUrlEncodedContent(values)); var strin = response.StatusCode.ToString();
var responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show("login Success");
GetFullResponse(httpClient);
}
After validating my credentials, the server will create a session to me if i try to do "GET" HTTP by using another urls, it should gives my required data but this thing was not happening, every time iam getting "403" forbidden response.
This is the code using for "GET" data.
var uri = new Uri("https://xx-yyy.com/_ua/web/web/v1/xyz/?xyx=1431369000000&end=1431436740000&_=1431436741550");
var Response = await httpClient.GetAsync(uri);
var statusCode = Response.StatusCode;
Response.EnsureSuccessStatusCode()
var ResponseText = await Response.Content.ReadAsStringAsync();
i don't know whats wrong, i was doing.
Can any one suggest me how can i do this to be happen.
var handler = new HttpClientHandler();
var cookieContainer = handler.CookieContainer;
var client = new HttpClient(handler);
store cookies using cookieContainer and use them to authenticate the future calls using the same way as on web.
Store the cookies to the phone using IsolatedStorageSettings
Reference for more details here
How to pass post parameters in background transfer upload request for windows phone 8? I have to pass parameter to the server (post parameter name "userfile" with a file name "song.m4a" for the parameter)
// server to POST to
string url = "myserver.com/path/to/my/post";
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
//create some json string
string json = "{ \"my\" : \"json\" }";
// convert json to byte array
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
// Write the bytes to the stream
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
Try this code and read this answer
Http Post for Windows Phone 8
I am building my first windowsPhone 8.1 application ,the role of my application is to create connection with server to get information from it, so I am writing the code to do this process by sending json-rpc request to server to get some information ,I am successful to get it in first time but when I send the second request I am receiving an empty response with 404 error (page not found).
But when I call the service without https (http only) it works fine regardless how many time I call it !
public async Task<string> GetDataFromServer(string urlToCall, string JSONData,string RR)
{
string UserName = “XXXXXXX”
string Password = "XXX";
using ( var handler = new HttpClientHandler())
{
handler.Credentials = new NetworkCredential(UserName, Password);
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = null;
try
{
response = await client.PostAsync(urlToCall, new StringContent(JSONData.ToString(), Encoding.UTF8, " application/json"));
string res = response.Content.ReadAsStringAsync().Result;
Windows.UI.Popups.MessageDialog g = new Windows.UI.Popups.MessageDialog(res);
await g.ShowAsync();
return res;
}
catch (Exception ex)
{
Windows.UI.Popups.MessageDialog g = new Windows.UI.Popups.MessageDialog("Error is : " + ex.Message);
g.ShowAsync();
return "Error";
}
finally
{
response.Dispose();
client.CancelPendingRequests();
client.Dispose();
handler.Dispose();
}
}
}
Again, when call the URL of service (start with https) on first time I got response with seeked data, but second time I receive an empty response with 404 error (page not found) !!
Any help please
Please try to use this solution.
public async Task<string> SendJSONData3(string urlToCall, string JSONData)
{
string UserName = "XXXXXXXXX";
string Password = "XXXXXXXXX";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlToCall);
httpWebRequest.Credentials = new NetworkCredential(UserName, Password);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync()))
{
string json = JSONData;
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
A couple of ideas:
Do not use the .Result property. Just use await instead to avoid deadlocks.
Remove the additional space in front of the media type parameter " application/json"
Enable logging on the webserver and see if the second request arrives on the server.
Get a network trace, for example with Wireshark or Fiddler.
Try puting WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp); in your initialization code, as proposed in this answer.
I have this code to get JSON data from an API for WP8:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(mainURL.ToString());
HttpResponseMessage response = await client.GetAsync("");
string res = await response.Content.ReadAsStringAsync();
var root = await JsonConvert.DeserializeObjectAsync<Rootobject>(res);
Everything works perfectly, but when I update data on the web API from the web site and try to retrieve data again using this code it gets the old data even though accessing the URL in a browser it gets the new data.
When I debug line by line, I see that the "response" object contains the old data.
The only way I have found to fix this is to rebuild the project in this way it works.
How can I properly get the updated data?
There may be some caching involved. Tried adding some random string to the URL, like
client.BaseAddress = new Uri(mainURL.ToString()+"&random="+DateTime.Now.Ticks);
I have same kind of problem. I tried this this may be help you.
HttpWebRequest request = HttpWebRequest.CreateHttp(mainURL.ToString());
request.Method = "GET or Post";
request.BeginGetResponse(ResponseCallBack, request);
void ResponseCallBack(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
string jsonString = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Rootobject));
Rootobject yourdata= dataContractJsonSerializer.ReadObject(memoryStream) as Rootobject;
}
}
}