XML Serialization and DeSerialization using SOAP request C# - c#

I need your help to solve my issue please give me a solution for this
I am trying a Serialize and Deserialize the Dynamic XML Data but the data was not Deserialized
These are my methods and i am using.
**Button Click Method**
protected void btnCreateSession_Click(object sender, EventArgs e)
{
//System.Threading.Thread.Sleep(2000);
tbodyException.Visible = false;//changes 9/10/12
try
{
CreateSessionRequest request = new CreateSessionRequest();
//ucClientInfo uc =
(ucClientInfo)LoadControl("~Shared/UserControls/ucClientInfo.ascx");
request.applicationId = ucClientInfo1.txtApplicationID.Text;
request.accountType = ddlAccountType.SelectedValue;
request.salesOffice =
ddlSalesoffice.SelectedItem.ToString();//txtSalesOffice.Text;
request.salesAgentId = txtAgentId.Text;
// Thiyagu 10/10/2012 added for deriving metrics by Agent and Outlet details
request.salesAgentName = txtAgentName.Text;
request.outletLocationId = txtOutletID.Text;
request.outletLocationName = txtOutletName.Text;
// Thiyagu 10/10/2012 added for deriving metrics by Agent and Outlet details
Dictionary<string, string> agentDetails = new Dictionary<string, string>();
agentDetails.Add("SubClientId", request.salesOffice);
agentDetails.Add("SalesAgentId", request.salesAgentId);
agentDetails.Add("SalesAgentName", request.salesAgentName);
Session.Add("AgentDetails", agentDetails);
ClientInfo clientinfo = new ClientInfo();
// Thiyagu 10/04/12 populating dummy app server details in client else schema
clientinfo = PreOrderingHelper.mapClientInfoDetails(clientinfo);
clientinfo.name = ucClientInfo1.txtClientName.Text;
clientinfo.clientId = ucClientInfo1.ddlClientID.SelectedValue;
GlobalVariable.ServiceClientID = ucClientInfo1.ddlClientID.SelectedValue;
request.client = clientinfo;
CreateSessionResponse response = new CreateSessionResponse();
string url = (Page.Master as TestBed).COAServiceUrl;
var token = (Page as BasePage).Token;
var _url = (Page as BasePage).AppUrl;
var _action = (Page as BasePage).Action + CurrentFlow.ToString();
bool localDebug = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["localDebug"]);
if (!localDebug)
{
//ServiceHelper<CreateSessionRequest, CreateSessionResponse> helper = new
ServiceHelper<CreateSessionRequest, CreateSessionResponse>(url);
//response = helper.CallService(request, CurrentFlow.ToString(), TcId);
var webRequest = (HttpWebRequest)CommonUtil.SendSOAPRequest(request, _url, CurrentFlow.ToString(), token, _action, false);
string result;
using (WebResponse resp = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(resp.GetResponseStream()))
{
result = rd.ReadToEnd();
response = CommonUtil.DeserializeInnerSoapObject < CreateSessionResponse(result);
}
}
}
else
{
TextReader tr = new StreamReader(#"C:\SampleXmls\CreateSessionResp.xml");
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(CreateSessionResponse), "http://verizon.com/CoFEEAnywhere/CoAServices/v1");
//response = xs.Deserialize(tr) as SoapResponse.CreateSessionResponse;
response = xs.Deserialize(tr) as CreateSessionResponse;
}
if (response != null && response.output != null &&
!string.IsNullOrEmpty(response.output.sessionId))
{
Session["sessionId"] = response.output.sessionId; // Saving it in session - Can be used elsewehere in later flows
(Page.Master.FindControl("lblGlobalSessionIDValue") as Label).Text = response.output.sessionId; // setting the bottom session area in Preordering.aspx
var masterPage = Page.Master as TestBed;
masterPage.SessionIdUpdatePanel.Update();
(Page as BasePage).SessionID = response.output.sessionId;
lblCreatedSession.Text = (Page as BasePage).SessionID;
lblSalesProfileResult.Text = "SUCCESS";
Session["ClientId"] = ucClientInfo1.ddlClientID.SelectedValue;
Session["ClientName"] = ucClientInfo1.txtClientName.Text;
Session["AppId"] = ucClientInfo1.txtApplicationID.Text;
Session["OrderType"] = ddlOrderType.SelectedValue;
Session["AccountType"] = ddlAccountType.SelectedValue;
}
}
catch (Exception ex)
{
tbodyException.Visible = true;
aExcpetion.InnerText = ex.Message + " | " + ex.InnerException != null ?
ex.InnerException.Message : string.Empty;//aExcpetion.Attributes.Add("onclick",
"OpenExceptionWindow('" + ex.InnerException + "');
}
finally
{
if (!string.IsNullOrEmpty(Session["ClientId"].ToString()) &&
Session["ClientId"].ToString() == "CETC")
{
var masterPage = Page.Master as TestBed;
masterPage.NextFlow.CommandName = FlowType.Recommended.ToString();
masterPage.NextFlow.Text = "Next";
masterPage.NextFlow.Visible = true;
}
else
{
var masterPage = Page.Master as TestBed;
masterPage.NextFlow.Visible = true;
}
}
}
** SOAP Request**
public static object SendSOAPRequest(object req, string _url, string methodName, string token, string _action, bool useSOAP12)
{
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback
(
delegate { return true; }
);
// Create the SOAP envelope
var formXml = new XmlDocument();
string soapXml = "";
soapXml = WsdlRequestToSOAP(req);
if (methodName == "GetBroadbandAvailability")
{
soapXml = soapXml.Remove(0, 21).Replace(methodName + "Request",
"gbbRequest");
}
else if (methodName == "GetQualifiedProducts")
{
soapXml = soapXml.Remove(0, 21).Replace(methodName + "Request",
"productsrequest");
}
else
{
soapXml = soapXml.Remove(0, 21).Replace(methodName + "Request", "req" +
methodName);
}
formXml.LoadXml(soapXml);
var newXml = new XmlDocument();
var rootTag = String.Format("<{0}></{0}>", methodName);
newXml.LoadXml(rootTag);
XmlNode rootNode = newXml.ImportNode(formXml.DocumentElement, true);
newXml.DocumentElement.AppendChild(rootNode);
var stringXml = #"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns=""http://some link""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<soap:Body>
{0}
</soap:Body>
</soap:Envelope>";
var s = String.Format(stringXml, newXml.InnerXml);
formXml.LoadXml(s);
// Create the web request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_url);
webRequest.Headers.Add("SOAPAction", _action ?? _url);
webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" :
"text/xml; encoding=utf-8";
webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
webRequest.Method = "POST";
webRequest.Headers.Add("Authorization", "Bearer " + token);
webRequest.Headers.Add("X-CLIENT-CERT-STATUS", "ok");
webRequest.Headers.Add("X-SUBJECT-NAME", "C=US, ST=Florida, L=Temple Terrace, O =\"Verizon Data Services.LLC\", OU=GTSAP, CN=apigee.coasvcs.verizon.com");
// Insert SOAP envelope
using (Stream stream = webRequest.GetRequestStream())
{
formXml.Save(stream);
}
return webRequest;
}
** AuthorizeRequest**
public static string AuthorizeRequest()
{
string client_id = "t1ehVqcAGYmWC8yvPapwgdZOqOjQd5oO";
string client_secret = "ICo3o8Da8BCpmXk0";
var restClient = new RestClient("https://some link / oauth / client_credential / accesstoken ? grant_type = client_credentials");
var restRequest = new RestRequest(Method.POST);
restRequest.AddHeader("Cache-Control", "no-cache");
restRequest.AddHeader("Content-Type", "application/json");
restRequest.AddParameter("client_id", client_id);
restRequest.AddParameter("client_secret", client_secret);
IRestResponse restResponse = restClient.Execute(restRequest);
var responseJson = restResponse.Content;
var token = JsonConvert.DeserializeObject<Dictionary<string, object>>
(responseJson)["access_token"].ToString();
return token;
}
** WsdlRequestToSOAP**
public static string WsdlRequestToSOAP(object Object)
{
if (Object == null)
{
throw new ArgumentException("Object can not be null");
}
try
{
var serxml = new System.Xml.Serialization.XmlSerializer(Object.GetType());
var ms = new MemoryStream();
serxml.Serialize(ms, Object);
return Encoding.UTF8.GetString(ms.ToArray());
}
catch { throw; }
}
** IndentXMLString**
public static string IndentXMLString(string xml)
{
string outXml = string.Empty;
MemoryStream ms = new MemoryStream();
// Create a XMLTextWriter that will send its output to a memory stream (file)
XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.Unicode);
XmlDocument doc = new XmlDocument();
StreamReader sr = null;`enter code here`
try
{
// Load the unformatted XML text string into an instance
// of the XML Document Object Model (DOM)
doc.LoadXml(xml);
// Set the formatting property of the XML Text Writer to indented
// the text writer is where the indenting will be performed
xtw.Formatting = System.Xml.Formatting.Indented;
// write dom xml to the xmltextwriter
doc.WriteContentTo(xtw);
// Flush the contents of the text writer
// to the memory stream, which is simply a memory file
xtw.Flush();
// set to start of the memory stream (file)
ms.Seek(0, SeekOrigin.Begin);
// create a reader to read the contents of
// the memory stream (file)
sr = new StreamReader(ms);
// return the formatted string to caller
}
catch (Exception ex)
{
}
return sr.ReadToEnd();
}
** Finally this is the DeserializeInnerSoapObject method**
public static T DeserializeInnerSoapObject<T>(string soapResponse)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(soapResponse);
var soapBody = xmlDocument.GetElementsByTagName("s:Body")[0];
string innerObject = IndentXMLString(soapBody.InnerXml); //soapBody.InnerXml;
XmlSerializer deserializer = new XmlSerializer(typeof(T), "http://some link");
using (TextReader reader = new StringReader(innerObject))
{
return (T)deserializer.Deserialize(reader);
}
}

Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string soap = File.ReadAllText(FILENAME);
StringReader sReader = new StringReader(soap);
XmlReader reader = XmlReader.Create(sReader);
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
Envelope envelope = (Envelope)serializer.Deserialize(reader);
}
}
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public Body body { get; set; }
}
public class Body
{
[XmlElement(ElementName = "CreateSessionResponse", Namespace = "http://some link")]
public CreateSessionResponse CreateSessionResponse { get; set; }
}
public class CreateSessionResponse
{
[XmlElement(ElementName = "CreateSessionResult", Namespace = "http://some link")]
public CreateSessionResult CreateSessionResult { get; set; }
}
public class CreateSessionResult
{
[XmlElement(ElementName = "output", Namespace = "http://some link")]
public Output Output { get; set; }
}
public class Output
{
[XmlElement]
public string sessionId { get; set; }
}
}

Actually this is not the answer
I have shared my output here please check with this and give me the solution for this issue
I got the Soap response like this
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CreateSessionResponse xmlns="http://some link">
<CreateSessionResult>
<output>
<sessionId>some id</sessionId>
</output>
</CreateSessionResult>
</CreateSessionResponse>
</soap:Body>
</soap:Envelope>

Related

ICloud Caldav connection to get calendars

I am trying to connect to ICloud calendars and parse events I can do that if I use the public calendar url and it works fine. However doing that I cannot update the event for that I need CalDav connection.
I am struggling as most of the examples here return 404 Not Found.
Can anyone please guide me "ICloud Caldav connection to get Calendars " in C# a sample or working example.
Keeping in mind the for the above I will only have Username and Password for the account so with that provided I have to load list of Calendar's.
Found this article very helpful in achieving the task:
Sample code:
static string calendarURI = "https://caldav.icloud.com/";
static string username = "abc#icloud.com";
static string password = "xxxx-xxxx-xxxx-xxxx";
//static string content = "<?xml version=\"1.0\" encoding=\"utf-8\"?><propfind xlmns=\"DAV:\"><allprop/></propfind>";
static string content = "<propfind xmlns='DAV:'><prop><current-user-principal/></prop></propfind>";
public async static void GetCalendars()
{
try
{
ResponseStream = ExectueMethod(username, password, calendarURI, "PROPFIND", null, content, "application/x-www-form-urlencoded","0");
XmlDocument = new XmlDocument();
XmlDocument.Load(ResponseStream);
string xmlInner = XmlDocument.InnerXml;
XmlDocument innerXmlDocument = new XmlDocument();
innerXmlDocument.LoadXml(xmlInner);
XmlNode statusCheck = innerXmlDocument.GetElementsByTagName("status")[0];
if (statusCheck != null)
{
string status = statusCheck.InnerText.Trim();
if (status == "HTTP/1.1 200 OK")
{
XmlNode tag = innerXmlDocument.GetElementsByTagName("current-user-principal")[0];
if (tag != null)
{
XmlNode taghref = tag.ChildNodes[0];
if (taghref != null)
{
string href = taghref.InnerText.Trim();
string baseUrl = "https://caldav.icloud.com" + href;
Console.WriteLine("BASSE URL :" + baseUrl);
content = "<propfind xmlns='DAV:' xmlns:cd='urn:ietf:params:xml:ns:caldav'><prop><cd:calendar-home-set/></prop></propfind>";
ResponseStream = ExectueMethod(username, password, baseUrl, "PROPFIND", null, content, "application/x-www-form-urlencoded","0");
XmlDocument = new XmlDocument();
XmlDocument.Load(ResponseStream);
xmlInner = XmlDocument.InnerXml;
innerXmlDocument = new XmlDocument();
innerXmlDocument.LoadXml(xmlInner);
tag = innerXmlDocument.GetElementsByTagName("calendar-home-set")[0];
if (tag != null)
{
taghref = tag.ChildNodes[0];
if (taghref != null)
{
string calURL = taghref.InnerText.Trim();
Console.WriteLine("CALENDER URL :" + calURL);
content = "<propfind xmlns='DAV:'><prop><displayname/><getctag />calendar-data</prop></propfind>";
ResponseStream = ExectueMethod(username, password, calURL, "PROPFIND", null, content, "application/x-www-form-urlencoded","1");
XmlDocument = new XmlDocument();
XmlDocument.Load(ResponseStream);
xmlInner = XmlDocument.InnerXml;
innerXmlDocument = new XmlDocument();
innerXmlDocument.LoadXml(xmlInner);
int xx = 0;
foreach (XmlNode row in innerXmlDocument.GetElementsByTagName("response"))
{
if (xx > 0)
{
string calhrefUrlfinal = row.InnerXml.Remove(row.InnerXml.IndexOf("</href>"));
calhrefUrlfinal = calhrefUrlfinal.Replace("<href xmlns=\"DAV:\">", "");
string Calname = row.InnerXml.Remove(row.InnerXml.IndexOf("</displayname>"));
Calname = Calname.Remove(0, Calname.IndexOf("<displayname>")).Replace("<displayname>", "").Trim();
string statusx = row.InnerXml.Remove(row.InnerXml.IndexOf("</status>"));
statusx = statusx.Remove(0, statusx.IndexOf("<status>")).Replace("<status>", "").Trim();
if (statusx == "HTTP/1.1 200 OK")
{
Console.Write("THIS IS VALID CAL!");
// ADD THIS CAL TO LIST TO SHOW!
content = "<propfind xmlns='DAV:'><prop><calendar-data/><getctag /></prop></propfind>";
ResponseStream = ExectueMethod(username, password, calhrefUrlfinal, "PROPFIND", null, content, "application/x-www-form-urlencoded", "1");
XmlDocument = new XmlDocument();
XmlDocument.Load(ResponseStream);
xmlInner = XmlDocument.InnerXml;
XmlDocument icsSoc = new XmlDocument();
icsSoc.LoadXml(xmlInner);
foreach (XmlNode ics in icsSoc.GetElementsByTagName("href"))
{
string t = ics.InnerText.Trim();
if (t.Contains(".ics"))
{
DownloadICS(t, Calname + ".ics");
break;
}
}
}
}
xx = xx + 1;
}
}
}
}
}
}
}
}
catch (Exception ex)
{ }
}
private static void DownloadICS(string pathUri, string fileNames)
{
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(username, password);
Byte[] data = request.DownloadData(pathUri);
var str = System.Text.Encoding.Default.GetString(data);
string path = "icloudCalenders\\" + fileNames.Substring(fileNames.LastIndexOf(" / ") + 1);
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
fs.Write(data, 0, data.Length);
fs.Close();
}
private static Stream ExectueMethod(string username, string password, string caldevURI, string methodName, WebHeaderCollection headers, string content, string contentType,string depth)
{
HttpWebRequest httpGetRequest = (HttpWebRequest)WebRequest.Create(caldevURI);
httpGetRequest.Credentials = new NetworkCredential(username, password);
httpGetRequest.PreAuthenticate = true;
httpGetRequest.Method = methodName;
httpGetRequest.Headers.Add("Depth", depth);
httpGetRequest.Headers.Add("Authorization", username);
//httpGetRequest.UserAgent = "DAVKit/3.0.6 (661); CalendarStore/3.0.8 (860); iCal/3.0.8 (1287); Mac OS X/10.5.8 (9L31a)";
httpGetRequest.UserAgent = "curl/7.37.0";
if (!string.IsNullOrWhiteSpace(contentType))
{
httpGetRequest.ContentType = contentType;
}
using (var streamWriter = new StreamWriter(httpGetRequest.GetRequestStream()))
{
string data = content;
streamWriter.Write(data);
}
//Stream requestStream = httpGetRequest.GetRequestStream();
//requestStream.Write(optionsArray, 0, optionsArray.Length);
//requestStream.Close();
HttpWebResponse httpGetResponse = (HttpWebResponse)httpGetRequest.GetResponse();
Stream responseStream = httpGetResponse.GetResponseStream();
return responseStream;
}

Set the Authentication Token Profile Header

I have an OpenIdConnect Server I'm connecting to an I would like to forward token data the first time logging in to be stored on the server. Currently I'm doing this to forward the access token
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function () {
log(xhr.status, JSON.parse(xhr.responseText));
}
xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
xhr.send();
I want to send the Profile Data as well but I don't know the proper header.
How can I do something like this:
xhr.setRequestHeader("Authorization-Profile", "Bearer " + user.profile);
Does anyone know the proper header so I can add these claims to the access token.
Here is an example of what we did in one of our project:
Created a common API response class as below:
public class ApiCommonResponse
{
public object Object { get; set; }
public int httpStatus { get; set; }
public string httpErrorMessage { get; set; }
}
And a generic method to call GET and POST API endpoints. This method will map the response to the supplied data model and will return you the object.
public static ApiCommonResponse GetApiData<T>(string token, T dataModel, string apiEndPoint = null)
{
var responseText = "";
var apiCommonResponse = new ApiCommonResponse();
if (apiEndPoint != null)
{
var request = (HttpWebRequest)WebRequest.Create(apiEndPoint);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
request.Headers.Add("X-Api-Version", "");
try
{
var httpResponse = (HttpWebResponse)request.GetResponse();
var stream = httpResponse.GetResponseStream();
if (stream != null)
{
using (var streamReader = new StreamReader(stream))
{
responseText = streamReader.ReadToEnd();
}
}
}
catch (WebException we)
{
var stream = we.Response.GetResponseStream();
if (stream != null)
{
var resp = new StreamReader(stream).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
throw new Exception(obj.ToString());
}
}
}
var jsonSettings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore };
apiCommonResponse.Object = JsonConvert.DeserializeObject<T>(responseText, jsonSettings);
apiCommonResponse.httpStatus = 0;
return apiCommonResponse;
}
public static ApiCommonResponse PostApiData<T>(string username, string token, T dataModel, string apiEndPoint = null)
{
var apiCommonResponse = new ApiCommonResponse();
if (apiEndPoint == null) return null;
var webRequest = WebRequest.Create(apiEndPoint);
webRequest.Method = "POST";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
webRequest.Headers.Add("X-Api-Version", "");
using (var requeststreams = webRequest.GetRequestStream())
{
using (var sw = new StreamWriter(requeststreams))
{
sw.Write(JsonConvert.SerializeObject(dataModel));
}
}
try
{
var httpStatus = (((HttpWebResponse)webRequest.GetResponse()).StatusCode);
var httpMessage = (((HttpWebResponse)webRequest.GetResponse()).StatusDescription);
using (var s = webRequest.GetResponse().GetResponseStream())
{
if (s == null) return null;
using (var sr = new StreamReader(s))
{
var responseObj = sr.ReadToEnd();
if (!string.IsNullOrEmpty(responseObj))
{
apiCommonResponse = JsonConvert.DeserializeObject<ApiCommonResponse>(responseObj);
}
}
apiCommonResponse.httpStatus = (int)httpStatus;
apiCommonResponse.httpErrorMessage = httpMessage;
apiCommonResponse.Object = apiCommonResponse.Object;
}
}
catch (WebException we)
{
var stream = we.Response.GetResponseStream();
if (stream != null)
{
var resp = new StreamReader(stream).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
throw new Exception(obj.ToString());
}
}
return apiCommonResponse;
}

Send push to Android by C# using FCM (Firebase Cloud Messaging)

I am using this code to send notification message by C# with GCM, using Winforms, Webforms, whatever. Now I want to send to FCM (Firebase Cloud Messaging). Should I update my 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() + "&registration_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;
}
}
but the GCM was changed to FCM. Is this same code to send the notification?
Where can I find the SERVER_API_KEY? Is the same solution?
firebase cloud messaging with c#:
working all .net platform (asp.net, .netmvc, .netcore)
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
//serverKey - Key from Firebase cloud messaging server
tRequest.Headers.Add(string.Format("Authorization: key={0}", "AIXXXXXX...."));
//Sender Id - From firebase project setting
tRequest.Headers.Add(string.Format("Sender: id={0}", "XXXXX.."));
tRequest.ContentType = "application/json";
var payload = new
{
to = "e8EHtMwqsZY:APA91bFUktufXdsDLdXXXXXX..........XXXXXXXXXXXXXX",
priority = "high",
content_available = true,
notification = new
{
body = "Test",
title = "Test",
badge = 1
},
data = new
{
key1 = "value1",
key2 = "value2"
}
};
string postbody = JsonConvert.SerializeObject(payload).ToString();
Byte[] byteArray = Encoding.UTF8.GetBytes(postbody);
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
if (dataStreamResponse != null) using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
//result.Response = sResponseFromServer;
}
}
}
}
Here is another approach of writing Notification Service inside ASP.Net REST API.
public async Task<bool> NotifyAsync(string to, string title, string body)
{
try
{
// Get the server key from FCM console
var serverKey = string.Format("key={0}", "Your server key - use app config");
// Get the sender id from FCM console
var senderId = string.Format("id={0}", "Your sender id - use app config");
var data = new
{
to, // Recipient device token
notification = new { title, body }
};
// Using Newtonsoft.Json
var jsonBody = JsonConvert.SerializeObject(data);
using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send"))
{
httpRequest.Headers.TryAddWithoutValidation("Authorization", serverKey);
httpRequest.Headers.TryAddWithoutValidation("Sender", senderId);
httpRequest.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
var result = await httpClient.SendAsync(httpRequest);
if (result.IsSuccessStatusCode)
{
return true;
}
else
{
// Use result.StatusCode to handle failure
// Your custom error handler here
_logger.LogError($"Error sending notification. Status Code: {result.StatusCode}");
}
}
}
}
catch (Exception ex)
{
_logger.LogError($"Exception thrown in Notify Service: {ex}");
}
return false;
}
References:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
I have posted this answer as this question was viewed most and this server side code was written in VS 2015 in C# for sending push notification either single device based on device id or subscribed topic to Xamarin Android app
public class FCMPushNotification
{
public FCMPushNotification()
{
// TODO: Add constructor logic here
}
public bool Successful
{
get;
set;
}
public string Response
{
get;
set;
}
public Exception Error
{
get;
set;
}
public FCMPushNotification SendNotification(string _title, string _message, string _topic)
{
FCMPushNotification result = new FCMPushNotification();
try
{
result.Successful = true;
result.Error = null;
// var value = message;
var requestUri = "https://fcm.googleapis.com/fcm/send";
WebRequest webRequest = WebRequest.Create(requestUri);
webRequest.Method = "POST";
webRequest.Headers.Add(string.Format("Authorization: key={0}", YOUR_FCM_SERVER_API_KEY));
webRequest.Headers.Add(string.Format("Sender: id={0}", YOUR_FCM_SENDER_ID));
webRequest.ContentType = "application/json";
var data = new
{
// to = YOUR_FCM_DEVICE_ID, // Uncoment this if you want to test for single device
to="/topics/"+_topic, // this is for topic
notification=new
{
title=_title,
body=_message,
//icon="myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
webRequest.ContentLength = byteArray.Length;
using (Stream dataStream = webRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse webResponse = webRequest.GetResponse())
{
using (Stream dataStreamResponse = webResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
result.Response = sResponseFromServer;
}
}
}
}
}
catch(Exception ex)
{
result.Successful = false;
result.Response = null;
result.Error = ex;
}
return result;
}
}
and its uses
// start sending push notification to apps
FCMPushNotification fcmPush = new FCMPushNotification();
fcmPush.SendNotification("your notificatin title", "Your body message","news");
// end push notification
Yes, you should update your code to use Firebase Messaging interface.
There's a GitHub Project for that here.
using Stimulsoft.Base.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace _WEBAPP
{
public class FireBasePush
{
private string FireBase_URL = "https://fcm.googleapis.com/fcm/send";
private string key_server;
public FireBasePush(String Key_Server)
{
this.key_server = Key_Server;
}
public dynamic SendPush(PushMessage message)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FireBase_URL);
request.Method = "POST";
request.Headers.Add("Authorization", "key=" + this.key_server);
request.ContentType = "application/json";
string json = JsonConvert.SerializeObject(message);
//json = json.Replace("content_available", "content-available");
byte[] byteArray = Encoding.UTF8.GetBytes(json);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse respuesta = (HttpWebResponse)request.GetResponse();
if (respuesta.StatusCode == HttpStatusCode.Accepted || respuesta.StatusCode == HttpStatusCode.OK || respuesta.StatusCode == HttpStatusCode.Created)
{
StreamReader read = new StreamReader(respuesta.GetResponseStream());
String result = read.ReadToEnd();
read.Close();
respuesta.Close();
dynamic stuff = JsonConvert.DeserializeObject(result);
return stuff;
}
else
{
throw new Exception("Ocurrio un error al obtener la respuesta del servidor: " + respuesta.StatusCode);
}
}
}
public class PushMessage
{
private string _to;
private PushMessageData _notification;
private dynamic _data;
private dynamic _click_action;
public dynamic data
{
get { return _data; }
set { _data = value; }
}
public string to
{
get { return _to; }
set { _to = value; }
}
public PushMessageData notification
{
get { return _notification; }
set { _notification = value; }
}
public dynamic click_action
{
get
{
return _click_action;
}
set
{
_click_action = value;
}
}
}
public class PushMessageData
{
private string _title;
private string _text;
private string _sound = "default";
//private dynamic _content_available;
private string _click_action;
public string sound
{
get { return _sound; }
set { _sound = value; }
}
public string title
{
get { return _title; }
set { _title = value; }
}
public string text
{
get { return _text; }
set { _text = value; }
}
public string click_action
{
get
{
return _click_action;
}
set
{
_click_action = value;
}
}
}
}
Based on Teste's code .. I can confirm the following works. I can't say whether or not this is "good" code, but it certainly works and could get you back up and running quickly if you ended up with GCM to FCM server problems!
public AndroidFCMPushNotificationStatus SendNotification(string serverApiKey, string senderId, string deviceId, string message)
{
AndroidFCMPushNotificationStatus result = new AndroidFCMPushNotificationStatus();
try
{
result.Successful = false;
result.Error = null;
var value = message;
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", serverApiKey));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
result.Response = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
result.Successful = false;
result.Response = null;
result.Error = ex;
}
return result;
}
public class AndroidFCMPushNotificationStatus
{
public bool Successful
{
get;
set;
}
public string Response
{
get;
set;
}
public Exception Error
{
get;
set;
}
}
You need change url from https://android.googleapis.com/gcm/send to https://fcm.googleapis.com/fcm/send and change your app library too. this tutorial can help you https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol
Try to send a json object.
Replace this:
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
For this:
tRequest.ContentType = "application/json";
var data = new
{
to = deviceId,
notification = new
{
body = "This is the message",
title = "This is the title",
icon = "myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
Here's the code for server side firebase cloud request from C# / Asp.net.
Please note that your client side should have same topic.
e.g.
FirebaseMessaging.getInstance().subscribeToTopic("news");
public String SendNotificationFromFirebaseCloud()
{
var result = "-1";
var webAddr = "https://fcm.googleapis.com/fcm/send";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization:key=" + YOUR_FIREBASE_SERVER_KEY);
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"to\": \"/topics/news\",\"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\",}}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
You can use this library, makes it seamless to send push notifications using Firebase Service from a C# backend download here
public SendNotice(int deviceType, string deviceToken, string message, int badge, int status, string sound)
{
AndroidFCMPushNotificationStatus result = new AndroidFCMPushNotificationStatus();
try
{
result.Successful = false;
result.Error = null;
var value = message;
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var serializer = new JavaScriptSerializer();
var json = "";
tRequest.Headers.Add(string.Format("Authorization: key={0}", "AA******"));
tRequest.Headers.Add(string.Format("Sender: id={0}", "11********"));
if (DeviceType == 2)
{
var body = new
{
to = deviceToken,
data = new
{
custom_notification = new
{
title = "Notification",
body = message,
sound = "default",
priority = "high",
show_in_foreground = true,
targetScreen = notificationType,//"detail",
},
},
priority = 10
};
json = serializer.Serialize(body);
}
else
{
var body = new
{
to = deviceToken,
content_available = true,
notification = new
{
title = "Notification",
body = message,
sound = "default",
show_in_foreground = true,
},
data = new
{
targetScreen = notificationType,
id = 0,
},
priority = 10
};
json = serializer.Serialize(body);
}
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
result.Response = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
result.Successful = false;
result.Response = null;
result.Error = ex;
}
}
I write this code and It's worked for me .
public static string ExcutePushNotification(string title, string msg, string fcmToken, object data)
{
var serverKey = "AAAA*******************";
var senderId = "3333333333333";
var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");
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
{
notification = new
{
title = title,
body = msg,
sound = "default"
},
data = new
{
info = data
},
to = fcmToken,
priority = "high",
content_available = true,
};
var serializer = new JavaScriptSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = serializer.Serialize(payload);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
I am using this approach and it is working fine:
public class PushNotification
{
private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// firebase
private static Uri FireBasePushNotificationsURL = new Uri("https://fcm.googleapis.com/fcm/send");
private static string ServerKey = ConfigurationManager.AppSettings["FIREBASESERVERKEY"];
public static async Task<bool> SendPushNotification(List<SendNotificationModel> notificationData)
{
try
{
bool sent = false;
foreach (var data in notificationData)
{
var messageInformation = new Message()
{
notification = new Notification()
{
title = data.Title,
text = data.Message,
ClickAction = "FCM_PLUGIN_ACTIVITY"
},
data = data.data,
priority="high",
to =data.DeviceId
};
string jsonMessage = JsonConvert.SerializeObject(messageInformation);
//Create request to Firebase API
var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);
request.Headers.TryAddWithoutValidation("Authorization", "key=" + ServerKey);
request.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
HttpResponseMessage result;
using (var client = new HttpClient())
{
result = await client.SendAsync(request);
sent = result.IsSuccessStatusCode;
}
}
return sent;
}
catch(Exception ex)
{
Logger.Error(ex);
return false;
}
}
}
Following Approach, I have used for writing Firebase Notification Service inside ASP.Net REST API.
public async Task<bool> NotifyAsync(string to, string title, string body)
{
try
{
//Server key from FCM console
var serverKey = string.Format("key={0}", "Provide your Server key here from Fibase console");
//Sender id from FCM console
var senderId = string.Format("id={0}", "Provide your Sender Id here from Firebase Console");
var data = new
{
to, // Recipient device token
notification = new { title, body }
};
// Using Newtonsoft.Json
var jsonBody = JsonConvert.SerializeObject(data);
using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send"))
{
httpRequest.Headers.TryAddWithoutValidation("Authorization", serverKey);
httpRequest.Headers.TryAddWithoutValidation("Sender", senderId);
httpRequest.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
var result = await httpClient.SendAsync(httpRequest);
if (result.IsSuccessStatusCode)
{
return true;
}
else
{
// Use result.StatusCode to handle failure
// Your custom error handler here
return false;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
Refer This blog for send Group Notification
https://firebase.google.com/docs/cloud-messaging/android/send-multiple

Toggl API v8 with .NET

I'm trying to use the new Toggl API (v8) with .NET C#. I've based my code on the example from litemedia (http://litemedia.info/connect-to-toggl-api-with-net), but it was originally created for version 1 of the API.
private const string TogglTasksUrl = "https://www.toggl.com/api/v8/tasks.json";
private const string TogglAuthUrl = "https://www.toggl.com/api/v8/me"; //sessions.json";
private const string AuthenticationType = "Basic";
private const string ApiToken = "user token goes here";
private const string Password = "api_token";
public static void Main(string[] args)
{
CookieContainer container = new CookieContainer();
var authRequest = (HttpWebRequest)HttpWebRequest.Create(TogglAuthUrl);
authRequest.Credentials = CredentialCache.DefaultCredentials;
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.CookieContainer = container;
string value = ApiToken; //= Convert.ToBase64String(Encoding.Unicode.GetBytes(ApiToken));
value = string.Format("{1}:{0}", Password, value);
//value = Convert.ToBase64String(Encoding.Unicode.GetBytes(value));
authRequest.ContentLength = value.Length;
using (StreamWriter writer = new StreamWriter(authRequest.GetRequestStream(), Encoding.ASCII))
{
writer.Write(value);
}
try
{
var authResponse = (HttpWebResponse)authRequest.GetResponse();
using (var reader = new StreamReader(authResponse.GetResponseStream(), Encoding.UTF8))
{
string content = reader.ReadToEnd();
}
HttpWebRequest tasksRequest = (HttpWebRequest)HttpWebRequest.Create(TogglTasksUrl);
tasksRequest.CookieContainer = container;
//var jsonResult = string.Empty;
var tasksResponse = (HttpWebResponse)tasksRequest.GetResponse();
MemoryStream ms = new MemoryStream();
tasksResponse.GetResponseStream().CopyTo(ms);
//using (var reader = new StreamReader(tasksResponse.GetResponseStream(), Encoding.UTF8))
//{
// jsonResult = reader.ReadToEnd();
//}
ms.Seek(0, SeekOrigin.Begin);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Task));
var tasks = ser.ReadObject(ms) as List<Task>;
ms.Close();
//var tasks = DataContractJsonConvert.DeserializeObject<Task[]>(jsonResult);
foreach (var task in tasks)
{
Console.WriteLine(
"{0} - {1}: {2} starting {3:yyyy-MM-dd HH:mm}",
task.Project.Name,
task.Description,
TimeSpan.FromSeconds(task.Duration),
task.Start);
}
}
catch (System.Exception ex)
{
throw;
}
}
The following line is returning a 404 error.
var authResponse = (HttpWebResponse)authRequest.GetResponse();
Here is code that works. Since I was looking for this answer recently there might still be others as lost as me.
Notes: I used Encoding.Default.GetBytes() because Encoding.Unicode.GetBytes() did not give me a correct result on my .NET string. I hope it doesn't depend on the default setup of Visual Studio.
The content-type is "application/json".
Sorry, I haven't tried a POST version yet.
string ApiToken = "user token goes here";
string url = "https://www.toggl.com/api/v8/me";
string userpass = ApiToken + ":api_token";
string userpassB64 = Convert.ToBase64String(Encoding.Default.GetBytes(userpass.Trim()));
string authHeader = "Basic " + userpassB64;
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(url);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "GET";
authRequest.ContentType = "application/json";
//authRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
var response = (HttpWebResponse)authRequest.GetResponse();
string result = null;
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
}
if (null != result)
{
System.Diagnostics.Debug.WriteLine(result.ToString());
}
// Get the headers
object headers = response.Headers;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.ToString());
}

Multiple HttpWebRequest in loop?

I have to call web-service multiple time (in loop) the problem is that my code always return empty object (Image Description) and doesn't run properly when I tested it separately (out of loop) it worked normally
here is my portion of code
HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(imageCollection[i].ImageTag));
httpReq.BeginGetResponse(new AsyncCallback((iar) =>
{
try
{
string strResponse = "";
var response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar);
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
strResponse = reader.ReadToEnd();
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.OptionFixNestedTags = true;
htmlDocument.LoadHtml(strResponse);
HtmlAgilityPack.HtmlNode titleNode = htmlDocument.DocumentNode.SelectSingleNode("//meta[#property='og:description']");
if (titleNode != null)
{
string desc = titleNode.GetAttributeValue("content", "");
imageCollection[i].ImageDescription = desc;
}
}
catch (Exception ex)
{
throw ex;
}
}), httpReq);
httpReq.Abort();
I got the answer from another post in stack-overflow modified to adapt my solution here
Getting the Response of a Asynchronous HttpWebRequest
I made specific class called Request to transform my logic to newly async and await here it's
public Task<string> MakeAsyncRequest()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
Task<WebResponse> task = Task.Factory.FromAsync(
request.BeginGetResponse,
asyncResult => request.EndGetResponse(asyncResult),
(object)null);
return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
}
private string ReadStreamFromResponse(WebResponse response)
{
string desc = "";
try
{
using (Stream responseStream = response.GetResponseStream())
using (StreamReader sr = new StreamReader(responseStream))
{
//Need to return this response
string strContent = sr.ReadToEnd();
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.OptionFixNestedTags = true;
htmlDocument.LoadHtml(strContent);
HtmlAgilityPack.HtmlNode titleNode = htmlDocument.DocumentNode.SelectSingleNode("//meta[#property='og:description']");
if (titleNode != null)
{
desc = titleNode.GetAttributeValue("content", "");
}
imageDesc = desc;
return desc;
}
}
catch (Exception ex)
{ return desc; }
}
public string imageDesc { get; private set; }
}
Then I made a Queue of Request
queueWebRequest = new Queue<Request>();
for (int i = 0; i < imageCollection.Count; i++)
{
queueWebRequest.Enqueue(new Request(imageCollection[i].ImageTag));
}
for (int i = 0; i < imageCollection.Count; i++)
{
if (queueWebRequest.Count > 0)
{
Request currentRequest = queueWebRequest.Dequeue();
await currentRequest.MakeAsyncRequest();
imageCollection[i].ImageDescription = currentRequest.imageDesc;
}
else
break;
}

Categories

Resources