Getting Sharepoint-hosted app current user from within ASP.NET Web API - asp.net

i have an ASP.NET Web API which i'm using in my SharePoint-hosted app to do CRUD operations via REST. I want to get the current user's credentials (O365 account) from within my web api controllers? Is it possible? Any suggestions or referenced would be much appreciated. TIA

I was able to accomplish this by using the below code in my controller:
Uri targetWeb = new Uri(HttpContext.Request.QueryString["SPHostUrl"]);
string targetRealm = TokenHelper.GetRealmFromTargetUrl(spContext.SPHostUrl);
var responseToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, targetWeb.Authority, targetRealm);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(spContext.SPHostUrl + "_api/Web/SiteUserInfoList/Items("+ spUser.Id + ")"); // spUser.Id from spContext
request.Method = "GET";
request.Accept = "application/json;odata=verbose";
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + spContext.UserAccessTokenForSPHost);
WebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
if (dataStream == null)
{
ViewBag.res = "nothing";
}else
{
StreamReader reader = new StreamReader(dataStream);
var result = reader.ReadToEnd();
var resData = Json(result);
ViewBag.res= resData.Data; // res must be parse when using js
}
return View();
...not sure if it's the best practice but it did the job.

Related

how send Push Notification to Kindle Fire from WCF rest service

I want to send push notifications to Kindle Fire from WCF rest service.
I used PushSharp library, but it is not working properly. Can you please suggest any other way without using PushSharp library?
I am using below code to send notification on kindle it is give error 400,
private void sendNotification(String registrationID)
{
String message = "{data\": {\"NTY\":\"-1\",\"NOTY\": \"2\"}}";
String title="title";
String accessToken = "";
accessToken = UpdateAccessToken();
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create("https://api.amazon.com/messaging/registrations/" + registrationID + "/messages");
Encoding encoding = new UTF8Encoding();
string postData = "{\"data\":{\"message\":\"" + message + "\",\"title\":\"" + title + "\"},\"consolidationKey\":\"Some Key\",\"expiresAfter\":86400}";
byte[] data = encoding.GetBytes(postData);
httpWReq.ProtocolVersion = HttpVersion.Version11;
httpWReq.Method = "POST";
httpWReq.ContentType = "application/json";//charset=UTF-8";
httpWReq.Headers.Add("X-Amzn-Type-Version",
"com.amazon.device.messaging.ADMMessage#1.0");
httpWReq.Headers.Add("X-Amzn-Accept-Type",
"com.amazon.device.messaging.ADMSendResult#1.0");
httpWReq.Headers.Add(HttpRequestHeader.Authorization,
"Bearer " + accessToken);
httpWReq.ContentLength = data.Length;
Stream stream = httpWReq.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string s = response.ToString();
StreamReader reader = new StreamReader(response.GetResponseStream());
String jsonresponse = "";
String temp = null;
while ((temp = reader.ReadLine()) != null)
{
jsonresponse += temp;
}
}
PushSharp relies on Google Cloud Messaging for Android, which is not supported on Kindle. You would need to either implement an Amazon Device Messaging (ADM) version (https://developer.amazon.com/public/apis/engage/device-messaging) or take advantage of Amazon's Simple Notification Service (SNS) to target Kindle and other platforms (https://aws.amazon.com/sns/)

Embed DocuSign Signing Experience in a .NET Application

I am working in a .NET Web Application(Web Forms).I need to embed the document signing experience into my web application,preferably by means of an Iframe.
Is is possible to authenticate to docusign from the web application and then bring the signing experience in an Iframe?
Also is it possible to re-direct to a custom URL on signing complete,signing declined,window closed..etc?
This is a copy of the API walkthrough on how to do embedded signing in C#. You can find other walkthroughs here: http://iodocs.docusign.com/APIWalkthroughs.
The code below should do exactly what you are looking for - give you an authenticated IFRAME ready for signing. Before using this you should create a template with your document and place the signature tabs in the places where you want someone to sign.
// DocuSign API Walkthrough 08 in C# - Embedded Signing
// To run this sample:
// 1) Create a new .NET project.
// 2) Add 3 assembly references to the project: System, System.Net, and System.XML
// 3) Update the username, password, integrator key, and templateId in the code
// 4) Compile and Run
//
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Text;
namespace APIWalkthrough08
{
public class EmbeddedSigning
{
// Enter your info:
static string username = "***";
static string password = "***";
static string integratorKey = "***";
static string templateId = "***";
static string roleName = "***";
public static void Main ()
{
string url = "https://demo.docusign.net/restapi/v2/login_information";
string baseURL = ""; // we will retrieve this
string accountId = ""; // will retrieve
string envelopeId = ""; // will retrieve
string uri = ""; // will retrieve
string authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + username + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" +
"</DocuSignCredentials>";
//
// STEP 1 - Login
//
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
request.Headers.Add ("X-DocuSign-Authentication", authenticateStr);
request.Accept = "application/xml";
request.Method = "GET";
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse ();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string responseText = sr.ReadToEnd();
using (XmlReader reader = XmlReader.Create(new StringReader(responseText))) {
while (reader.Read()) { // Parse the xml response body
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "accountId"))
accountId = reader.ReadString();
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "baseUrl"))
baseURL = reader.ReadString();
}
}
//--- display results
Console.WriteLine("accountId = " + accountId + "\nbaseUrl = " + baseURL);
//
// STEP 2 - Request Envelope Result
//
// Construct an outgoing XML request body
string requestBody = "<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">" +
"<accountId>" + accountId + "</accountId>" +
"<status>sent</status>" +
"<emailSubject>API Call for Embedded Sending</emailSubject>" +
"<emailBlurb>This comes from C#</emailBlurb>" +
"<templateId>" + templateId + "</templateId>" +
"<templateRoles>" +
"<templateRole>" +
"<email>" + username + "</email>" + // NOTE: Use different email address if username provided in non-email format!
"<name>Name</name>" + // username can be in email format or an actual ID string
"<roleName>" + roleName + "</roleName>" +
"<clientUserId>1</clientUserId>" +
"</templateRole>" +
"</templateRoles>" +
"</envelopeDefinition>";
// append "/envelopes" to baseUrl and use in the request
request = (HttpWebRequest)WebRequest.Create (baseURL + "/envelopes");
request.Headers.Add ("X-DocuSign-Authentication", authenticateStr);
request.ContentType = "application/xml";
request.Accept = "application/xml";
request.ContentLength = requestBody.Length;
request.Method = "POST";
// write the body of the request
byte[] body = System.Text.Encoding.UTF8.GetBytes (requestBody);
Stream dataStream = request.GetRequestStream ();
dataStream.Write (body, 0, requestBody.Length);
dataStream.Close ();
// read the response
webResponse = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(webResponse.GetResponseStream());
responseText = sr.ReadToEnd();
using (XmlReader reader = XmlReader.Create(new StringReader(responseText))) {
while (reader.Read()) { // Parse the xml response body
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "envelopeId"))
envelopeId = reader.ReadString();
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "uri"))
uri = reader.ReadString();
}
}
//--- display results
Console.WriteLine("Envelope sent!. EnvelopeId is --> " + envelopeId);
//
// STEP 3 - Get the Embedded Console Sign View
//
// construct another outgoing XML request body
string reqBody = "<recipientViewRequest xmlns=\"http://www.docusign.com/restapi\">" +
"<authenticationMethod>email</authenticationMethod>" +
"<email>" + username + "</email>" + // NOTE: Use different email address if username provided in non-email format!
"<returnUrl>http://www.docusign.com</returnUrl>" + // username can be in email format or an actual ID string
"<clientUserId>1</clientUserId>" +
"<userName>Name</userName>" +
"</recipientViewRequest>";
// append uri + "/views/recipient" to baseUrl and use in the request
request = (HttpWebRequest)WebRequest.Create (baseURL + uri + "/views/recipient");
request.Headers.Add ("X-DocuSign-Authentication", authenticateStr);
request.ContentType = "application/xml";
request.Accept = "application/xml";
request.ContentLength = reqBody.Length;
request.Method = "POST";
// write the body of the request
byte[] body2 = System.Text.Encoding.UTF8.GetBytes (reqBody);
Stream dataStream2 = request.GetRequestStream ();
dataStream2.Write (body2, 0, reqBody.Length);
dataStream2.Close ();
// read the response
webResponse = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(webResponse.GetResponseStream());
responseText = sr.ReadToEnd();
using (XmlReader reader = XmlReader.Create(new StringReader(responseText))) {
while (reader.Read()) { // Parse the xml response body
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "url"))
url = reader.ReadString();
}
}
Console.WriteLine("Embeded View Result --> " + responseText);
System.Diagnostics.Process.Start(url);
}
catch (WebException e) {
using (WebResponse response = e.Response) {
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
Console.WriteLine(text);
}
}
}
} // end main()
} // end class
} // end namespace
If you haven't already done so, I'd suggest that you review the DocuSign REST API Guide: http://www.docusign.com/sites/default/files/REST_API_Guide_v2.pdf -- as it contains all the information you need to accomplish your goals (in greater detail than I'll describe here).
To create/send an Envelope via the REST API, you'll use POST /accounts/{accountId}/envelopes, as described in the "Send an Envelope or Create a Draft Envelope" section of the API guide. For each recipient whom you'll want to sign embedded/captive within your application, be sure to set the clientUserId property for the recipient -- the presence of this property for a recipient in the Create Envelope request is what tells DocuSign that your application will be initiating/facilitating the signing experience for the Recipient (so DocuSign won't send a signing invitation email to the Recipient).
When it's time for the Recipient to view/sign the Envelope within your application, you'll use POST /accounts/{accountId}/envelopes/{envelopeId}/views/recipient, as described in the "POST Recipient View" section of the API guide -- to retrieve a URL that can be used to launch/initiate the Recipient's DocuSign signing session. Using this URL as the target of an iFrame will present the DocuSign signing session within the frame. In the POST Recipient View request, you set the returnUrl property to indicate where DocuSign should redirect the signer when their embedded/captive signing session is complete. DocuSign will append a querystring parameter ("event") when redirecting to this URL, and the value of that parameter will indicate the outcome of the Signing session. The returnUrl parameter description on page 167 of the API guide lists the possible values of this parameter. Your application (i.e., the redirect page you specify) can interrogate this parameter value to know the outcome of the signing session, and take whatever action is necessary.
Regarding authentication -- the information used to authenticate the Sender of the Envelope is supplied via the X-DocuSign-Authentication header of each API request. Additionally, a specific form of authentication can be specified for each Recipient -- for example, Access Code, Phone Authentication, ID Check, SMS Auth -- you can specify authentication method for each Recipient by setting the appropriate properties for each Recipient in the "Create Envelope" request. (The API Guide contains info about these properties.)

REST WEBAPI POST method with parameters not being called

I have built a REST API with a controller having a POST method with 4 parameters like this-
[HttpPost]
public void SaveSession([FromBody] string userId, [FromBody] DateTime issueDateTime, [FromBody] string browserType, [FromBody] string salt)
{
// Params need to be changed
_sessionService.SaveSession(userId, issueDateTime, browserType, salt);
}
How should I POST data on the client side, I mean what should be the format of the data to be sent?
I tried this format-
"userId=abc&DateTime=someDatetime&browserType=somebrowser&salt=somesalt"
Its not working if I try this, The web service method is not even being called
Could anyone tell me the correct format?
EDIT:
Here is how I am calling the API-
const string endPoint = #"http://localhost:85/session/Test";
var postData = "userId=abc&DateTime=someDatetime&browserType=somebrowser&salt=somesalt"
var request = (HttpWebRequest) WebRequest.Create(EndPoint + parameters);
request.Method = "POST";
request.ContentLength = 0;
request.ContentType = "application/x-www-form-urlencoded";
if (!string.IsNullOrEmpty(postData) && Method == HttpVerb.POST)
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(postData);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse) request.GetResponse())
{
var xmlDoc = new XmlDocument();
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
xmlDoc.Load(responseStream);
}
return (xmlDoc);
}
Thanks!
I assume routing has been properly configured.
Said so.... DateTime parameter in the controller method has been named "issueDateTime" while within the request has been named "DateTime".
I got to know, what mistake I was doing. I was sending 4 parameters in a WebService method. We can only send one parameter while calling a web service method. If you want to send multiple data, just send it as an object. Like this -
[HttpPost]
public void SaveSession([FromBody] Values value)
{
var userId = values.userId,
var issueDateTime= values.issueDateTime,
var browserType= values.browserType,
var salt= values.salt,
_sessionService.SaveSession(userId, issueDateTime, browserType, salt);
}

How to call web API in WPF 4.0

I wants to call web API in my WPF 4.0 application , where API receive request in JSON format & send response in JSON format.
I got the solution to call web API in WPF 4.5 from here http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-wpf-application
but i want same kind of solution in WPF 4.0
please help me
you have to install the NuGet package manager and the Http client libraries. This should work:
http://www.codeproject.com/Articles/611176/CallingplusASP-NetplusWebAPIplususingplusHttpClien
public T CallWebAPi<T>(string userName, string password, Uri url, out bool isSuccessStatusCode)
{
T result = default(T);
using (HttpClient client = new HttpClient())
{
client.BaseAddress = url;
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password))));
HttpResponseMessage response = client.GetAsync(url).Result;
isSuccessStatusCode = response.IsSuccessStatusCode;
var JavaScriptSerializer = new JavaScriptSerializer();
if (isSuccessStatusCode)
{
var dataobj = response.Content.ReadAsStringAsync();
result = JavaScriptSerializer.Deserialize<T>(dataobj.Result);
}
else if (Convert.ToString(response.StatusCode) != "InternalServerError")
{
result = JavaScriptSerializer.Deserialize<T>("{ \"APIMessage\":\"" + response.ReasonPhrase + "\" }");
}
else
{
result = JavaScriptSerializer.Deserialize<T>("{ \"APIMessage\":\"InternalServerError\" }");
}
}
return result;
}

Serializing using protobuf-net and sending as postdata in http

I'm using Protobuf-net to try and send a serialized object to a webapplication that I'm running in another project. The Serializer.Serialize<T>() method takes a Stream (to write to) and and instance of T (in this case, a list of a few objects that I set up to work with protobuf-net)
How do I go about doing this? Do I need to write to a file or can I send the stream as postdata somehow? Below you can see I'm using a string as the postdata.
My execute post method
public static void ExecuteHttpWebPostRequest(Uri uri,string postdata, int requestTimeOut, ref string responseContent)
{
if (string.IsNullOrEmpty(uri.Host))// || !IsConnectedToInternet(uri))
return;
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(postdata);
httpWebReq.Timeout = requestTimeOut*1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
//httpWebReq.ContentType = "text/xml;charset=utf-8";
httpWebReq.ContentType = "application/octet-stream";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
// Get the stream associated with the response.
var receiveStream = httpWebResponse.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
var readStream = new StreamReader(receiveStream,Encoding.Default);
responseContent = readStream.ReadToEnd();
httpWebResponse.Close();
}
You can just serialize to the request:
Serializer.Serialize(dataStream, obj);
And equally, you can deserialize from receiveStream, if you choose.
Note, however, that protobuf data is not text, and should not be treated as such - very bad things happen if you try that.

Resources