I am writing an app that parses a csv file to an array and then insert the array into a sqlite database. I am having issues with Async connection to the sqlite database, I get a 3106 error...... I think the problem is that it executes the next statement before the previous is finished but I can't find a way to deal with this. Any help would be greatly appreciated.
public function addData(categories:Array):void{
status = "Adding data to table";
var insrtStmt:SQLStatement = new SQLStatement();
insrtStmt.sqlConnection = conn;
for(var i:int=categories.length-1; i>=0; i--){
insrtStmt.text = "";
insrtStmt.text += "INSERT INTO masterlist ";
insrtStmt.text += "(mainid, transactionDate, tradeId, ccyPair, account, buySell, customer, date,";
insrtStmt.text += " additionalid, dealType, traderName, genericType, owner) ";
insrtStmt.text += "VALUES(#mainid, #transactionDate, #tradeId, #ccyPair, #account, #buySell, #customer, #date,";
insrtStmt.text += " #additionalid, #dealType, #traderName, #genericType, #owner);";
insrtStmt.parameters["#mainid"] = categories[i].mainid;
insrtStmt.parameters["#transactionDate"] = categories[i].transactionDate;
insrtStmt.parameters["#tradeId"] = categories[i].tradeId;
insrtStmt.parameters["#ccyPair"] = categories[i].ccyPair;
insrtStmt.parameters["#account"] = categories[i].account;
insrtStmt.parameters["#buySell"] = categories[i].buySell;
insrtStmt.parameters["#customer"] = categories[i].customer;
insrtStmt.parameters["#date"] = categories[i].date;
insrtStmt.parameters["#additionalid"] = categories[i].additionalid;
insrtStmt.parameters["#dealType"] = categories[i].dealType;
insrtStmt.parameters["#traderName"] = categories[i].traderName;
insrtStmt.parameters["#genericType"] = categories[i].genericType;
insrtStmt.parameters["#owner"] = categories[i].owner;
insrtStmt.execute();
}
}
if you think the problem is that it is still executing, just add an event listener to the statement for it's "result" event, and then fire off the next statements.
public function addDataSet( categories : Array ) : void {
_categories = categories;
_loopcounter = categories.length;
_insrtStmt : SQLStatement = new SQLStatement();
_insrtStmt.addEventListener( "result", addData );
addData();
}
public function addData(event : Event = null) : void {
_loopcounter--;
// Set up rest of statement
_insrtStmt.execute();
}
Maybe you should use a synchronous connection instead of an async one? If needed you can open multiple connections to the same db and use the appropriate connection.
For executing multiple commands at once - use transactions.
Simple example from http://www.zedia.net/2009/air-sqlite-optimization-tricks/
_updateStmt.sqlConnection = _conn;
_updateStmt.text = "UPDATE main.myTable SET statusF=#STATUS WHERE keyId=#ID";
_conn.begin();//_conn is a SQLConnection, I didn't take the time to write the code for it, but this is where the magic happens
for (var i:uint = 0; i < currentArray.length; i++){
_updateStmt.parameters["#STATUS"] = currentArray[i].status;
_updateStmt.parameters["#ID"] = currentArray[i].id;
_updateStmt.execute();
}
_conn.commit();
Also have a look at the adobe flex livedocs chapter 'Improving database performance'
Or you could create a new SQLStatement for each query, that way you don't need to wait and you can fire the inserts off as fast as the client machine can process them.
public function addData(categories:Array):void {
status = "Adding data to table";
var insrtStmt:SQLStatement;
for(var i:int=categories.length-1; i>=0; i--) {
insrtStmt = new SQLStatement();
insrtStmt.sqlConnection = conn;
insrtStmt.text = "";
insrtStmt.text += "INSERT INTO masterlist ";
insrtStmt.text += "(mainid, transactionDate, tradeId, ccyPair, account, buySell, customer, date,";
insrtStmt.text += " additionalid, dealType, traderName, genericType, owner) ";
insrtStmt.text += "VALUES(#mainid, #transactionDate, #tradeId, #ccyPair, #account, #buySell, #customer, #date,";
insrtStmt.text += " #additionalid, #dealType, #traderName, #genericType, #owner);";
insrtStmt.parameters["#mainid"] = categories[i].mainid;
insrtStmt.parameters["#transactionDate"] = categories[i].transactionDate;
insrtStmt.parameters["#tradeId"] = categories[i].tradeId;
insrtStmt.parameters["#ccyPair"] = categories[i].ccyPair;
insrtStmt.parameters["#account"] = categories[i].account;
insrtStmt.parameters["#buySell"] = categories[i].buySell;
insrtStmt.parameters["#customer"] = categories[i].customer;
insrtStmt.parameters["#date"] = categories[i].date;
insrtStmt.parameters["#additionalid"] = categories[i].additionalid;
insrtStmt.parameters["#dealType"] = categories[i].dealType;
insrtStmt.parameters["#traderName"] = categories[i].traderName;
insrtStmt.parameters["#genericType"] = categories[i].genericType;
insrtStmt.parameters["#owner"] = categories[i].owner;
insrtStmt.execute();
}
}
Related
I'm building a web API Rest on .Net Core and ADO.Net
I use this code to populate my model object from DataRow:
public IEnumerable<TEntity> Map(DataTable table)
{
List<TEntity> entities = new List<TEntity>();
var columnNames = table.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToList();
var properties = (typeof(TEntity)).GetProperties().ToList();
foreach (DataRow row in table.Rows)
{
TEntity entity = new TEntity();
foreach (var prop in properties)
{
PropertyMapHelper.Map(typeof(TEntity), row, prop, entity);
}
entities.Add(entity);
}
return entities;
}
And use this other code for create the necesary SQL Update command:
protected void base_UpdateCommand(IDbCommand myCommand, TEntity entity, string sWhere)
{
var properties = (typeof(TEntity)).GetProperties().ToList();
string sProps = "";
string sCommand = "";
foreach (var prop in properties)
{
bool bIgnore = prop.GetCustomAttributes(true).Any(a => a is KeyAttribute);
if (prop.Name.ToUpper() != sKeyField.ToUpper() && !bIgnore)
{
sProps = sProps + prop.Name + "=#" + prop.Name + ", ";
var p = myCommand.CreateParameter();
p.ParameterName = prop.Name;
if (prop.GetValue(entity) == null)
p.Value = DBNull.Value;
else
p.Value = prop.GetValue(entity);
myCommand.Parameters.Add(p);
}
}
sProps = sProps.Substring(0, sProps.Length - 2);
sCommand = "UPDATE [" + sTable + "] SET " + sProps;
sCommand = sCommand + " WHERE " + sWhere;
myCommand.CommandText = sCommand;
}
I know that reflection has impact on performance, so i'm looking for suggestion on how to improve this code.
Thanks!
You might consider using Dapper. It is a wrapper around ADO.NET so technically it can't be faster than ADO.NET, but in most cases it uses better coding practices comparing to custom code you use to manupulate data via ADO.NET, so potentially it could give the better performance results.
Creating a Web API through which array of id is passed and returns the result from the OracleDB.
public class SampleController : ApiController
{
public string Getdetails([FromUri] int []id)
{
string inconditons = "";
for (int i = 0; i < id.Length; i++)
{
if (i == id.Length - 1)
{
inconditons = inconditons + id[i];
}
else
{
inconditons = inconditons + id[i] + ", ";
}
}
using (var dbConn = new OracleConnection("DATA SOURCE=X;PASSWORD=03JD;PERSIST SECURITY INFO=True;USER ID=IN"))
{
dbConn.Open();
var strQuery = #"Select PRIO_CATEGORY_ID as PRIO,LANG_ID as LANG, REC_DATE as REC, REC_USER as RECUSER, DESCR,COL_DESCR AS COL,ROW_DESCR as DROW,ABBR from STCD_PRIO_CATEGORY_DESCR where REC_USER IN (" + inconditons + ");";
var queryResult = dbConn.Query<SamModel>(strQuery);
return JsonConvert.SerializeObject(queryResult);
}
}
}
And called the API as http://localhost:35432/api/Sample?id=1&id=83 it throws an error saying on var queryResult = dbConn.Query(strQuery);
But if I just give one parameter as below it works
var strQuery = #"Select PRIO_CATEGORY_ID as PRIO,LANG_ID as LANG, REC_DATE as REC, REC_USER as RECUSER, DESCR,COL_DESCR AS COL,ROW_DESCR as DROW,ABBR from STCD_PRIO_CATEGORY_DESCR where REC_USER =" +id ;
Can anyone please suggest me what is the issue here as a single parameter works. Thanks
Check to make sure your don't have any stray characters in your query.
As stated in the comments
Use parameterized queries, otherwise you're vulnerable to errors like
this and SQL Injection attacks.
So pass the id array into the parameterized query when executing.
Here is a refactored version of your example.
public class SampleController : ApiController {
public string Getdetails([FromUri] int[] id) {
var inconditions = id.Distinct().ToArray();
using (var dbConn = new OracleConnection("DATA SOURCE=h;PASSWORD=C;PERSIST SECURITY INFO=True;USER ID=T")) {
dbConn.Open();
var strQuery = "SELECT PRIO_CATEGORY_ID AS PRIO, LANG_ID AS LANG, REC_DATE AS REC, REC_USER AS RECUSER, DESCR, COL_DESCR AS COL, ROW_DESCR AS DROW, ABBR FROM STCD_PRIO_CATEGORY_DESCR WHERE REC_USER IN (:p)";
var queryResult = dbConn.Query<SamModel>(strQuery, new { p = inconditions });
return JsonConvert.SerializeObject(queryResult);
}
}
}
Your code looks fine to me. It might fail if your id array parameter is empty (but it will be a different error than what you see now). Put a breakpoint in your code and inspect the value of that.
Also for converting your array to string, You may use the String.Join method.
var ids = String.Join(",",id);
This will give the result like "1,3,5", assuming your int array has 3 items ,1,3 and 5
Now you can use this string variable in your query. Also you may consider passing this data as a parameter.
var q= " ... where REC_USER IN (#ids);" //Please fill the missing part of query
var result = con.Query<SomeModel>(q,new { ids });
I'm trying to retrieve all phone calls related to opportunity, which statecode isn't equal 1. Tried QueryByAttribute, QueryExpression and RetrieveMultipleRequest, but still has no solution.
Here some code i wrote.
IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
IWorkflowContext context = contextService.Context;
ICrmService crmService = context.CreateCrmService(true);
if (crmService != null)
{
QueryByAttribute query = new Microsoft.Crm.Sdk.Query.QueryByAttribute();
query.ColumnSet = new Microsoft.Crm.Sdk.Query.AllColumns();
query.EntityName = EntityName.phonecall.ToString();
query.Attributes = new string[] { "regardingobjectid" };
query.Values = new string[] { context.PrimaryEntityId.ToString() };
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
retrieve.ReturnDynamicEntities = true;
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieve);
}
return ActivityExecutionStatus.Closed;
}
And almost same for QueryExpression
QueryExpression phCallsQuery = new QueryExpression();
ColumnSet cols = new ColumnSet(new string[] { "activityid", "regardingobjectid" });
phCallsQuery.EntityName = EntityName.phonecall.ToString();
phCallsQuery.ColumnSet = cols;
phCallsQuery.Criteria = new FilterExpression();
phCallsQuery.Criteria.FilterOperator = LogicalOperator.And;
phCallsQuery.Criteria.AddCondition("statuscode", ConditionOperator.NotEqual, "1");
phCallsQuery.Criteria.AddCondition("regardingobjectid", ConditionOperator.Equal, context.PrimaryEntityId.ToString();
I always get something like Soap exception or "Server was unable to proceed the request" when debugging.
To get exception details try to use following code:
RetrieveMultipleResponse retrieved = null;
try
{
retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieve);
}
catch(SoapException se)
{
throw new Exception(se.Detail.InnerXml);
}
I am receiving an error
Incorrect syntax near ?
when trying to use a update query function. The code is from SagePay http://www.sagepay.co.uk/file/12136/download-document/DotNetkit%201.2.6.7%20-%202014-08-14.zip?token=BJFwtM7qNnnm5ZCc_l_dOhq4INB0cQTPCxCd5JOpeh4 and relates to their server InFrame implementation.
As far as I can see the order is being passed correctly, and the list of fields, match the database, just not understanding why I am seeing this error. The code was originally created for MySQL but have had to adapt to SQL Server.
I've tried debugging, but cannot actually see what is being committed to the SQL Server from cmd.ExecuteNonQuery(); any help would be much appreciated, here is the code:
private static readonly List<String> FieldNames = new List<String>
{
VendorTxCodeField, AddressResultField, AddressStatusField, AmountField, AvsCv2Field, BankAuthCodeField, BasketField,
BillingFirstnamesField, BillingSurnameField, BillingPhoneField, BillingAddress1Field, BillingAddress2Field, BillingCityField,
BillingPostCodeField, BillingStateField, BillingCountryField, DeclineCodeField, DeliveryFirstnamesField, DeliverySurnameField, DeliveryPhoneField,
DeliveryAddress1Field, DeliveryAddress2Field, DeliveryCityField, DeliveryPostCodeField, DeliveryStateField, DeliveryCountryField,
CapturedAmountField, CardTypeField, CavvField, CurrencyField, CustomerEmailField, Cv2ResultField, ExpiryDateField, FraudResponseField,
GiftAidField, Last4DigitsField, LastUpdatedField, PayerIdField, PayerStatusField, PostCodeResultField,
RelatedVendorTxCodeField, SecurityKeyField, StatusField, StatusMessageField, SurchargeField, ThreeDSecureStatusField,
TransactionTypeField, TxAuthNoField, TokenIdField, VpsTxIdField
};
public static bool UpdateOrder(Order order, string vendorTxCode)
{
var result = false;
SqlConnection conn = null;
try
{
conn = new SqlConnection(ConnectionString);
conn.Open();
var cmd = new SqlCommand
{
Connection = conn, CommandText = "UPDATE Orders SET " + string.Join(",", FieldNames.Select(field => field + "=?" + field).ToList()) + " WHERE " + VendorTxCodeField + " =?" + VendorTxCodeField
};
cmd.Prepare();
AddOrderParameters(cmd, order);
cmd.ExecuteNonQuery();
result = true;
}
catch (SqlException ex)
{
Console.WriteLine("Error: {0}", ex);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return result;
}
private static void AddOrderParameters(SqlCommand command, Order order)
{
command.Parameters.AddWithValue(VendorTxCodeField, order.VendorTxCode);
command.Parameters.AddWithValue(AddressResultField, order.AddressResult);
command.Parameters.AddWithValue(AddressStatusField, order.AddressStatus);
command.Parameters.AddWithValue(AmountField, order.Amount);
command.Parameters.AddWithValue(AvsCv2Field, order.AvsCv2);
command.Parameters.AddWithValue(BankAuthCodeField, order.BankAuthCode);
command.Parameters.AddWithValue(BasketField, order.Basket);
command.Parameters.AddWithValue(BillingAddress1Field, order.BillingAddress1);
command.Parameters.AddWithValue(BillingAddress2Field, order.BillingAddress2);
command.Parameters.AddWithValue(BillingCityField, order.BillingCity);
command.Parameters.AddWithValue(BillingCountryField, order.BillingCountry);
command.Parameters.AddWithValue(BillingFirstnamesField, order.BillingFirstnames);
command.Parameters.AddWithValue(BillingPhoneField, order.BillingPhone);
command.Parameters.AddWithValue(BillingPostCodeField, order.BillingPostCode);
command.Parameters.AddWithValue(BillingStateField, order.BillingState);
command.Parameters.AddWithValue(BillingSurnameField, order.BillingSurname);
command.Parameters.AddWithValue(CapturedAmountField, order.CapturedAmount);
command.Parameters.AddWithValue(CardTypeField, order.CardType);
command.Parameters.AddWithValue(CavvField, order.Cavv);
command.Parameters.AddWithValue(CurrencyField, order.Currency);
command.Parameters.AddWithValue(CustomerEmailField, order.CustomerEmail);
command.Parameters.AddWithValue(Cv2ResultField, order.Cv2Result);
command.Parameters.AddWithValue(DeclineCodeField, order.DeclineCode);
command.Parameters.AddWithValue(DeliveryAddress1Field, order.DeliveryAddress1);
command.Parameters.AddWithValue(DeliveryAddress2Field, order.DeliveryAddress2);
command.Parameters.AddWithValue(DeliveryCityField, order.DeliveryCity);
command.Parameters.AddWithValue(DeliveryCountryField, order.DeliveryCountry);
command.Parameters.AddWithValue(DeliveryFirstnamesField, order.DeliveryFirstnames);
command.Parameters.AddWithValue(DeliveryPhoneField, order.DeliveryPhone);
command.Parameters.AddWithValue(DeliveryPostCodeField, order.DeliveryPostCode);
command.Parameters.AddWithValue(DeliveryStateField, order.DeliveryState);
command.Parameters.AddWithValue(DeliverySurnameField, order.DeliverySurname);
command.Parameters.AddWithValue(ExpiryDateField, order.ExpiryDate);
command.Parameters.AddWithValue(FraudResponseField, order.FraudResponse);
command.Parameters.AddWithValue(GiftAidField, order.GiftAid);
command.Parameters.AddWithValue(Last4DigitsField, order.Last4Digits);
command.Parameters.AddWithValue(LastUpdatedField, order.LastUpdated);
command.Parameters.AddWithValue(PayerIdField, order.PayerId);
command.Parameters.AddWithValue(PayerStatusField, order.PayerStatus);
command.Parameters.AddWithValue(PostCodeResultField, order.PostCodeResult);
command.Parameters.AddWithValue(RelatedVendorTxCodeField, order.RelatedVendorTxCode);
command.Parameters.AddWithValue(SecurityKeyField, order.SecurityKey);
command.Parameters.AddWithValue(StatusField, order.Status);
command.Parameters.AddWithValue(StatusMessageField, order.StatusMessage);
command.Parameters.AddWithValue(SurchargeField, order.Surcharge);
command.Parameters.AddWithValue(ThreeDSecureStatusField, order.ThreeDSecureStatus);
command.Parameters.AddWithValue(TokenIdField, order.TokenId);
command.Parameters.AddWithValue(TransactionTypeField, order.TransactionType);
command.Parameters.AddWithValue(TxAuthNoField, order.TxAuthNo);
command.Parameters.AddWithValue(VpsTxIdField, order.VpsTxId);
}
You have to use # for sql-parameters. Maybe this fixes your issue although i must admit that i don't understand the query because the column-names are the same as the values. However ...
string sql = #"UPDATE Orders SET {0}
Where {1}=#{1};";
sql = string.Format(sql
, string.Join(",", FieldNames.Select(field => string.Format("{0}=#{0}", field)))
, VendorTxCodeField);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
for (int i = 0; i < FieldNames.Count; i++)
{
cmd.Parameters.AddWithValue(FieldNames[i], FieldNames[i]);
}
// open connection and execute the command...
}
I'm new to creating commerce websites, and now that I need to sell software over the internet, I'm not sure where to start.
I'm using ASP.NET and am considering using Authorize.NET to validate and process the credit cards.
I'm looking for a stable, trusted solution that I can install on a single server. My secondary goal (besides selling products online) is to become familiar with shopping cart software that is popular, and in use by large businesses. Perhaps I should start with MS Commerce server?
There are a million options here, but if you are writing the code, the easiest way code-wise is to use http://sharpauthorize.com/
Authorize.Net is Very easy to implement with ASP.NET
Basically you can make transaction in 3-4 ways:
Simple Checkout Through Button like Paypal (http://developer.authorize.net/api/simplecheckout/)
Direct Post : Suppose you little bit more customization than Simple CheckOut. Create a checkout form that posts directly to Authorize.Net http://developer.authorize.net/api/simplecheckout/
Eg:
<h1><%=ViewData["message"] %></h1>
<%using (Html.BeginSIMForm("http://YOUR_SERVER.com/home/sim",
1.99M,"YOUR_API_LOGIN","YOUR_TRANSACTION_KEY",true)){%>
<%=Html.CheckoutFormInputs(true)%>
<%=Html.Hidden("order_id","1234") %>
<input type = "submit" value = "Pay" />
<%}%>
SIM (Server Integration)
AIM (Advance Integration Method): Give full control & customization.
CIM ( store Customer card no & info on Auth.NET server with tokanization)
*Below is a sample of CIM function to make a transaction, AIM is very much similar to CIM only difference is tokanization *
using ProjName.AuthApiSoap; // USE AUth Webserice Reference
public Tuple<string, string, string> CreateTransaction(long profile_id, long payment_profile_id, decimal amt, string DDD)
{
CustomerProfileWS.ProfileTransAuthCaptureType auth_capture = new CustomerProfileWS.ProfileTransAuthCaptureType();
auth_capture.customerProfileId = profile_id;
auth_capture.customerPaymentProfileId = payment_profile_id;
auth_capture.amount = amt;//1.00m;
auth_capture.order = new CustomerProfileWS.OrderExType();
POSLib.POSManager objManager = new POSLib.POSManager();
auth_capture.order.invoiceNumber = objManager.GetTimestamp(DateTime.Now);
DateTime now = DateTime.Now;
auth_capture.order.description = "Service " + DDD;
CustomerProfileWS.ProfileTransactionType trans = new CustomerProfileWS.ProfileTransactionType();
trans.Item = auth_capture;
CustomerProfileWS.CreateCustomerProfileTransactionResponseType response = SoapAPIUtilities.Service.CreateCustomerProfileTransaction(SoapAPIUtilities.MerchantAuthentication, trans, null);
string AuthTranMsg = "";
string AuthTranCode = "";
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranMsg = response.messages[i].text; // To Get Message n for loop to check the [i] is not empty
}
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranCode = response.messages[i].code; // To Get Code n for loop to check the [i] is not empty
}
var tCompResp = new Tuple<string, string, string>(AuthTranCode, AuthTranMsg, response.directResponse);
return tCompResp;
}
This is how to split the Reponse Msg (Format and Order will be FIXED for all transaction/ on web service responsed )
var tResp = objManager.CreateTransaction(profID, paymProfID, Convert.ToDecimal(PmtToday), DDD);
string respCCNo = "";
string RespCCType = "";
string InvoiceNo = "";
string transType = "";
string approvalCode = "";
string AmtRequested = "";
string respName = "";
string respReasonText = "";
string respMD5Hash = "";
string respEmailId = "";
string respReasonCode = "";
string respMethod = "";
string respAVSResultCode = "";
string responseCode = "";
string transactionId = "0";
if (!string.IsNullOrEmpty(tCompResp.Item3))
{
string[] arrRespParts = tCompResp.Item3.Replace("|", "").Split(',');
responseCode = arrRespParts[0];
respReasonCode = arrRespParts[2];
respReasonText = arrRespParts[3];
approvalCode = arrRespParts[4];
respAVSResultCode = arrRespParts[5];
transactionId = arrRespParts[6].Replace("|", "");
InvoiceNo = arrRespParts[7];
AmtRequested = arrRespParts[9];
transType = arrRespParts[10];
respMethod = arrRespParts[11];
respName = arrRespParts[13] + " " + arrRespParts[14];
respEmailId = arrRespParts[23];
respMD5Hash = arrRespParts[37];
respCCNo = arrRespParts[50];
RespCCType = arrRespParts[51];
}
==================================AIM Code
public Tuple<string, string, string> ECheckCreateTransAIM(string amount, string bankRoutingNo, string bankAccNo, string bankAccType, string bankName, string bankAccName, string echeckType, bool isCustomerEmail, string customerEmail, string mechantEMail)
{
//CustomValidator1.ErrorMessage = "";
string AuthNetVersion = "3.1"; // Contains CCV support
WebClient webClientRequest = new WebClient();
System.Collections.Specialized.NameValueCollection InputObject = new System.Collections.Specialized.NameValueCollection(30);
System.Collections.Specialized.NameValueCollection ReturnObject = new System.Collections.Specialized.NameValueCollection(30);
byte[] ReturnBytes;
string[] ReturnValues;
string ErrorString;
InputObject.Add("x_version", AuthNetVersion);
InputObject.Add("x_delim_data", "True");
InputObject.Add("x_login", MERCHANT_NAME);
InputObject.Add("x_tran_key", TRANSACTION_KEY);
InputObject.Add("x_relay_response", "False");
//----------------------Set to False to go Live--------------------
InputObject.Add("x_test_request", "False");
//---------------------------------------------------------------------
InputObject.Add("x_delim_char", ",");
InputObject.Add("x_encap_char", "|");
if (isCustomerEmail)
{
InputObject.Add("x_email", customerEmail);
InputObject.Add("x_email_customer", "TRUE"); //Emails Customer
}
InputObject.Add("x_merchant_email", mechantEMail);
// FOR echeck
InputObject.Add("x_bank_aba_code", bankRoutingNo);
InputObject.Add("x_bank_acct_num", bankAccNo);
InputObject.Add("x_bank_acct_type", bankAccType);
InputObject.Add("x_bank_name", bankName);
InputObject.Add("x_bank_acct_name", bankAccName);
InputObject.Add("x_method", "ECHECK");
InputObject.Add("x_type", "AUTH_CAPTURE");
InputObject.Add("x_amount", string.Format("{0:c2}", Convert.ToDouble(amount)));
// Currency setting. Check the guide for other supported currencies
//needto change it to Actual Server URL
//Set above Testmode=off to go live
webClientRequest.BaseAddress = eCheckBaseAddress; //"https://apitest.authorize.net/soap/v1/Service.asmx"; //"https://secure.authorize.net/gateway/transact.dll";
ReturnBytes = webClientRequest.UploadValues(webClientRequest.BaseAddress, "POST", InputObject);
ReturnValues = System.Text.Encoding.ASCII.GetString(ReturnBytes).Split(",".ToCharArray());
if (ReturnValues[0].Trim(char.Parse("|")) == "1") // Succesful Transaction
{
//AuthNetCodeLabel.Text = ReturnValues[4].Trim(char.Parse("|")); // Returned Authorisation Code
//AuthNetTransIDLabel.Text = ReturnValues[6].Trim(char.Parse("|")); // Returned Transaction ID
var tCompResp = new Tuple<string, string, string>("I00001", ReturnValues[3].Trim(char.Parse("|")), string.Join(",", ReturnValues));
return tCompResp;
}
else
{
// Error!
ErrorString = ReturnValues[3].Trim(char.Parse("|")) + " (" + ReturnValues[2].Trim(char.Parse("|")) + ")";
if (ReturnValues[2].Trim(char.Parse("|")) == "45")
{
if (ErrorString.Length > 1)
ErrorString += "<br />n";
// AVS transaction decline
ErrorString += "Address Verification System (AVS) " +
"returned the following error: ";
switch (ReturnValues[5].Trim(char.Parse("|")))
{
case "A":
ErrorString += " the zip code entered does not match the billing address.";
break;
case "B":
ErrorString += " no information was provided for the AVS check.";
break;
case "E":
ErrorString += " a general error occurred in the AVS system.";
break;
case "G":
ErrorString += " the credit card was issued by a non-US bank.";
break;
case "N":
ErrorString += " neither the entered street address nor zip code matches the billing address.";
break;
case "P":
ErrorString += " AVS is not applicable for this transaction.";
break;
case "R":
ErrorString += " please retry the transaction; the AVS system was unavailable or timed out.";
break;
case "S":
ErrorString += " the AVS service is not supported by your credit card issuer.";
break;
case "U":
ErrorString += " address information is unavailable for the credit card.";
break;
case "W":
ErrorString += " the 9 digit zip code matches, but the street address does not.";
break;
case "Z":
ErrorString += " the zip code matches, but the address does not.";
break;
}
}
}
var tCompRespFail = new Tuple<string, string, string>(ReturnValues[6].ToString(), ErrorString, string.Join(",", ReturnValues));
return tCompRespFail;
}
CIM CODE (Tokanisation (Card not present method)
public Tuple<string, string, string> CreateTransaction(long profile_id, long payment_profile_id, decimal amt, string DDD)
{
CustomerProfileWS.ProfileTransAuthCaptureType auth_capture = new CustomerProfileWS.ProfileTransAuthCaptureType();
auth_capture.customerProfileId = profile_id;
auth_capture.customerPaymentProfileId = payment_profile_id;
auth_capture.amount = amt;//1.00m;
auth_capture.order = new CustomerProfileWS.OrderExType();
POSLib.POSManager objManager = new POSLib.POSManager();
auth_capture.order.invoiceNumber = objManager.GetTimestamp(DateTime.Now);
DateTime now = DateTime.Now;
auth_capture.order.description = "Service " + DDD;
CustomerProfileWS.ProfileTransactionType trans = new CustomerProfileWS.ProfileTransactionType();
trans.Item = auth_capture;
CustomerProfileWS.CreateCustomerProfileTransactionResponseType response = SoapAPIUtilities.Service.CreateCustomerProfileTransaction(SoapAPIUtilities.MerchantAuthentication, trans, null);
string AuthTranMsg = "";
string AuthTranCode = "";
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranMsg = response.messages[i].text; // To Get Message n for loop to check the [i] is not empty
}
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranCode = response.messages[i].code; // To Get Code n for loop to check the [i] is not empty
}
var tCompResp = new Tuple<string, string, string>(AuthTranCode, AuthTranMsg, response.directResponse);
return tCompResp;
}