Can Field locators be used with the CoSign Signature Soap API C# - cosign-api

I have tried
Req.OptionalInputs.FieldLocatorOpeningPattern = "<<";
Req.OptionalInputs.FieldLocatorClosingPattern = ">>";
but sign is not replaced the space provided in pdf. Can you please provide a code sample for using the Soap API.

Please see the code sample below for using CoSign Signature SOAP API (aka SAPIWS) with CoSign Signature Locators:
public SAPISigFieldSettingsType[] getSigFieldLocatorsInPDF(
string FileName,
string UserName,
string Password)
{
//Create Request object contains signature parameters
RequestBaseType Req = new RequestBaseType();
Req.OptionalInputs = new RequestBaseTypeOptionalInputs();
//Here Operation Type is set: enum-field-locators
Req.OptionalInputs.SignatureType = SignatureTypeFieldLocators;
//Configure Create and Sign operation parameters:
Req.OptionalInputs.ClaimedIdentity = new ClaimedIdentity();
Req.OptionalInputs.ClaimedIdentity.Name = new NameIdentifierType();
Req.OptionalInputs.ClaimedIdentity.Name.Value = UserName; //User Name
Req.OptionalInputs.ClaimedIdentity.Name.NameQualifier = " "; //Domain (relevant for Active Directory environment only)
Req.OptionalInputs.ClaimedIdentity.SupportingInfo = new CoSignAuthDataType();
Req.OptionalInputs.ClaimedIdentity.SupportingInfo.LogonPassword = Password; //User Password
Req.OptionalInputs.FieldLocatorOpeningPattern = "<<";
Req.OptionalInputs.FieldLocatorClosingPattern = ">>";
//Set Session ID
Req.RequestID = Guid.NewGuid().ToString();
//Prepare the Data to be signed
DocumentType doc1 = new DocumentType();
DocumentTypeBase64Data b64data = new DocumentTypeBase64Data();
Req.InputDocuments = new RequestBaseTypeInputDocuments();
Req.InputDocuments.Items = new object[1];
b64data.MimeType = "application/pdf"; //Can also be: application/msword, image/tiff, pplication/octet-string
Req.OptionalInputs.ReturnPDFTailOnlySpecified = true;
Req.OptionalInputs.ReturnPDFTailOnly = false;
b64data.Value = ReadFile(FileName, true); //Read the file to the Bytes Array
doc1.Item = b64data;
Req.InputDocuments.Items[0] = doc1;
//Call sign service
ResponseBaseType Resp = null;
try
{
// Create the Web Service client object
DSS service = new DSS();
service.Url = "https://prime.cosigntrial.com:8080/sapiws/dss.asmx"; //This url is constant and shouldn't be changed
SignRequest sreq = new SignRequest();
sreq.InputDocuments = Req.InputDocuments;
sreq.OptionalInputs = Req.OptionalInputs;
//Perform Signature operation
Resp = service.DssSign(sreq);
if (Resp.Result.ResultMajor != Success )
{
MessageBox.Show("Error: " + Resp.Result.ResultMajor + " " +
Resp.Result.ResultMinor + " " +
Resp.Result.ResultMessage.Value, "Error");
return null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
if (ex is WebException)
{
WebException we = ex as WebException;
WebResponse webResponse = we.Response;
if (webResponse != null)
MessageBox.Show(we.Response.ToString(), "Web Response");
}
return null;
}
//Handle Reply
DssSignResult sResp = (DssSignResult) Resp;
return Resp.OptionalOutputs.SAPISeveralSigFieldSettings;
}

Related

ASP .Net Core file upload - getting form data when [DisableFormValueModelBinding] attribute is in place

I went ahead and implemented an ASP .Net Core file upload controller per the documentation and it requires using a [DisableFormValueModelBinding] attribute for streaming large files. I got that working fine. Unfortunately, when using that attribute it seems to block my JSON properties coming in from the form.
Is there any way to get both the file and the form data here? Here is my controller code (the request.form calls are where I am having issues):
[Route("{caseNbr:int}/Document")]
[ResponseType(typeof(CaseDocumentModel))]
[DisableFormValueModelBinding]
[HttpPost]
public async Task<IActionResult> PostDocument(int caseNbr)
{
string errorTrackingFileName = string.Empty;
try
{
UserSessionModel userSessionModel = SessionExtensions.CurrentUserSession;
if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
{
return BadRequest("Bad Request");
}
var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
var reader = new MultipartReader(boundary, HttpContext.Request.Body);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
if (hasContentDispositionHeader)
{
if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
{
return BadRequest("Bad Request");
}
var fileName = WebUtility.HtmlEncode(contentDisposition.FileName.Value);
errorTrackingFileName = fileName;
var trustedFileNameForFileStorage = fileName; //Path.GetRandomFileName();
var streamedFileContent = await FileHelpers.ProcessStreamedFile(section, contentDisposition, ModelState, _permittedExtensions, _fileSizeLimit);
if (!ModelState.IsValid)
{
return BadRequest("Bad Request");
}
using (var targetStream = System.IO.File.Create(Path.Combine(_tempFilePath, trustedFileNameForFileStorage)))
{
await targetStream.WriteAsync(streamedFileContent);
**//This is where I am having trouble:**
string descrip = HttpContext.Request.Form["Description"].ToString();
string docType = HttpContext.Request.Form["DocType"].ToString() ?? "Document";
bool isGeneralFileUpload = false;
if (string.IsNullOrWhiteSpace(Request.Form["GeneralFileUpload"]) == false && AppHelper.IsBool(Request.Form["GeneralFileUpload"]))
isGeneralFileUpload = bool.Parse(Request.Form["GeneralFileUpload"]);
int transcriptionJobId = 0;
if (string.IsNullOrWhiteSpace(Request.Form["TranscriptionJobId"]) == false && AppHelper.IsNumeric(Request.Form["TranscriptionJobId"]))
transcriptionJobId = int.Parse(Request.Form["TranscriptionJobId"]);
CaseDocumentModel createdCaseDocumentModel;
if (docType.Equals("Dictation"))
createdCaseDocumentModel = DictationRepository.ProcessDictationFile(userSessionModel.DBID, caseNbr, _tempFilePath, fileName, userSessionModel);
else if (isGeneralFileUpload)
createdCaseDocumentModel = DashboardAdjusterRepository.CreateGeneralFileUploadDocument(_tempFilePath, fileName, userSessionModel, docType, descrip);
else if (docType.Equals("Transcription"))
createdCaseDocumentModel = TranscriptionRepository.UploadTranscriptionFile(userSessionModel.DBID, _tempFilePath, fileName, userSessionModel, transcriptionJobId);
else
createdCaseDocumentModel = CaseRepository.CreateCaseDocumentRecord(userSessionModel.DBID, caseNbr, descrip, docType, _tempFilePath, fileName, userSessionModel);
return Ok(createdCaseDocumentModel);
}
}
// Drain any remaining section body that hasn't been consumed and
// read the headers for the next section.
section = await reader.ReadNextSectionAsync();
}
}
catch (Exception ex)
{
AppHelper.WriteErrorLog("CaseController PostDocument failed due to " + ex.Message + " case number was " + caseNbr + " file name was " + errorTrackingFileName);
return BadRequest("Bad Request");
}
return BadRequest("Bad Request");
}
Here is a sample call with Postman:
Screen shot of Postman

How can I upload a file to rackspace using RESTSharp and .net 4.0?

Here is what i have so far and it's not working:
private void _send1(string file)
{
var client = new RestClient("https://identity.api.rackspacecloud.com/v2.0");
var request = new RestRequest("tokens", Method.POST);
request.RequestFormat = DataFormat.Json;
string test = "{\"auth\":{\"RAX-KSKEY:apiKeyCredentials\"{\"username\":\"";
test += UserName;
test += "\",\"apiKey\":\"";
test += MyToken;
test += "\"}}}";
request.AddBody(serText);
request.AddParameter("application/json", test, ParameterType.RequestBody);
RestResponse response = (RestResponse)client.Execute(request);
// Content = "{\"badRequest\":{\"code\":400,\"message\":\"java.lang.String cannot be cast to org.json.simple.JSONObject\"}}"
}
note: UserName and apiKey are valid RackSpace credentials :-)
Thanks
In advance
Try 2: ( found this on the web ) and it gives me a token... now what do I do with it?
private void _send2(string file)
{
Dictionary<string, object> dictAuth = new Dictionary<string, object>();
dictAuth.Add("RAX-KSKEY:apiKeyCredentials", new { username = UserName, apiKey = MyToken });
var auth = new
{
auth = dictAuth
};
RestClient client = new RestClient("https://identity.api.rackspacecloud.com");
RestSharp.RestRequest r = new RestRequest("/v2.0/tokens", Method.POST);
r.AddHeader("Content-Type", "application/json");
r.RequestFormat = DataFormat.Json;
r.AddBody(auth);
RestResponse response = (RestResponse)client.Execute(r);
// Content = "{\"access\":{\"token\":{\"id\":\"AACCvxjTOXA\",\"expires\":\"2016-04-09T21:12:10.316Z\",\"tenant\":{\"id\":\"572045\",\"name\...
}
moving just a bit further:
I have create a class that parses out the URL, tenantID and token from Step 2 above
This data is passed to the PostFile call:
private void PostFile(string url, string tenantID, string token, string file)
{
string fName = Path.GetFileName(file);
RestClient client = new RestClient(url);
string baseURL = string.Format("v1/{0}/Support/{1}", tenantID, fName);
RestRequest r = new RestRequest(baseURL, Method.POST);
r.AddHeader("Content-Type", "text/plain");
r.AddParameter("X-Auth-Token", token);
r.AddFile(fName, file);
RestResponse response = (RestResponse)client.Execute(r);
if( response.StatusCode == System.Net.HttpStatusCode.OK)
{
int x = 0;
}
}
Here is what finally worked:
bool bRetval = false;
string fName = Path.GetFileName(file);
RestClient client = new RestClient(url);
string baseURL = string.Format("/Support/{0}", fName);
RestRequest r = new RestRequest(baseURL, Method.PUT);
r.AddHeader("Content-Type", "text/plain");
r.AddHeader("X-Auth-Token", token);
r.AddFile(fName, file);
RestResponse response = (RestResponse)client.Execute(r);
See the above post for the supporting functions that lead up to this one
private bool PostFile(string url, string token, string file)
{
bool bRetval = false;
string fName = Path.GetFileName(file);
RestClient client = new RestClient(url);
string baseURL = string.Format("/Support/{0}", fName);
RestRequest r = new RestRequest(baseURL, Method.PUT);
r.AddHeader("Content-Type", "text/plain");
r.AddHeader("X-Auth-Token", token);
r.AddFile(fName, file);
RestResponse response = (RestResponse)client.Execute(r);
if ( response.StatusCode == System.Net.HttpStatusCode.Created)
{
bRetval = true;
}
return bRetval;
}

How to send 1 million of push notification (APNS) within few second using PushSharp as webservice?

to do that i made a web service to send push (by referencing PushSharp library). I request web service through my web application. i retrieve list of device token from database(using web application) send to web service using for loop to send push. and get result/exception for each one. This process is very slow and take long long time to send notification. If anybody suggest me to what should i do i will be grateful to you.
public ActionResult SendNowToken(int certificateInfoId, string message, string certificate, int badgeNo, int pushtype, string password, string countryJsonString)
{
if (IsPushParameterValid(certificateInfoId, message, certificate, badgeNo, pushtype, password, countryJsonString))
{
var countryObject = new JavaScriptSerializer().Deserialize<Country>(countryJsonString);
var errorList = new List<ErrorList>();
byte[] certificatePath = System.IO.File.ReadAllBytes(HttpContext.Server.MapPath("~/Content/certificate/" + certificate));
foreach (var aDeviceToken in countryObject.DeviceTokens)
{
try
{
var serviceClient = new PushServiceSoapClient();
string serviceResult = serviceClient.SendPushNotification(message, badgeNo, pushtype, aDeviceToken.Token, certificatePath, password);
if (serviceResult != "Sent Notification")
{
var delimiters = new[] { ' ' };
string[] errorResult = serviceResult.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string errorMessage = ConvertErrorCodeToErrorMessage(errorResult[0]);
var error = new ErrorList
{
CountryName = countryObject.CountryName,
ErrorTime = DateTime.Now,
ErrorMessage = errorMessage,
Token = aDeviceToken.Token
};
errorList.Add(error);
}
}
catch (Exception ex)
{
var error = new ErrorList
{
CountryName = countryObject.CountryName,
ErrorTime = DateTime.Now,
ErrorMessage = ex.Message,
Token = aDeviceToken.Token
};
errorList.Add(error);
}
}
if (errorList.Count != 0)
{
ViewBag.Message = "Push Notification does not send to country... ";
return PartialView("_SendAllError", errorList.ToList());
}
errorList.Clear();
}
return View();
}

2 exceptions when trying to make async HttpWebRequest

I am writing an MVC Web API the make async HttpWebRequest calls. I am getting 2 different exceptions. Below is the method I am using.
The 1st exception is: "This stream does not support seek operations." and it is happening on the responseStream.
The 2nd exception is: "timeouts are not supported on this stream" and that is happening on the MemoryStream content.
What am I doing wrong? I have been Googling but not really finding any solution.
Thanks,
Rhonda
private async Task GetHtmlContentAsync(string requestUri, string userAgent, string referrer, bool keepAlive, TimeSpan timeout, bool forceTimeoutWhileReading, string proxy, string requestMethod, string type)
{
//string to hold Response
string output = null;
//create request object
var request = (HttpWebRequest)WebRequest.Create(requestUri);
var content = new MemoryStream();
request.Method = requestMethod;
request.KeepAlive = keepAlive;
request.Headers.Set("Pragma", "no-cache");
request.Timeout = (Int32)timeout.TotalMilliseconds;
request.ReadWriteTimeout = (Int32)timeout.TotalMilliseconds;
request.Referer = referrer;
request.Proxy = new WebProxy(proxy);
request.UserAgent = userAgent;
try
{
using (WebResponse response = await request.GetResponseAsync().ConfigureAwait(false))
{
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
await responseStream.CopyToAsync(content);
}
}
var sr = new StreamReader(content);
output = sr.ReadToEnd();
sr.Close();
}
}
catch (Exception ex)
{
output = string.Empty;
var message = ("The API caused an exception in the " + type + ".\r\n " + requestUri + "\r\n" + ex);
Logger.Write(message);
}
return output;
}
I fixed the issue by adding
content.Position = 0
before new StreamReader line. Now I just need to get it work with GZip compression.
Rhonda

HTTP Authentication with Web References

I have a web reference created from the WSDL, but I'm not allowed to call the function unless I pass in the username / password; the original code for the XML toolkit was:
Set client = CreateObject("MSSOAP.SOAPClient30")
URL = "http://" & host & "/_common/webservices/Trend?wsdl"
client.mssoapinit (URL)
client.ConnectorProperty("WinHTTPAuthScheme") = 1
client.ConnectorProperty("AuthUser") = user
client.ConnectorProperty("AuthPassword") = passwd
On Error GoTo err
Dim result1() As String
result1 = client.getTrendData(expression, startDate, endDate,
limitFromStart, maxRecords
How do I add the AuthUser/AuthPassword to my new code?
New code:
ALCServer.TrendClient tc = new WindowsFormsApplication1.ALCServer.TrendClient();
foreach(string s in tc.getTrendData(textBox2.Text, "5/25/2009", "5/28/2009", false, 500))
textBox1.Text+= s;
Found it: Even if Preauthenticate==True, it doesn't do it. You have to overried the WebRequest:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest request;
request = (HttpWebRequest)base.GetWebRequest(uri);
if (PreAuthenticate)
{
NetworkCredential networkCredentials =
Credentials.GetCredential(uri, "Basic");
if (networkCredentials != null)
{
byte[] credentialBuffer = new UTF8Encoding().GetBytes(
networkCredentials.UserName + ":" +
networkCredentials.Password);
request.Headers["Authorization"] =
"Basic " + Convert.ToBase64String(credentialBuffer);
}
else
{
throw new ApplicationException("No network credentials");
}
}
return request;
}
Since it gets created as a partial class, you can keep the stub in a separate file and rebuilding the Reference.cs won't clobber you.