CyberSource No WS-Security Header Issue - web-services

I found the following example code for the CyberSource Payment Gateway but am unable to get it to work. When I run the sample I get the following error: FaultException: Security Data : No WS-Security Header. I have been through the gateway documentation and searched all of the forums but have not been able to find a solution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using PaymentGatewayConsole.CyberSourceTest;
namespace PaymentGatewayConsole
{
class Program
{
private const String MERCHANT_ID = "removed";
private const String TRANSACTION_KEY = "removed";
private static string REQUEST_TOKEN = string.Empty;
private static string REQUEST_ID = string.Empty;
static void Main(string[] args)
{
MakePayment();
RequestRefund();
}
private static void MakePayment()
{
RequestMessage request = new RequestMessage();
request.merchantID = MERCHANT_ID;
// replace request.merchantReferenceCode with reference number for the current transaction.
request.merchantReferenceCode = "123";
request.clientLibrary = ".NET WCF";
request.clientLibraryVersion = Environment.Version.ToString();
request.clientEnvironment = Environment.OSVersion.Platform + Environment.OSVersion.Version.ToString();
request.ccAuthService = new CCAuthService();
request.ccAuthService.run = "true";
BillTo billTo = new BillTo();
billTo.firstName = "John";
billTo.lastName = "Doe";
billTo.street1 = "1295 Charleston Road";
billTo.city = "Mountain View";
billTo.state = "CA";
billTo.postalCode = "94043";
billTo.country = "US";
billTo.email = "null#cybersource.com";
billTo.ipAddress = "10.7.111.111";
request.billTo = billTo;
Card card = new Card();
card.accountNumber = "4111111111111111";
card.expirationMonth = "12";
card.expirationYear = "2020";
card.cardType = "Visa";
request.card = card;
PurchaseTotals purchaseTotals = new PurchaseTotals();
purchaseTotals.currency = "USD";
request.purchaseTotals = purchaseTotals;
request.item = new Item[1];
Item item = new Item();
item.id = "0";
item.unitPrice = "49.00";
request.item[0] = item;
try
{
TransactionProcessorClient proc = new TransactionProcessorClient();
proc.ChannelFactory.Credentials.UserName.UserName = request.merchantID;
proc.ChannelFactory.Credentials.UserName.Password = TRANSACTION_KEY;
ReplyMessage reply = proc.runTransaction(request);
REQUEST_ID = reply.requestID;
REQUEST_TOKEN = reply.requestToken;
Console.WriteLine("decision = " + reply.decision);
Console.WriteLine("reasonCode = " + reply.reasonCode);
Console.WriteLine("requestID = " + reply.requestID);
Console.WriteLine("requestToken = " + reply.requestToken);
Console.WriteLine("ccAuthReply.reasonCode = " + reply.ccAuthReply.reasonCode);
}
catch (TimeoutException e)
{
Console.WriteLine("TimeoutException: " + e.Message + "\n" + e.StackTrace);
}
catch (FaultException e)
{
Console.WriteLine("FaultException: " + e.Message + "\n" + e.StackTrace);
}
catch (CommunicationException e)
{
Console.WriteLine("CommunicationException: " + e.Message + "\n" + e.StackTrace);
}
Console.ReadLine();
}
/// <summary>
/// Method for requesting refund
/// </summary>
private static void RequestRefund()
{
RequestMessage request = new RequestMessage();
request.merchantID = MERCHANT_ID;
request.merchantReferenceCode = "123";
request.clientLibrary = ".NET WCF";
request.clientLibraryVersion = Environment.Version.ToString();
request.clientEnvironment = Environment.OSVersion.Platform + Environment.OSVersion.Version.ToString();
request.ccAuthService = new CCAuthService();
request.ccAuthService.run = "true";
//request.ccAuthReversalService = new CCAuthReversalService();
//request.ccAuthReversalService.run = "true";
//request.ccAuthReversalService.authRequestID = REQUEST_ID;
//request.orderRequestToken = REQUEST_TOKEN;
//request.purchaseTotals = new PurchaseTotals();
//request.purchaseTotals.currency = "USD";
//request.purchaseTotals.grandTotalAmount = "10";
VoidService reqVoid = new VoidService();
reqVoid.voidRequestID = REQUEST_ID;
reqVoid.voidRequestToken = REQUEST_TOKEN;
reqVoid.run = "true";
request.voidService = reqVoid;
try
{
TransactionProcessorClient proc = new TransactionProcessorClient();
proc.ChannelFactory.Credentials.UserName.UserName = request.merchantID;
proc.ChannelFactory.Credentials.UserName.Password = TRANSACTION_KEY;
ReplyMessage reply = proc.runTransaction(request);
Console.WriteLine("decision = " + reply.decision);
Console.WriteLine("reasonCode = " + reply.reasonCode);
Console.WriteLine("requestID = " + reply.requestID);
Console.WriteLine("requestToken = " + reply.requestToken);
}
catch (TimeoutException e)
{
Console.WriteLine("TimeoutException: " + e.Message + "\n" + e.StackTrace);
}
catch (FaultException e)
{
Console.WriteLine("FaultException: " + e.Message + "\n" + e.StackTrace);
}
catch (CommunicationException e)
{
Console.WriteLine("CommunicationException: " + e.Message + "\n" + e.StackTrace);
}
Console.ReadLine();
}
}
}

I was getting the same error. The default security mode in the basicHttpBinding was set to Transport in the bindings of the web.config. Once I change the security mode to TransportWithMessageCredential this error went away. I know this question is a bit old, but I hope this can help someone.

You need to set
System.setProperty("axis.ClientConfigFile", 'path/to/cybs.wsdd');
Example:
<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
<transport name="http" pivot="java:org.apache.axis.transport.http.HTTPSender"/>
<globalConfiguration >
<requestFlow >
<handler type="java:org.apache.ws.axis.security.WSDoAllSender" >
<parameter name="action" value="UsernameToken"/>
<parameter name="passwordType" value="PasswordText"/>
<parameter name="passwordCallbackClass" value="org.broadleafcommerce.vendor.cybersource.service.CyberSourcePasswordCallbackDecorator"/>
</handler>
</requestFlow >
</globalConfiguration >
</deployment>
I take it from https://github.com/BroadleafCommerce/blc-cybersource/blob/master/src/main/resources/CyberSourceDeploy.wsdd

Related

S3 bukcet getobject throws error Method not found: 'Amazon.Runtime.Internal.Transform.UnmarshallerContext

I am tring to read my s3 bucket object from EKS cluster application method as listed below.
[HttpGet("ReadFromS3")]
[ProducesResponseType(typeof(ApiResponse<string>), 200)]
[ProducesResponseType(500)]
public async Task<String> ReadFromS3()
{
AmazonS3Config config = new AmazonS3Config { RegionEndpoint = RegionEndpoint.EUWest2 };
string aws_tokenFile = Environment.GetEnvironmentVariable("AWS_WEB_IDENTITY_TOKEN_FILE");
string aws_rolw_arn = Environment.GetEnvironmentVariable("AWS_ROLE_ARN");
string logs = string.Empty;
using (var stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials()))
{
logs += "AmazonSecurityTokenServiceClient";
var assumeRoleResult = await stsClient.AssumeRoleWithWebIdentityAsync(new AssumeRoleWithWebIdentityRequest
{
WebIdentityToken = System.IO.File.ReadAllText(Environment.GetEnvironmentVariable("AWS_WEB_IDENTITY_TOKEN_FILE")),
RoleArn = Environment.GetEnvironmentVariable("AWS_ROLE_ARN"),
RoleSessionName = "S3Session",
DurationSeconds = 900
});
if (assumeRoleResult != null)
{
logs += " -> assumeRoleResult";
var credentials = assumeRoleResult.Credentials;
var basicCredentials = new BasicAWSCredentials(credentials.AccessKeyId,
credentials.SecretAccessKey);
logs += " -> BasicAWSCredentials";
using (client = new AmazonS3Client(basicCredentials, RegionEndpoint.EUWest2) )
{
logs += " -> AmazonS3Client";
try
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = bucketName,
Key = keyName
};
GetObjectResponse response = await client.GetObjectAsync(request);
logs += " -> GetObjectAsync";
Stream responseStream = response.ResponseStream;
StreamReader reader = new StreamReader(responseStream);
logs += " -> ResponseStream";
return await reader.ReadToEndAsync();
}
catch (Exception ex)
{
return "Exception in ReadFromS3 :" + ex.Message + logs;
}
}
}
else
{
return "Unable to Connect";
}
}
}
I am getting error at line GetObjectResponse response = await client.GetObjectAsync(request);
Method not found: 'Amazon.Runtime.Internal.Transform.UnmarshallerContext Amazon.Runtime.Internal.Transform.ResponseUnmarshaller.CreateContext

Extract pdf document with multi page

I am using Amazon's Textract service for extracting tables, Forms from pdf documnets.
The example provided at Github here is working for single page document only. But as per demo provided by AWS they are able to extract multi page pdf docs as well.
As per documentation we have to call same service for multi pages as well. But it is not working for me.
All the examples provided by them are either in python or java.
I am doing it in dotnet core.
Any help?
Here is my code.
public IActionResult FileExtract(string filename)
{
try
{
string lineText = "";
string wordText = "";
string fieldsText = "";
string fieldsText2 = "";
string tableText = "";
// Extracting file in below code.
var textractAnalysisClient = BuildTextractClient();
var document = PrepareDocument(textractAnalysisClient, "FORMS", filename);
document.Pages.ForEach(page =>
{
page.Lines.ForEach(line =>
{
lineText += "<button class='rawlabel'>" + line.Text + "</button>";
line.Words.ForEach(word =>
{
wordText += word.Text;
});
});
page.Form.Fields.ForEach(f =>
{
fieldsText += "<div><h5>" + f.Key + "</h5><p style='background-color:lightgray;width: 200px;padding: 6px;'>"
+ f.Value + "</p></div>";
});
var key = "Phone Number:";
var field = page.Form.GetFieldByKey(key);
if (field != null)
{
fieldsText2 += "Key: " + field.Key + " | Value: " + field.Value;
}
});
tableText = "<table id='customers'>";
document = PrepareDocument(textractAnalysisClient, "TABLES", filename);
document.Pages.ForEach(page =>
{
page.Tables.ForEach(table =>
{
var r = 0;
table.Rows.ForEach(row =>
{
r++;
tableText += "<tr>";
var c = 0;
row.Cells.ForEach(cell =>
{
c++;
tableText += "<td>";
tableText += cell.Text + "</td>";
});
tableText += "</tr>";
});
});
});
tableText += "</table>";
objJsonResponse.fieldsText = fieldsText;
objJsonResponse.fieldsText2 = fieldsText2;
objJsonResponse.lineText = lineText;
objJsonResponse.tableText = tableText;
objJsonResponse.wordText = wordText;
objJsonResponse.responsecode = 1;
return Json(objJsonResponse);
}
catch (Exception ex)
{
this.objJsonResponse.responsecode = -1;
this.objJsonResponse.error = "failed";
return Json(this.objJsonResponse);
}
}
static TextractTextAnalysisService BuildTextractClient()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var awsOptions = builder.GetAWSOptions();
return new TextractTextAnalysisService(awsOptions.CreateServiceClient<IAmazonTextract>());
}
static TextractDocument PrepareDocument(TextractTextAnalysisService textractAnalysisClient, string type, string FormFile)
{
var task = textractAnalysisClient.StartDocumentAnalysis(BucketName, FormFile, type);
var jobId = task.Result;
textractAnalysisClient.WaitForJobCompletion(jobId);
var results = textractAnalysisClient.GetJobResults(jobId);
return new TextractDocument(results);
}

How to make oledb query asychronous

I'm having problems with this query, it takes a long time to run and is timing out. I wanted to try to make it async but I can't find a good example that's close to what I'm trying to do.
Below is what I've tried, it starts but does nothing. This is inside a WinForm project.
namespace access_db_csharp
{
public partial class Form1 : Form
{
string SQL = "";
public Form1()
{
InitializeComponent();
textBox1.Text = "Select Project, Request, Release, TestName, AssignmentNumber, Formulation, Container, Closure FROM tblWtLossBottDropResults";
textBox2.Text = "Where Container LIKE '%2700-305%'";
dataGridView1.Focus();
}
OleDbConnection con=new OleDbConnection ();
OleDbCommand cmd=new OleDbCommand ();
string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=K:\R&D Dept\Development Lab\DLab Databases and Add Ins\DLab Results Database\DLab Results Individual Tables.accdb;Jet OLEDB:Database Password='roscoe'";
private async void button1_Click(object sender, EventArgs e)
{
Task<DataTable> task = new Task<DataTable>(RunQuery);
task.Start();
}
private DataTable RunQuery()
{
if (checkBox1.Checked == true)
{
SQL = textBox1.Text + " " + textBox2.Text;
}
else
{
SQL = textBox1.Text;
}
OleDbConnection con = new OleDbConnection(connectionstring);
OleDbCommand cmd = new OleDbCommand(SQL, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable tblWtLossBottDropResults = new DataTable();
da.Fill(tblWtLossBottDropResults);
dataGridView1.DataSource = tblWtLossBottDropResults;
//dataGridView1.ColumnCount = 17;
dataGridView1.Columns[0].Name = "Project";
dataGridView1.Columns[1].Name = "Request";
dataGridView1.Columns[2].Name = "Release";
dataGridView1.Columns[3].Name = "TestName";
dataGridView1.Columns[4].Name = "AssignmentNumber";
dataGridView1.Columns[5].Name = "Formulation";
dataGridView1.Columns[6].Name = "Container";
dataGridView1.Columns[7].Name = "Closure";
MessageBox.Show("Done");
int numRows = dataGridView1.RowCount;
label4.Text = "Rows Returned: " + numRows.ToString();
return tblWtLossBottDropResults;
}
private void Form1_Load(object sender, EventArgs e)
{
con.ConnectionString = connectionstring;
con.Open();
}
}
}
Ideally I want to get the data from the query and load it into a datagridview table.
There are a few things you should change:
1. You should not mix UI and non-UI code.
2. You should keep your connection open for the shortest amount of time.
Because the OleDb provider doesn't have asynchronous APIs, your database code will be synchronous:
private DataTable RunQuery(string commandText)
{
using (var connection = new OleDbConnection(connectionstring))
{
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = commandText;
using (var dataAdapter = new OleDbDataAdapter(command))
{
connection.Open();
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
return dataTable;
}
}
}
}
Because it's a Windows Forms application you can use Task.Run to offload that work to the thread pool and free the UI thread:
private async void button1_Click(object sender, EventArgs e)
{
var commandText = checkBox1.Checked
? textBox1.Text + " " + textBox2.Text
: textBox1.Text;
var dataTable = await Task.Run(() => RunQuery(commandText));
/* This should be set on the designer or on the constructor
//dataGridView1.ColumnCount = 17;
dataGridView1.Columns[0].Name = "Project";
dataGridView1.Columns[1].Name = "Request";
dataGridView1.Columns[2].Name = "Release";
dataGridView1.Columns[3].Name = "TestName";
dataGridView1.Columns[4].Name = "AssignmentNumber";
dataGridView1.Columns[5].Name = "Formulation";
dataGridView1.Columns[6].Name = "Container";
dataGridView1.Columns[7].Name = "Closure";
*/
dataGridView1.DataSource = dataTable;
MessageBox.Show("Done");
int numRows = dataGridView1.RowCount;
label4.Text = "Rows Returned: " + numRows.ToString();
}

In SharePoint 2013 pragmatically how to copy document Library Item from one site collection to another site collection

I have 2 site collection of same web application as site1 & site2.
I have create Document Library on both site as Doc1 & Doc2.when Item is uploaded in Documemnt Library then copy that item into site2 Doc2 Library.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
namespace CopyListItems
{
class Program
{
static void Main(string[] args)
{
try
{
SPSite mySourceSite = new SPSite("http://fivenumber:5/");
SPWeb mySourceWeb = mySourceSite.OpenWeb();
SPList mySourceList = mySourceWeb.Lists["Source List"];
SPQuery mySourceListQuery = new SPQuery();
mySourceListQuery.Query = "" +
"" +
"" +
"" +
"";
SPListItemCollection mySourceItemColl = mySourceList.GetItems(mySourceListQuery);
int count = 0;
foreach (SPListItem mySourceListItem in mySourceItemColl)
{
string SourceEmpId = mySourceListItem["Employee Id"].ToString();
string SourceEmpName = mySourceListItem["Employee Name"].ToString();
string SourceDesig = mySourceListItem["Designation"].ToString();
string SourceAge = mySourceListItem["Age"].ToString();
SPSite myDestinationSite = new SPSite("http://fivenumber:50");
SPWeb myDestinationWeb = myDestinationSite.OpenWeb();
SPList myDestinationList = myDestinationWeb.Lists["Destination List"];
SPListItem myDestinationListItem = myDestinationList.Items.Add();
myDestinationListItem["Employee Id"] = SourceEmpId;
myDestinationListItem["Employee Name"] = SourceEmpName;
myDestinationListItem["Designation"] = SourceDesig;
myDestinationListItem["Age"] = SourceAge;
myDestinationWeb.AllowUnsafeUpdates = true;
myDestinationListItem.Update();
myDestinationWeb.AllowUnsafeUpdates = false;
count++;
Console.WriteLine(count+" item(s) copied");
}
Console.WriteLine("Press enter to continue");
Console.ReadLine();
}
catch (Exception ex)
{
Console.Write(ex);
Console.WriteLine("Press enter to continue");
Console.ReadLine();
}
}
}
}

System.Net.WebException: The remote server returned an error: (401) Unauthorized.in C#?

my code for gcm:
[WebMethod]
public void SendNotificationToAndroid()
{
string DeviceTokenID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// string deviceId = notificationId;
const string tickerText = "Text";
const string contentTitle = "Title";
string message = "Hello world";
string postData =
"{ \"registration_ids\": [ \"" + DeviceTokenID + "\" ], " +
"\"data\": {\"tickerText\":\"" + tickerText + "\", " +
"\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
SendGcmNotification("xxxxxxxxxxxxxxxxx", postData, "application/json");
}
private void SendGcmNotification(string apiKey, string postData, string postDataContentType)
{
// ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertificate;
var byteArray = Encoding.UTF8.GetBytes(postData);
var request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
request.Method = "POST";
request.KeepAlive = false;
request.ContentType = postDataContentType;
request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
request.ContentLength = byteArray.Length;
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
var dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
try
{
var response = request.GetResponse();
var responseCode = ((HttpWebResponse)response).StatusCode;
if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
{
const string text = "Unauthorized - need new token";
Context.Response.Write(text);
}
else if (!responseCode.Equals(HttpStatusCode.OK))
{
const string text = "Response from web service isn't OK";
Context.Response.Write(text);
}
// ReSharper disable AssignNullToNotNullAttribute
var reader = new StreamReader(response.GetResponseStream());
// ReSharper restore AssignNullToNotNullAttribute
reader.ReadToEnd();
reader.Close();
//Context.Response.Write();
}
catch (Exception e)
{
Context.Response.Write(e.ToString());
}
}
this is my push notification code at server side.The response i am getting error "System.Net.WebException: The remote server returned an error: (401) Unauthorized.
please any one one help. Thank yOu in advance.
Try unsing session on your web method
[WebMethod(true)]