Google voice call error - asp.net

namespace GoogleVoiceCall
{
class Program
{
private const string LOGIN_URL = "https://www.google.com/accounts/ServiceLoginAuth?service=grandcentral";
private const string GOOGLE_VOICE_HOME_URL = "https://www.google.com/voice";
private const string CALL_URL = "https://www.google.com/voice/call/connect";
private static string m_emailAddress = "your email address";
private static string m_password = "password";
private static string m_gizmoNumber = "your gizmo number";
private static string m_destinationNumber = "your destination number";
static void Main(string[] args)
{
try
{
Console.WriteLine("Attempting Google Voice Call");
CookieContainer cookies = new CookieContainer();
// First send a login request to get the necessary cookies.
string loginData = "Email=" + Uri.EscapeDataString(m_emailAddress)
+ "&Passwd=" + Uri.EscapeDataString(m_password);
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(LOGIN_URL);
loginRequest.CookieContainer = cookies;
loginRequest.AllowAutoRedirect = true;
loginRequest.Method = "POST";
loginRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
loginRequest.ContentLength = loginData.Length;
loginRequest.GetRequestStream().Write(Encoding.UTF8.GetBytes(loginData), 0, loginData.Length);
HttpWebResponse loginResponse = (HttpWebResponse)loginRequest.GetResponse();
if (loginResponse.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("Login failed.");
}
else
{
Console.WriteLine("Login request was successful.");
}
// Second send a request to the Google Voice home page to get a string key needed when placing a callback.
HttpWebRequest keyRequest = (HttpWebRequest)WebRequest.Create(GOOGLE_VOICE_HOME_URL);
keyRequest.CookieContainer = cookies;
HttpWebResponse keyResponse = (HttpWebResponse)keyRequest.GetResponse();
if (keyResponse.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("_rnr_se key request failed.");
}
else
{
Console.WriteLine("Key request was successful.");
}
StreamReader reader = new StreamReader(keyResponse.GetResponseStream());
string keyResponseHTML = reader.ReadToEnd();
Match rnrMatch = Regex.Match(keyResponseHTML, #"name=""_rnr_se"".*?value=""(?<rnrvalue>.*?)""");
if (!rnrMatch.Success)
{
throw new ApplicationException("_rnr_se key was not found on your Google Voice home page.");
}
string rnr = rnrMatch.Result("${rnrvalue}");
Console.WriteLine("_rnr_se key=" + rnr);
// Thirdly (and lastly) submit the request to initiate the callback.
string callData = "outgoingNumber=" + Uri.EscapeDataString(m_destinationNumber) +
"&forwardingNumber=" + Uri.EscapeDataString(m_gizmoNumber) +
"&subscriberNumber=undefined&remember=0&_rnr_se=" + Uri.EscapeDataString(rnr);
HttpWebRequest callRequest = (HttpWebRequest)WebRequest.Create(CALL_URL);
callRequest.CookieContainer = cookies;
callRequest.Method = "POST";
callRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
callRequest.ContentLength = callData.Length;
callRequest.GetRequestStream().Write(Encoding.UTF8.GetBytes(callData), 0, callData.Length);
HttpWebResponse callResponse = (HttpWebResponse)callRequest.GetResponse();
if (callResponse.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Call request failed.");
}
else
{
Console.WriteLine("Call request was successful.");
}
}
catch (Exception excp)
{
Console.WriteLine("Exception Main. " + excp.Message);
}
finally
{
Console.WriteLine("finished, press any key to exit...");
Console.ReadLine();
}
}
}
}
I have used the above codes for make a call like Googl voice call using Google voicall service, but i am getting an error. error is
_rnr_se key was not found
pelase tell here what are this
m_gizmoNumber and _rnr_se key

add this line before login request :
m_cookies.Add(new Uri(PRE_LOGIN_URL), galxResponse.Cookies);
see here .

Related

ASP.NET WEB API cant upload multipart/form-data (image) to Web server

After uploading image through ASP.NET WEB API successfuly through localhost . I uploaded my project to the hosting server but this time i got the error as
an error has occured
This is my controller
tutorEntities entities = new tutorEntities();
[HttpPost]
public HttpResponseMessage ImageUp()
{
var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
img std = new img();
// std.Title = httpContext.Request.Form["Title"];
// std.RollNo = httpContext.Request.Form["RollNo"];
// std.Semester = httpContext.Request.Form["Semester"];
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
string random = Guid.NewGuid().ToString();
string url = "/UserImage/" + random + httpRequest.Files[0].FileName.Substring(httpRequest.Files[0].FileName.LastIndexOf('.'));
Console.WriteLine(url);
string path = System.Web.Hosting.HostingEnvironment.MapPath(url);
httpRequest.Files[0].SaveAs(path);
std.Path = "http://localhost:2541/" + url;
}
entities.imgs.Add(std);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
Ensure that AppPoolIdentity user has write permissions on the UserImage folder. Also, catch the exception in code for debugging:
try {
var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
img std = new img();
// std.Title = httpContext.Request.Form["Title"];
// std.RollNo = httpContext.Request.Form["RollNo"];
// std.Semester = httpContext.Request.Form["Semester"];
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
string random = Guid.NewGuid().ToString();
string url = "/UserImage/" + random + httpRequest.Files[0].FileName.Substring(httpRequest.Files[0].FileName.LastIndexOf('.'));
Console.WriteLine(url);
string path = System.Web.Hosting.HostingEnvironment.MapPath(url);
httpRequest.Files[0].SaveAs(path);
std.Path = "http://localhost:2541/" + url;
}
entities.imgs.Add(std);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
catch(Exception ex) {
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(ex.ToString()),
ReasonPhrase = "Error"
}
throw new HttpResponseException(response);
}

FCM PushNotification to iOS device from .NET

Is it possible to use Firebase's FCM to send apns push notifications to an ios device?
Desired Workflow:
iOS app sends request to my .NET server to provide it the push token. My .NET server will handle all push notifications. So I assume this would be http requests to firebase and firebase would send out the notification?
Is this workflow possible?
I have worked with Android Applications using Firebase's FCM.. so i think there must be way to work with ios.
here is the snippet of code for sending push notification using fcm in c#.
NotifBooking objnotif = new NotifBooking();
string ApplicationID = "AIzaSyCBM20ZXXXXXXXXXXjog3Abv88";
string SENDER_ID = "962XXXXXXX";
var value = "Alert :" + Message + ""; //message text box
WebRequest tRequest;
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}", ApplicationID)); tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
tRequest.ContentType = "application/json";
var data1 = new
{
to = "" + dt.Rows[i]["RegId"].ToString().Trim() + "",//Device RegID
priority = "high",
notification = new
{
body = Message,
title = Heading,
is_background = true,
image = "abc.com/images/1_icon.png",
appicon = "abc.com/images/1_icon.png",
sound = "default"
},
data = new
{
//body = Message,
//is_background=false,
//title = "Test FCM",
//appicon = "myicon",
image = "abc.com/images/1_icon.png"
},
};
Console.WriteLine(data1);
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data1);
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();
string str = sResponseFromServer;
}
}
}
}
objnotif.data = json;
}
You should get device token from Firebase and register the current user in backend side with the same token.
After that, you can send push notifications from your backend.
Put this code in AppDelegate class.
Call InitAPNS() from FinishedLaunching.
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
//TODO: save token and register one in backend side
Settings.DeviceTokenFCM = InstanceId.SharedInstance.Token;
}
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
ShowPushMessage(userInfo);
}
private void ShowPushMessage(NSDictionary userInfo)
{
if (userInfo != null)
{
try
{
var apsDictionary = userInfo["aps"] as NSDictionary;
var alertDictionary = apsDictionary?["alert"] as NSDictionary;
var body = alertDictionary?["body"].ToString();
var title = alertDictionary?["title"].ToString();
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
var alert = UIAlertController.Create(title, body, UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, null));
vc.PresentViewController(alert, animated: true, completionHandler: null);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
private void InitAPNS()
{
// Monitor token generation
InstanceId.Notifications.ObserveTokenRefresh(TokenRefreshNotification);
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Sound, (granted, error) =>
{
if (granted)
{
InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
}
});
}
else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
else
{
UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
}
Firebase.Core.App.Configure();
}
private void TokenRefreshNotification(object sender, NSNotificationEventArgs e)
{
ConnectToFCM();
}
private void ConnectToFCM()
{
var tokenFirebase = InstanceId.SharedInstance.Token;
////registation token in background thread
System.Threading.Tasks.Task.Run(() =>
{
if (!string.IsNullOrEmpty(tokenFirebase))
{
Firebase.CloudMessaging.Messaging.SharedInstance.SetApnsToken(tokenFirebase, ApnsTokenType.Production);
}
});
Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
}
IOS push Notification using C#.I have worked with Android Applications using Firebase's FCM.here is the snippet of code for sending push notification using fcm in c#.
**
namespace push
{
public partial class pushios : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SendPushNotification(txtDeviceToken.Text, txtMessage.Text);
}
private void SendPushNotification(string deviceToken,string message)
{
try
{
//Get Certificate
var appleCert = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Files/Certificate/IOS/Production_Certificate.p12"));
// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, "1234567890");
// Create a new broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
string desc = $"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
Console.WriteLine(desc);
Label1.Text = desc;
}
else
{
string desc = $"Apple Notification Failed for some unknown reason : {ex.InnerException}";
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine(desc);
Label1.Text = desc;
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) =>
{
Label1.Text = "Apple Notification Sent successfully!";
};
var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
{
};
apnsBroker.Start();
if (deviceToken != "")
{
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload = JObject.Parse(("{\"aps\":{\"badge\":1,\"sound\":\"oven.caf\",\"alert\":\"" + (message + "\"}}")))
});
}
apnsBroker.Stop();
}
catch (Exception)
{
throw;
}
}
}
**
I have worked with Android Applications using Firebase's FCM..
namespace pushios.Controllers
{
public class HomeController : ApiController
{
[HttpGet]
[Route("sendmessage")]
public IHttpActionResult SendMessage()
{
var data = new {
to = "xxxxxxxxxxxxxxxxxxx",
data = new
{
body="Test",
confId= "6565",
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;
}
}
}
}
```

how to make a web application in .NET send notifications to firebase? [duplicate]

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

Problems with downloading copies of signed documents on my server through the docusign rest api

I am using docusign rest api in my asp.net mvc application. I uploaded a .docx file to docusign. After signing, i am downloading this file . It gets downloaded as .docx file itself. But not able to open it. When I open the same file with adobe reader, it can be opened as pdf file. Can anyone help me to download the signed document as pdf so that i can open it easily?
static string email = "****"; // your account email
static string password = "****"; // your account password
static string integratorKey = "******";
static string recipientName = "***";
static string documentName = "test1.docx";
static string baseURL = "";
public void UploadtoDocuSign(int DocId, string DocName, int ObjectTypeId, int ObjectId)
{
try
{
User _dealuser = _imanageVacancy.GetDealById(ObjectId).LeadUser;
string recipientName = _dealuser.FirstName + " " + _dealuser.LastName; // provide a recipient (signer's) name
string documentName = DocName;
string recipientEmail = _dealuser.EmailAddress;
string sectionname = "";
DocumentManager _docmanager = GetDocumentById(DocId);
if (_docmanager.SectionID != null)
sectionname = "\\" + GetSectionName_additionalDoc((int)_docmanager.SectionID);
string FileNameWithPath = CommonFunctions.ConfigReader.GetConfigValue("appSettings", "FileUploadPath") + "\\Documents\\" + EnumsNeeded.VacancySubMenu.Deal.ToString() + "\\" + ObjectId + sectionname + "\\" + documentName;
//============================================================================
// STEP 1 - Login API Call (used to retrieve your baseUrl)
//============================================================================
// Endpoint for Login api call (in demo environment):
string url = "https://demo.docusign.net/restapi/v2/login_information";
// set request url, method, and headers. No body needed for login api call
HttpWebRequest request = initializeRequest(url, "GET", null, email, password);
// read the http response
string response = getResponseBody(request);
// parse baseUrl from response body
baseURL = parseDataFromResponse(response, "baseUrl");
//============================================================================
// STEP 2 - Send Signature Request from Template
//============================================================================
/*
This is the only DocuSign API call that requires a "multipart/form-data" content type. We will be
constructing a request body in the following format (each newline is a CRLF):
--AAA
Content-Type: application/xml
Content-Disposition: form-data
<XML BODY GOES HERE>
--AAA
Content-Type:application/pdf
Content-Disposition: file; filename="document.pdf"; documentid=1
<DOCUMENT BYTES GO HERE>
--AAA--
*/
// append "/envelopes" to baseURL and use for signature request api call
url = baseURL + "/envelopes";
// construct an outgoing XML formatted request body (JSON also accepted)
// .. following body adds one signer and places a signature tab 100 pixels to the right
// and 100 pixels down from the top left corner of the document you supply
string xmlBody =
"<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">" +
"<emailSubject>DocuSign API - Signature Request on Document</emailSubject>" +
"<status>sent</status>" + // "sent" to send immediately, "created" to save as draft in your account
// add document(s)
"<documents>" +
"<document>" +
"<documentId>1</documentId>" +
"<name>" + documentName + "</name>" +
"</document>" +
"</documents>" +
// add recipient(s)
"<recipients>" +
"<signers>" +
"<signer>" +
"<recipientId>1</recipientId>" +
"<email>" + recipientEmail + "</email>" +
"<name>" + recipientName + "</name>" +
"<tabs>" +
"<signHereTabs>" +
"<signHere>" +
"<xPosition>100</xPosition>" + // default unit is pixels
"<yPosition>100</yPosition>" + // default unit is pixels
"<documentId>1</documentId>" +
"<pageNumber>4</pageNumber>" +
"</signHere>" +
"</signHereTabs>" +
"</tabs>" +
"</signer>" +
"</signers>" +
"</recipients>" +
"</envelopeDefinition>";
// set request url, method, headers. Don't set the body yet, we'll set that separelty after
// we read the document bytes and configure the rest of the multipart/form-data request
request = initializeRequest(url, "POST", null, email, password);
// some extra config for this api call
configureMultiPartFormDataRequest(request, xmlBody, documentName, FileNameWithPath);
// read the http response
response = getResponseBody(request);
string envelopeId = parseDataFromResponse(response, "envelopeId");
_docmanager.DocuSignReferenceId = envelopeId;
_docmanager.DocuSignStatus = "Sent";
_iDocRep.Update(_docmanager);
_unitOfWork.Commit();
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
}
}
}
}
public void DocuSignDownload()
{
try
{
//============================================================================
// STEP 1 - Login API Call (used to retrieve your baseUrl)
//============================================================================
// Endpoint for Login api call (in demo environment):
string url = "https://demo.docusign.net/restapi/v2/login_information";
// set request url, method, and headers. No body needed for login api call
HttpWebRequest request = initializeRequest(url, "GET", null, email, password);
// read the http response
string response = getResponseBody(request);
// parse baseUrl from response body
baseURL = parseDataFromResponse(response, "baseUrl");
//============================================================================
// STEP 2 - Get Statuses of a set of envelopes
//============================================================================
//*** This example gets statuses of all envelopes in your account going back 1 month...
int curr_month = System.DateTime.Now.Month;
int curr_day = System.DateTime.Now.Day;
int curr_year = System.DateTime.Now.Year;
if (curr_month != 1)
{
curr_month -= 1;
}
else
{ // special case for january
curr_month = 12;
curr_year -= 1;
}
// append "/envelopes?from_date=MONTH/DAY/YEAR" and use in get statuses api call
// we need to URL encode the slash (/) chars, whos URL encoding is: %2F
url = baseURL + "/envelopes?from_date=" + curr_month.ToString() + "%2F" + curr_day.ToString() + "%2F" + curr_year.ToString();
// set request url, method, and headers. No request body for this api call...
request = initializeRequest(url, "GET", null, email, password);
// read the http response
response = getResponseBody(request);
string ComplenvIds = CompletedenvelopeIds(response);
ComplenvIds = ComplenvIds.TrimEnd(',');
string[] envIds = ComplenvIds.Split(',');
foreach (var envid in envIds)
{
DocumentManager _doc = _iDocRep.Get(x => x.DocuSignReferenceId == envid);
if (_doc != null)
{
DownloadCompletedEnvelopes(envid, _doc);
_doc.DocuSignStatus = "Completed";
_iDocRep.Update(_doc);
_unitOfWork.Commit();
}
}
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
}
}
}
}
public void DownloadCompletedEnvelopes(string envId, DocumentManager doc)
{
try
{
//============================================================================
// STEP 1 - Login API Call (used to retrieve your baseUrl)
//============================================================================
// Endpoint for Login api call (in demo environment):
string url = "https://demo.docusign.net/restapi/v2/login_information";
// set request url, method, and headers. No body needed for login api call
HttpWebRequest request = initializeRequest(url, "GET", null, email, password);
// read the http response
string response = getResponseBody(request);
// parse baseUrl from response body
baseURL = parseDataFromResponse(response, "baseUrl");
//============================================================================
// STEP 2 - Get Envelope Document(s) List and Info
//============================================================================
// append "/envelopes/{envelopeId}/documents" to to baseUrl and use for next endpoint
url = baseURL + "/envelopes/" + envId + "/documents";
//url = baseURL + "/envelopes/";
// set request url, method, body, and headers
request = initializeRequest(url, "GET", null, email, password);
// read the http response
response = getResponseBody(request);
// store each document name and uri locally, so that we can subsequently download each one
Dictionary<string, string> docsList = new Dictionary<string, string>();
string uri, name;
using (XmlReader reader = XmlReader.Create(new StringReader(response)))
{
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "envelopeDocument"))
{
XmlReader reader2 = reader.ReadSubtree();
uri = ""; name = "";
while (reader2.Read())
{
if ((reader2.NodeType == XmlNodeType.Element) && (reader2.Name == "name"))
{
name = reader2.ReadString();
}
if ((reader2.NodeType == XmlNodeType.Element) && (reader2.Name == "uri"))
{
uri = reader2.ReadString();
}
}// end while
docsList.Add(name, uri);
}
}
}
//============================================================================
// STEP 3 - Download the Document(s)
//============================================================================
//string envelopeID = "Some EnvelopeID";
//EnvelopePDF envPDF = apiService.RequestPDF(envelopeID);
foreach (KeyValuePair<string, string> kvp in docsList)
{
// append document uri to baseUrl and use to download each document(s)
url = baseURL + kvp.Value;
// set request url, method, body, and headers
request = initializeRequest(url, "GET", null, email, password);
request.Accept = "application/pdf"; // documents are converted to PDF in the DocuSign cloud
// read the response and store into a local file:
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
string sectionname = "";
if (doc.SectionID != null)
sectionname = "\\" + GetSectionName_additionalDoc((int)doc.SectionID);
using (MemoryStream ms = new MemoryStream())
using (FileStream outfile = new FileStream(CommonFunctions.ConfigReader.GetConfigValue("appSettings", "FileUploadPath") + "\\Documents\\" + EnumsNeeded.VacancySubMenu.Deal.ToString() + "\\" + doc.ObjectID + sectionname + "\\" + kvp.Key, FileMode.Create))
{
webResponse.GetResponseStream().CopyTo(ms);
if (ms.Length > int.MaxValue)
{
throw new NotSupportedException("Cannot write a file larger than 2GB.");
}
outfile.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
}
Console.WriteLine("\nDone downloading document(s), check local directory.");
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
}
}
}
}
//***********************************************************************************************
// --- HELPER FUNCTIONS ---
//***********************************************************************************************
public static HttpWebRequest initializeRequest(string url, string method, string body, string email, string password)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
addRequestHeaders(request, email, password);
if (body != null)
addRequestBody(request, body);
return request;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void addRequestHeaders(HttpWebRequest request, string email, string password)
{
// authentication header can be in JSON or XML format. XML used for this walkthrough:
string authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + email + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" + // global (not passed)
"</DocuSignCredentials>";
request.Headers.Add("X-DocuSign-Authentication", authenticateStr);
request.Accept = "application/xml";
request.ContentType = "application/xml";
}
public static void addRequestBody(HttpWebRequest request, string requestBody)
{
// create byte array out of request body and add to the request object
byte[] body = System.Text.Encoding.UTF8.GetBytes(requestBody);
Stream dataStream = request.GetRequestStream();
dataStream.Write(body, 0, requestBody.Length);
dataStream.Close();
}
public static void configureMultiPartFormDataRequest(HttpWebRequest request, string xmlBody, string docName, string FileNameWithPath)
{
// overwrite the default content-type header and set a boundary marker
request.ContentType = "multipart/form-data; boundary=BOUNDARY";
// start building the multipart request body
string requestBodyStart = "\r\n\r\n--BOUNDARY\r\n" +
"Content-Type: application/xml\r\n" +
"Content-Disposition: form-data\r\n" +
"\r\n" +
xmlBody + "\r\n\r\n--BOUNDARY\r\n" + // our xml formatted envelopeDefinition
"Content-Type: application/pdf\r\n" +
"Content-Disposition: file; filename=\"" + docName + "\"; documentId=1\r\n" +
"\r\n";
string requestBodyEnd = "\r\n--BOUNDARY--\r\n\r\n";
// read contents of provided document into the request stream
FileStream fileStream = System.IO.File.OpenRead(FileNameWithPath);
// write the body of the request
byte[] bodyStart = System.Text.Encoding.UTF8.GetBytes(requestBodyStart.ToString());
byte[] bodyEnd = System.Text.Encoding.UTF8.GetBytes(requestBodyEnd.ToString());
Stream dataStream = request.GetRequestStream();
dataStream.Write(bodyStart, 0, requestBodyStart.ToString().Length);
// Read the file contents and write them to the request stream. We read in blocks of 4096 bytes
byte[] buf = new byte[4096];
int len;
while ((len = fileStream.Read(buf, 0, 4096)) > 0)
{
dataStream.Write(buf, 0, len);
}
dataStream.Write(bodyEnd, 0, requestBodyEnd.ToString().Length);
dataStream.Close();
}
public static string getResponseBody(HttpWebRequest request)
{
// read the response stream into a local string
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string responseText = sr.ReadToEnd();
return responseText;
}
public static string parseDataFromResponse(string response, string searchToken)
{
// look for "searchToken" in the response body and parse its value
using (XmlReader reader = XmlReader.Create(new StringReader(response)))
{
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == searchToken))
return reader.ReadString();
}
}
return null;
}
public static string CompletedenvelopeIds(string response)
{
string compenvIds = "";
string envId = "";
// look for "searchToken" in the response body and parse its value
using (XmlReader reader = XmlReader.Create(new StringReader(response)))
{
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "envelopes"))
{
XmlReader reader2 = reader.ReadSubtree();
while (reader2.Read())
{
if ((reader2.NodeType == XmlNodeType.Element) && (reader2.Name == "envelope"))
{
XmlReader reader3 = reader2.ReadSubtree();
envId = "";
while (reader3.Read())
{
if ((reader3.NodeType == XmlNodeType.Element) && (reader3.Name == "envelopeId"))
{
envId = reader3.ReadString();
}
if ((reader3.NodeType == XmlNodeType.Element) && (reader3.Name == "status"))
{
if (reader3.ReadString() == "completed")
compenvIds = string.Concat(compenvIds, envId + ",");
}
if ((reader3.NodeType == XmlNodeType.Element) && (reader3.Name == "status"))
{
DateTime date = reader3.ReadContentAsDateTime();
}
}
}
}
}
}
}
return compenvIds;
}
public List<Lookup> LookupCache()
{
List<Lookup> _lookup = (List<Lookup>)HttpContext.Current.Cache["Lookup"];
if (HttpContext.Current.Cache["Lookup"] == null)
_lookup = _imanageUser.UpdateCache();
return _lookup;
}
string GetSectionName_additionalDoc(int SectionId)
{
List<Lookup> _lookup = LookupCache();
string _section = _lookup.Find(x => x.LookupType == (int)EnumsNeeded.EnumTypes.AdditionalDocumentTypes && x.LookupId == SectionId).LookupDesc;
return _section;
}
All files that come from DocuSign are going to be .PDF files.
Your documents will be saved as the name they were uploaded as (often contain the extension). So if you're writing the file with the name that it is stored in DocuSign by DocumentPDF->Name. I would do a .Replace and replace the extension with .pdf.

Windows Phone 8 Basic Authentication

I have hosted a Windows Web API using a basic authentication header with username and password.
I'm trying to create a login form that takes a username and password and sends back a token.
so i have the following code.
I'm using a Attributed method
public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
private IPromiseRepository promiseRepository;
public BasicAuthenticationAttribute()
{
this.promiseRepository = new EFPromiseRepository(new PropellorContext());
//repository = promiseRepository;
}
public BasicAuthenticationAttribute(IPromiseRepository promiseRepository, INewsFeedRepository newsfeedRepository)
{
this.promiseRepository = promiseRepository;
}
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
else
{
string authToken = actionContext.Request.Headers.Authorization.Parameter;
string decodedToken = authToken;
// Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
string username = decodedToken.Substring(0, decodedToken.IndexOf(":"));
string password = decodedToken.Substring(decodedToken.IndexOf("^")+1);
string APIToken = decodedToken.Substring(decodedToken.IndexOf("="));
APIToken = APIToken.Replace("=", string.Empty);
password = password.Replace("=", string.Empty);
if (!string.IsNullOrEmpty(APIToken))
{
password = password.Replace(APIToken, string.Empty);
}
if (username != null && password != null)
{
try
{
var user = promiseRepository.GetUserByName(username);
var salt = user.PasswordSalt;
System.Security.Cryptography.SHA512Managed HashTool = new System.Security.Cryptography.SHA512Managed();
Byte[] PasswordAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(password, salt));
Byte[] EncryptedBytes = HashTool.ComputeHash(PasswordAsByte);
HashTool.Clear();
var hashedpass = Convert.ToBase64String(EncryptedBytes);
if (hashedpass == user.Password)
{
if (string.IsNullOrEmpty(user.APIToken))
{
String guid = System.Guid.NewGuid().ToString();
user.APIToken = guid;
promiseRepository.UpdateUser(user);
promiseRepository.Save();
}
if (user != null)
{
user = promiseRepository.GetUserByUserID(user.UserID);
HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(user), new string[] { });
base.OnActionExecuting(actionContext);
}
}
if (APIToken != null)
{
if (user.APIToken == APIToken)
{
var userbytoken = promiseRepository.GetUserByAPIToken(APIToken);
HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(userbytoken), new string[] { });
base.OnActionExecuting(actionContext);
}
}
}
catch (Exception)
{
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
base.OnActionExecuting(actionContext);
}
throw;
}
}
}
}
}
This works with Fiddler when the correct credentials are passed
I'm attempting to produce the same authentication in my windows phone application.
Passes a username and password into the basic authentication http header.
However I'm not sure how to do this after a large amount of diggging on the internet alot of the exmaples are windows phone 7 and certain methods don't exist anymore.
This is the code i have arrived at.
private void Login1_Click(object sender, RoutedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:5650/api/start");
NetworkCredential credentials = new NetworkCredential(userName.Text + ":^",password.Text + "=");
request.Credentials = credentials;
request.BeginGetResponse(new AsyncCallback(GetSomeResponse), request);
Hopefully someone can guide me into the right direction.
it should be simple in principle :(
Here is a sample using HttpClient:
public static async Task<String> Login(string username, string password)
{
HttpClient Client = new HttpClient();
Client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(StringToAscii(string.Format("{0}:{1}", username, password))));
var response = await Client.GetAsync(new Uri(new Uri("http://yourdomain.com"), "/login"));
var status= await response.Content.ReadAsAsync<String>();
return status;
}
And of course you can find the ToBase64String function on the internet. The tricky part here is the Authorization header.

Resources