DocuSign API and DocumentPDFs docPDFs = apiService.RequestDocumentPDFs(envelopeID); - c#

I am using the code below to connect to DocuSign API.
WHAT AM I doing wrong, I keep getting Username and Password not correct when they are!
String auth = "<DocuSignCredentials><Username>john.connolly#lechase.com</Username><Password>password</Password><IntegratorKey>20be051c-4c25-46c1-b0f1-1f10575a2e40</IntegratorKey></DocuSignCredentials>";
DSAPIServiceSoapClient client = new DSAPIServiceSoapClient("DSAPIServiceSoap");
using (System.ServiceModel.OperationContextScope scope = new System.ServiceModel.OperationContextScope(client.InnerChannel))
{
System.ServiceModel.Channels.HttpRequestMessageProperty httpRequestProperty = new System.ServiceModel.Channels.HttpRequestMessageProperty();
httpRequestProperty.Headers.Add("X-DocuSign-Authentication", auth);
System.ServiceModel.OperationContext.Current.OutgoingMessageProperties[System.ServiceModel.Channels.HttpRequestMessageProperty.Name] = httpRequestProperty;
EnvelopeStatus status = client.RequestStatusEx("12d46951-1f1c-48cd-9a28-e51685d67ccd");
Console.Out.WriteLine("Subject: " + status.Subject);
}

Since you use the (Legacy Header Authentication uses the X-DocuSign-Authentication header):
Use the Authentication: login method
to retrieve the account number and the baseUrl for the account.
The url for the login method is www.docusign.net for production and
demo.docusign.net for the developer sandbox. The baseUrl field is
part of the loginAccount object. See the docs and the loginAccount
object
The baseUrl for the selected account, in production, will start with na1, na2, na3, eu1, or something else. Use the baseUrl that is
returned to create the basePath (see the next step.) Use the
basePath for all of your subsequent API calls.
As returned by login method, the baseUrl includes the API version and account id. Split the string to obtain the basePath, just the
server name and api name. Eg, you will receive
https://na1.docusign.net/restapi/v2/accounts/123123123. You want
just https://na1.docusign.net/restapi
Instantiate the SDK using the basePath. Eg ApiClient apiClient = new ApiClient(basePath);
Set the authentication header as shown in the examples by using Configuration.Default.AddDefaultHeader Ref.
Sample Code: Try a verbatim string for your auth string.
string auth = #"<DocuSignCredentials>
<Username>john.connolly#lechase.com</Username>
<Password>S3cre+p455w0Rd</Password>
<IntegratorKey>20be051c-4c25-46c1-b0f1-1f10575a2e40</IntegratorKey>
</DocuSignCredentials>";
DSAPIServiceSoapClient apiService = new DSAPIServiceSoapClient();
using (var scope = new System.ServiceModel.OperationContextScope(apiService.InnerChannel))
{
var httpRequestProperty = new System.ServiceModel.Channels.HttpRequestMessageProperty();
httpRequestProperty.Headers.Add("X-DocuSign-Authentication", auth);
System.ServiceModel.OperationContext.Current.OutgoingMessageProperties[System.ServiceModel.Channels.HttpRequestMessageProperty.Name] = httpRequestProperty;
EnvelopeStatus envStatus = apiService.CreateAndSendEnvelope(envelope);
return envStatus.EnvelopeID;
}

Related

How to create CallCredentials from SslCredentials and token string

I am porting a gRPC client from python to c#. Both the python client and the c# client are using the gRPC Framework from grpc.io.
The python client uses the following code to open a secure, non-authenticated channel, which it then uses to procure a token string, which it then uses to create call credentials with the grpc.composite_channel_credentials() function:
channel = grpc.secure_channel(url_server_address, ssl_creds)
stub = gateway.GatewayStub(channel)
# Acquire access token via password authentication
pw_cmd = gateway.PasswordAuthenticateCmd(account_name=url.username, password=url.password)
auth_rsp = stub.PasswordAuthenticate(pw_cmd)
# Open a secure, authenticated channel
auth_creds = grpc.access_token_call_credentials(auth_rsp.access_token)
composite_creds = grpc.composite_channel_credentials(ssl_creds, auth_creds)
channel = grpc.secure_channel(url_server_address, composite_creds)
stub = gateway.GatewayStub(channel)
In c#, I have been able to compile the protocol buffer definitions, and connect with the generated client to successfully acquire the access token:
SslCredentials secureChannel = new SslCredentials(File.ReadAllText(SSLCertificatePath));
Channel channel = new Channel(ServerURL, PortNum, secureChannel);
var client = new GrpcClient(new Grpc.Gateway.GatewayClient(channel));
var response = client.client.PasswordAuthenticate(new PasswordAuthenticateCmd() { AccountName = UserName, Password = UserPassword });
Console.WriteLine(response.AccessToken);
From here, however, I can't find the c# analog to the grpc.composite_channel_credentials() function to take the SslCredentials and the access token string to create combined credentials.
None of the examples here https://grpc.io/docs/guides/auth.html here use a token string, and I haven't been able to find any other examples out there.
What you're looking for is:
https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Core/CallCredentials.cs#L49 and https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Core/ChannelCredentials.cs#L67.
Feel free to also look at:
https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Auth/GoogleAuthInterceptors.cs#L58
I solved my problem using CallCredentials.FromInterceptor().
The grpc.access_token_call_credentials() python call adds an authorization entry to the metadata, and sets its value to "Bearer " + AccessToken, so I just had to do the same:
SslCredentials secureCredentials = new SslCredentials(File.ReadAllText(SSLCertificatePath));
Channel secureChannel = new Channel(ServerURL, PortNum, secureCredentials);
var client = new GrpcClient(new Grpc.Gateway.GatewayClient(secureChannel));
var response = client.client.PasswordAuthenticate(new PasswordAuthenticateCmd() { AccountName = UserName, Password = UserPassword });
var accessTokenCredentials = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) =>
{
metadata.Add("authorization", "Bearer " + passwordResponse.AccessToken);
return TaskUtils.CompletedTask;
}));
var authenticatedCredentials = ChannelCredentials.Create(secureCredentials, accessTokenCredentials);
Channel authenticatedChannel = new Channel(hostURL, hostPort, authenticatedCredentials);
As Jan pointed out in his answer, there is a function in the Grpc.Auth namespace that does the same thing as the function that I wrote: https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Auth/GoogleAuthInterceptors.cs#L58

How do I update tokens in a JSON file using Rest API C#

Browserstack.com have a REST API that stores the results of Automated test sessions in a JSON file.
By default it sets the status token to "done" but you can update using the REST API e.g. "passed" or "failed".
It requires Basic authorization using your username & password.
They give an example of how to do this but it's a bit messy. So I wanted a simpler way of updating the file and only the tokens I was interested in.
I was able to do this using DalSoft's RestClient application:
public static async Task DalSoft(string SessionID, string TestStatus)
{
string Uri = "https://www.browserstack.com/automate/sessions/" + SessionID +
".json";
string AuthToken = "Basic " +
Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
dynamic client = new DalSoft.RestClient.RestClient(Uri);
var status = new { status=TestStatus };
var result = await client
.Headers(new { Authorization = AuthToken })
.Patch(status);
string Myresults = result.ToString();
}
https://github.com/DalSoft/DalSoft.RestClient/issues/40#issuecomment-334219145

How to create a new Microsoft Azure HybridConnection via code?

I am using HybridConnectionNamespace and create multiple HybridConnections via Azure portal. The question is quite simple. How can I create it programmatically (Azure SDK, PowerShell scripts, etc.)?
According to this article, there are currently two different ways to create a relay namespace.
Azure portal and Azure Resource Manager templates
If you want to create it programmatically, I suggest you could use azure rest api to send the deployment templates by codes.
More details, you could refer to this article and codes:
Notice: If you want to use rest api to send request to azure, you need firstly create an Azure Active Directory application and service principal. After you generate the service principal, you could get the applicationid,access key and talentid. More details, you could refer to this article.
Rest Body(json.txt):
Notice: You need change the parameters' name and location value.
{"properties":{"mode":"incremental","debugSetting":{"detailLevel":"RequestContent, ResponseContent"},"parameters":{"name":{"value":"yourrelayname"},"location":{"value":"location"}},"template":{"$schema":"http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#","contentVersion":"1.0.0.0","parameters":{"name":{"type":"string"},"location":{"type":"string"}},"resources":[{"apiVersion":"2016-07-01","name":"[parameters('name')]","location":"[parameters('location')]","type":"Microsoft.Relay/namespaces","properties":{"namespaceType":"Relay"}}]}}}
Code:
string body = File.ReadAllText(#"D:\json.txt");
// Display the file contents to the console. Variable text is a string.
string tenantId = "tenantId";
string clientId = "clientId(applicationid)";
string clientSecret = "applicationSecret";
string subscription = "subscriptionId";
string resourcegroup = "Youresourcegroup";
string authContextURL = "https://login.windows.net/" + tenantId;
var authenticationContext = new AuthenticationContext(authContextURL);
var credential = new ClientCredential(clientId, clientSecret);
var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Resources/deployments/Microsoft.Relay?api-version=2016-07-01", subscription, resourcegroup));
request.Method = "PUT";
request.Headers["Authorization"] = "Bearer " + token;
request.ContentType = "application/json";
try
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(body);
streamWriter.Flush();
streamWriter.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//Get the response
var httpResponse = (HttpWebResponse)request.GetResponse();
Console.WriteLine(httpResponse.StatusCode);
Console.ReadLine();
Result:
Use PowerShell CmdLets | Hybrid Connection Manager:
Add-HybridConnection
Update-HybridConnection
Remove-HybridConnection
Get-HybridConnection
Set-HybridConnectionManagerConfiguration
https://msdn.microsoft.com/en-us/library/azure/dn789178.aspx
GoodLuck

using the exmple of google drive sdk for read spreadsheet

I am trying to use the google drive sdk exmple for read spread sheet.
when I am opening the example I am getting this error: "unhandled excption has occured......... returned unexpected result"404"
I am doing the following things:
1) in the login section I am entering my user name and password correctly (validate it a couple of times that it is correct)
2) go to tab :"Selected SpreadSheet". then the error comes up
The problem you are experiencing is similar to this question: Google drive API to C#
You can no longer log into Google Spreadsheets with the old user credentials (username/password only). You need to use OAuth 2.0 now (which requires you to create an app and credentials at console.developers.google.com).
You can use the example below for the authentication logic, and use the logic in the logic found in this question to actually manipulate the file:
Accessing Google Spreadsheets with C# using Google Data API
Here is my answer to the linked question in case it gets deleted in the future:
This example requires you to use the following nuget packages and their dependencies:
Google.GData.Spreadsheets
Also, you must go to https://console.developers.google.com and register your application and create credentials for it so you can enter your CLIENT_ID and CLIENT_SECRET.
This is the documentation I used to put together this example: https://developers.google.com/google-apps/spreadsheets/
using System;
using System.Windows.Forms;
using Google.GData.Client;
using Google.GData.Spreadsheets;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string CLIENT_ID = "YOUR_CLIENT_ID";
string CLIENT_SECRET = "YOUR_CLIENT_SECRET";
string SCOPE = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds";
string REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.ClientId = CLIENT_ID;
parameters.ClientSecret = CLIENT_SECRET;
parameters.RedirectUri = REDIRECT_URI;
parameters.Scope = SCOPE;
string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
MessageBox.Show(authorizationUrl);
Console.WriteLine("Please visit the URL in the message box to authorize your OAuth "
+ "request token. Once that is complete, type in your access code to "
+ "continue...");
parameters.AccessCode = Console.ReadLine();
OAuthUtil.GetAccessToken(parameters);
string accessToken = parameters.AccessToken;
Console.WriteLine("OAuth Access Token: " + accessToken);
GOAuth2RequestFactory requestFactory =
new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
service.RequestFactory = requestFactory;
SpreadsheetQuery query = new SpreadsheetQuery();
SpreadsheetFeed feed = service.Query(query);
// Iterate through all of the spreadsheets returned
foreach (SpreadsheetEntry entry in feed.Entries)
{
// Print the title of this spreadsheet to the screen
Console.WriteLine(entry.Title.Text);
}
Console.ReadLine();
}
}
}

Azure ACS Credential Confusion

I downloaded the source for this project http://code.msdn.microsoft.com/windowsazure/MVC4-Web-API-With-SWT-232d69da#content because I am trying to understand ACS authentication and how to apply it in my MVC Web API.
The code has this:
// USE CONFIGURATION FILE, WEB.CONFIG, TO MANAGE THIS DATA
static string serviceNamespace = "<YOUR SERVICE NAMESPACE>";
static string acsHostUrl = "accesscontrol.windows.net";
static string realm = "<REALM>";
static string uid = "USERNAME";
static string pwd = "PASSWORD";
static string serviceUrl = "http://localhost:51388/api";
static string serviceAction = #"/values";
What USERNAME and PASSWORD is it requesting that I use? Does it want me to create a "Service Identity" and use the "password" option?
You need to read the associated article found at: http://blogs.msdn.com/b/alikl/archive/2011/06/05/how-to-request-swt-token-from-acs-and-how-to-validate-it-at-the-rest-wcf-service-hosted-in-windows-azure.aspx follow the steps to Configure ACS to Issue a SWT Token. The information you enter when completing the section "To configure a service identity for the REST web service" is what goes here.
If you are using a Symmetric key for your password then you need the client to request a token from ACS in a different way than the example. The following code is an example of what that request looks like and was taken from http://msdn.microsoft.com/en-us/library/hh674475.aspx. See the section "SWT token requests".
WebClient client = new WebClient();
client.BaseAddress = string.Format("https://mysnservice.accesscontrol.windows.net");
NameValueCollection values = new NameValueCollection();
// add the wrap_scope
values.Add("wrap_scope", "http://mysnservice.com/services");
// add the format
values.Add("wrap_assertion_format", "SWT");
// add the SWT
values.Add("wrap_assertion", "Issuer=mysncustomer1&HMACSHA256=b%2f%2bJFwbngGdufECFjQb8qhb9YH0e32Cf9ABMDZFiPPA%3d");
// WebClient takes care of the remaining URL Encoding
byte[] responseBytes = client.UploadValues("WRAPv0.9", "POST", values);
// the raw response from ACS
string response = Encoding.UTF8.GetString(responseBytes);

Categories