Consuming REST Service pb - asp.net

I'm having some problem consuming REST Service and want to figure out what I'm missing in implementation.
https://<server-name-or-address>/api/sessions
if I call this rest api using cURL, it works just fine by following script
curl -i -k -H "Accept:application/*+xml;version=1.5" -u username:password -X POST https://<server-name-or-address>/api/sessions
However, it isn't working at all with C# asp.net. I'm not sure what I'm missing here. Here are my attempts:
1) Using HTTP Web Request
Uri address = new Uri(url);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/*+xml;version=1.5";
request.Credentials = new NetworkCredential(username,password);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// following exception fires on calling aforementioned statement
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
2) Using Hammock.net
Hammock.RestClient client = new Hammock.RestClient();
string encodedAPIKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
client.AddHeader("Accept", "application/*+xml;version=1.5");
client.AddHeader("Authorization", "Basic " + username + ":" + password);
client.Authority = url;
Hammock.RestRequest req = new Hammock.RestRequest();
req.Path = url;
Hammock.RestResponse response = client.Request(req);
string _result = client.Request(req).Content; // exception
3) Using RestSharp
string _loginInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
RestSharp.RestClient client = new RestSharp.RestClient();
client.AddDefaultHeader("Accept", "application/*+xml;version=1.5");
client.AddDefaultHeader("Authorization", "Basic " + _loginInfo);
client.BaseUrl = url;
RestSharp.RestRequest request = new RestSharp.RestRequest();
request.AddUrlSegment("method", "POST");
request.AddUrlSegment("uri", url);
string result = client.Execute(request).Content;
I also have tried with HttpClient, WebRequest, WebClient though nothing appears to work.

Try manually setting the Authorization header yourself in the HTTP request.
string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
request.Headers.Add("Authorization", authorization);
EDIT:
It looks as though it may be due to a self-signed, expired, or otherwise invalid cert. Try the following
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Gleaned from this SO: https://stackoverflow.com/questions/5595049/servicepointmanager-servercertificatevalidationcallback-question

Related

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

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.

can a MVC 3 app execute an Action in a different app on the same server

I have two asp.net applications running on one server, one is MVC-3, the other is not. the MVC application has a POST action which sends an email and returns a JSON object. Can the plain asp.net application somehow execute the action (from server) and receive the JSON object? I guess it just needs to execute a POST somehow?
Found the answer: It is the method HttpWebRequest, used as follows.
string data = "data to post";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("put URL here");
// set post headers
request.Method = "POST";
request.KeepAlive = true;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
System.IO.StreamWriter writer = new System.IO.StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
writer.Dispose();
// next line posts the data to the URL
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

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.)

The remote server returned an error: (400) Bad Request while consuming a WCF Service

Please view the code given below. While the debug reaches the request.GetResponse() statement the error has been thrown.
Uri uri = new Uri(address);
string data = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HasRole xmlns='http://tempuri.org/'><userName>" + sid + "</userName><role>" + role + "</role></HasRole></s:Body></s:Envelope>";
data.Replace("'", "\"");
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
if (uri.Scheme == Uri.UriSchemeHttps)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";// WebRequestMethods.Http.Post;
request.ContentLength = byteData.Length;
request.ContentType = "application/soap+xml; charset=UTF-8"; // "text/xml; charset=utf-8";
//request.ContentType = "application/x-www-form-urlencoded";
//Stream requestStream = request.GetRequestStream();
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteData, 0, byteData.Length);
}
//writer.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
Response.Close();
Response.Write(tmp);
}
I would double check the URL. If the URL looks ok on the client side, I recommend looking at access logs on your server to see what URL is being hit. 4xx errors mean a resource was not found. If the endpoint was correct, but the request was fubared, you would get a 5xx error code. (Assuming that your server side frameworks uses standard HTTP Response Codes).
As has been mentioned you should use the 'Add Service Reference' to access the WCF service from a .NET client. However, if you're emulating trying to connect from a non .NET client, your soap envelope is missing the header information.
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">
specify your action namespace here (e.g. http://tempuri.org/ISomeService/Execute)
</Action>
</s:Header>

How to send a xml file over HTTP and HTTPS protocol and get result back

i want to send xml file with userid and password over HTTPs and then send all other xml file on HTTP using POST method and get the response as a xml file back. in ASP.NET (with vb.net preferred)
The url to which i want to send my xml file is:http://www.hostelspoint.com/xml/xml.php
exect xml file pettern is:
<?xml version="1.0" encoding="UTF-8"?>
<OTA_PingRQ xmlns="http://www.opentravel.org/OTA/2003/05"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05OTA_PingRQ.xsd"
TimeStamp="2003-03-17T11:09:47-05:00"
Target="Production" Version="1.001" PrimaryLangID="en"
EchoToken="testtoken12">
<EchoData>Hello</EchoData>
</OTA_PingRQ>
You should check out the WCF REST Starter Kit, and watch the screencast on HTTP Plain XML (POX) Services which explains step by step how to do just that - create a WCF REST service that will accept and process a plain XML stream.
All the WCF and WCF REST screencasts by Pluralsight are highly recommended! It's excellent material on how to get started and work with WCF.
In addition to that, the MSDN WCF Developer Center is your first point of contact for any questions or more information on WCF and WCF REST.
i don't know why u removed correct answer from here but yesterday i got correct answer here. and it is:- (can any one tell me how to do same with HTTPS protocol?)
string targetUri = "http://www.hostelspoint.com/xml/xml.php";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\myfile.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object
XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();
}
}
Yes, you can do same thing using HTTPS protocol. You have to add this code before request:
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
bool validationResult = true;
//
// policy code here ...
//
return validationResult;
};

Resources