How to broadcast an NBitcoin Transaction with multiple TxIn ( transaction inputs) - c#

I am running on TestNet. I am trying to add multiple transaction inputs TxIn() so as to spend from these inputs. When I broadcast my transaction, it returns successful but I can't see it on the block-explorer. I have handled a transaction with a single TxIn() and when I broadcast it, it was successful and i could view it on the block-explorer. I have been on this for more than 2 days now. Will greatly appreciate your help guys
var bitcoinPrivateKey = new BitcoinSecret("cNZupUgfs54DmsShwxa1wpomQcszUtuJYFvx9zWPbXrT7KsWtiUd");
var network = bitcoinPrivateKey.Network;
var address = bitcoinPrivateKey.GetAddress();
var client = new QBitNinjaClient(network);
var balance = client.GetBalance(address).Result;
var transactionId = uint256.Parse("06c0aec7543467951abad0c28998a2c1fc1cdc34e01113f8ec1fdb22be854771");
var transactionResponse = client.GetTransaction(transactionId).Result;
var tx = new Transaction();
foreach (var operation in balance.Operations)
{
OutPoint spendOutPoint = null;
var coinsReceived = operation.ReceivedCoins;
foreach (var coin in coinsReceived)
{
if (coin.TxOut.ScriptPubKey == bitcoinPrivateKey.ScriptPubKey)
{
spendOutPoint = coin.Outpoint;
tx.Inputs.Add(new TxIn()
{
PrevOut = spendOutPoint
});
}
}
}
var chimaTestDestinationAddress = new BitcoinPubKeyAddress("mxgN2AiqHjKfGvo6Y57fAe4Y754rPdKf4P");
TxOut chimaTestDestinationAddressTxOut = new TxOut()
{
Value = new Money((decimal)0.50, MoneyUnit.BTC),
ScriptPubKey = chimaTestDestinationAddress.ScriptPubKey
};
TxOut ugoChangeBackTxOut = new TxOut()
{
Value = new Money((decimal)2.98, MoneyUnit.BTC),
ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
};
tx.Outputs.Add(chimaTestDestinationAddressTxOut);
tx.Outputs.Add(ugoChangeBackTxOut);
var msg = "ugo the jedi master";
var msgBytes = Encoding.UTF8.GetBytes(msg);
TxOut txDesc = new TxOut()
{
Value = Money.Zero,
ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(msgBytes)
};
tx.Outputs.Add(txDesc);
tx.Inputs[0].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[1].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[2].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[3].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[4].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Sign(bitcoinPrivateKey, false);
BroadcastResponse broadcast = client.Broadcast(tx).Result;
if (!broadcast.Success)
{
Console.WriteLine("ErrorCode: " + broadcast.Error.ErrorCode);
Console.WriteLine("Error message: " + broadcast.Error.Reason);
}
else
{
Console.WriteLine("Success, you can now checkout the transaction in any block explorer");
Console.WriteLine("Hash: " + tx.GetHash());
}

Related

How do I delete a blob after it has been read by my function

I have created a blob triggered Azure function App that takes data from a TSV file and splits it up and writes data to a SQL database.
after the file have been read I would like to delete it from the blob container.
I'm currently studying and this is my first C# code ever so I hope you can help me out and be specific.
I have looked at the documentation for
CloudBlockBlob blob = CloudBlobContainer.GetBlockBlobReference(???????);
blob.DeleteIfExists();
but I can't seem to find out what to put here
here is my complete function. please if you could help me out where to insert the delete command as well I would appreciate it :)
using System.IO;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Threading.Tasks;
using System.Diagnostics;
using System;
using System.Data.SqlClient;
using System.Linq;
using Azure.Storage.Blobs;
using Microsoft.WindowsAzure.Storage.Blob;
namespace FileProcessor
{
public static class FileProcessorFn
{
[FunctionName("FileProcessorFn")]
public static async Task Run([BlobTrigger("import/{name}", Connection = "AzureWebJobsStorage")]Stream myBlob, string name, TraceWriter log)
{
log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
if (myBlob.Length > 0)
{
using (var reader = new StreamReader(myBlob))
{
var lineNumber = 1;
var line = await reader.ReadLineAsync();
var raceID = 0;
while (line != null)
{
if (lineNumber == 1 )
{
var fileName = name.Substring(0, name.Length - 4);
var races = fileName.Split('-');
var item2 = new Race
{
Race_Name = races[0],
Race_Track = races[1],
Race_Sequence = races[2],
Race_Date = races[3]
};
using (var context = new GokartDbContext())
{
context.Races.Add(item2);
log.Info("new race added with the name: " + item2.Race_Name + " and the date: " + item2.Race_Date + " with Success!");
await context.SaveChangesAsync();
//context.GetValidationErrors();
//context.SaveChanges();
raceID = context.Races.Select(p => p.RaceId).Max();
}
}
if (raceID > 0 )
{
await ProcessLine(name, line, lineNumber, log, raceID);
line = await reader.ReadLineAsync();
}
lineNumber++;
}
}
}
CloudBlockBlob blob = CloudBlobContainer.GetBlockBlobReference(image/{ name});
blob.DeleteIfExists();
}
private static async Task ProcessLine(string name, string line, int lineNumber, TraceWriter log, int raceID)
{
if (string.IsNullOrWhiteSpace(line))
{
log.Warning($"{name}: {lineNumber} is empty.");
return;
}
if (lineNumber == 1)
{
log.Warning($"File header detected! Skipping....");
return;
}
//var fileName = name.Substring(0, name.Length -4);
//var races = fileName.Split('-');
var x_GPS_Longitudinal_Acceleration = "";
var x_Gyroscope_Y_Axis = "";
var x_Accelerometer_X_Axis = "";
var x_GPS_Speed = "";
var x_Temperatur_1 = "";
var x_Retning = "";
var x_Vertikalt_DOP = "";
var x_GPS_Lateral_Acceleration = "";
var x_Temperatur_fra_Barometer = "";
var x_RPM = "";
var x_Humidity = "";
var x_Gyroscope_Z_Axis = "";
var x_Intern_Temperatur = "";
var x_Lufttryk = "";
var x_Laengdegrad = "";
var x_Acceleeerometer_Z_Akse = "";
var x_Rat_Vinkel = "";
var x_GPS_Afstand = "";
var x_Batteri_Voltage = "";
var x_Vertical_Acceleration = "";
var x_Positions_DOP = "";
var x_Height = "";
var x_Breddegrad = "";
var x_Horisontal_DOP = "";
var x_Gyroscope_X_Axis = "";
var x_Accelerometer_Y_Akse = "";
var parts = line.Split('\t');
if (parts.Length > 6)
{
x_GPS_Longitudinal_Acceleration = parts[5];
x_Gyroscope_Y_Axis = parts[6];
x_Accelerometer_X_Axis = parts[7];
x_GPS_Speed = parts[8];
x_Temperatur_1 = parts[9];
x_Retning = parts[10];
x_Vertikalt_DOP = parts[11];
x_GPS_Lateral_Acceleration = parts[12];
x_Temperatur_fra_Barometer = parts[13];
x_RPM = parts[14];
x_Humidity = parts[15];
x_Gyroscope_Z_Axis = parts[16];
x_Intern_Temperatur = parts[17];
x_Lufttryk = parts[18];
x_Laengdegrad = parts[19];
x_Acceleeerometer_Z_Akse = parts[20];
x_Rat_Vinkel = parts[21];
x_GPS_Afstand = parts[22];
x_Batteri_Voltage = parts[23];
x_Vertical_Acceleration = parts[24];
x_Positions_DOP = parts[25];
x_Height = parts[26];
x_Breddegrad = parts[27];
x_Horisontal_DOP = parts[28];
x_Gyroscope_X_Axis = parts[29];
x_Accelerometer_Y_Akse = parts[30];
}
//var item2 = new Race
//{
// Race_Name = races[0],
// Race_Track = races[1],
// Race_Sequence = races[2],
// Race_Date = races[3]
//};
var item = new RaceData
{
RaceForeignKey = raceID,
Start_Date = parts[0],
Start_Time = parts[1],
Lap_Number = parts[2],
Session_Time = parts[3],
Lap_Time = parts[4],
GPS_Longitudinal_Acceleration = x_GPS_Longitudinal_Acceleration,
Gyroscope_Y_Axis = x_Gyroscope_Y_Axis,
Accelerometer_X_Axis = x_Accelerometer_X_Axis,
GPS_Speed = x_GPS_Speed,
Temperatur_1 = x_Temperatur_1,
Retning = x_Retning,
Vertikalt_DOP = x_Vertikalt_DOP,
GPS_Lateral_Acceleration = x_GPS_Lateral_Acceleration,
Temperatur_fra_Barometer = x_Temperatur_fra_Barometer,
RPM = x_RPM,
Humidity = x_Humidity,
Gyroscope_Z_Axis = x_Gyroscope_Z_Axis,
Intern_Temperatur = x_Intern_Temperatur,
Lufttryk = x_Lufttryk,
Laengdegrad = x_Laengdegrad,
Acceleeerometer_Z_Akse = x_Acceleeerometer_Z_Akse,
Rat_Vinkel = x_Rat_Vinkel,
GPS_Afstand = x_GPS_Afstand,
Batteri_Voltage = x_Batteri_Voltage,
Vertical_Acceleration = x_Vertical_Acceleration,
Positions_DOP = x_Positions_DOP,
Height = x_Height,
Breddegrad = x_Breddegrad,
Horisontal_DOP = x_Horisontal_DOP,
Gyroscope_X_Axis = x_Gyroscope_X_Axis,
Accelerometer_Y_Akse = x_Accelerometer_Y_Akse
};
using (var context = new GokartDbContext())
{
//context.Races.Add(item2);
//log.Info("new race added with the name: " + item2.Race_Name + " and the date: " + item2.Race_Date + " with Success!");
context.RaceDatas.Add(item);
log.Info($"{name}: {lineNumber} inserted task: \"{item.Start_Date}\" with id: {item.Id}.");
await context.SaveChangesAsync();
}
}
}
}
the reason I want to delete the blob after is because the function reads the file more than once. when it does I get a timeout because it takes more than 5 mins to process data. may be that's why it starts more than once.
is there a way to write this so the process is quicker?
the TSV files can hold up to 100.000 lines sometime.
looking forward to some advise on this
Robin
If you look at the MSFT API for GetBlockBlobReference method it takes in a blobName as a parameter.
So ideally you already have the name from the param on your function. You can just do
CloudBlockBlob blob = CloudBlobContainer.GetBlockBlobReference(name);
blob.DeleteIfExists();

SaveChanges() doesn't insert any records to database

I'm using Entity Framework to add new records to the database, everything goes ok without any errors, but I don't see the new record in the database.
Update code works, but insert code doesn't work. No errors appear, but no records are inserted into the database.
My code :
var DBs2 = ConnectionTools.OpenConn();
DBs2.Configuration.AutoDetectChangesEnabled = false;
DBs2.Configuration.ValidateOnSaveEnabled = false;
var resList = CreatedSerials.Where(u => u.Item4 == VID).ToList();
foreach (var r in resList)
{
// if serial id ==0 => new then add it as new
if ( r.Item7 == 0)
{
try
{
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
ss.Add(purchasesItemSerials);
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
}
else
{
var DBs350 = ConnectionTools.OpenConn();
var UpdateSerial = DBs350.purchases_item_seriels.Find(r.Item7);
UpdateSerial.pitem_ID = pitem_ID;
UpdateSerial.stitems_ID = r.Item1;
UpdateSerial. pmain_ID = PurchasesID;
UpdateSerial.pitem_virtualID = r.Item4;
UpdateSerial.pis_CustomSerial = r.Item2;
UpdateSerial.pis_ExpireDate = r.Item3;
UpdateSerial.pis_Statues = r.Item6;
UpdateSerial.ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID"));
UpdateSerial.Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice"));
DBs350.SaveChanges();
}
}
try
{
DBs2.purchases_item_seriels.AddRange(ss);
DBs2.SaveChanges();
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
I also tried :
DBs2.Configuration.AutoDetectChangesEnabled = true;
DBs2.Configuration.ValidateOnSaveEnabled = true;
but again: no data is inserted, no errors appear
I also tried :
int returnCode = DBs2.SaveChanges();
and returnCode = 0
**I also tried : inserting just a single item then SaveChanges **
// if this serial is new
var NewSerialresList = CreatedSerials.Where(u => u.Item4 == VID && u.Item7 == 0).ToList();
if (NewSerialresList.Count() > 0)
{
var ss = new List<purchases_item_seriels>();
foreach (var r in NewSerialresList)
{
try
{
mrsalesdbEntities DBs002 = new mrsalesdbEntities();
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
//ss.Add(purchasesItemSerials);
DBs002.purchases_item_seriels.Add(purchasesItemSerials);
DBs002.SaveChanges();
}
catch (Exception ex)
{
Msg.Show("", ex.ToString(), 0);
}
}
int CC = ss.Count();
}
i use this function to change the connection variables at run-time :
public static mrsalesdbEntities OpenConn()
{
mrsalesdbEntities MrSalesContext = new mrsalesdbEntities();
MrSalesContext.ChangeDatabase
(
initialCatalog: myconn.database,
port: Convert.ToUInt32( myconn.port),
userId: myconn.uid,
password: myconn.password,
dataSource: myconn.server
);
return MrSalesContext;
}
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
uint port = 3307,
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "mrsalesdbEntities")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new MySqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.Database = initialCatalog;
if ((port) != 0)
sqlCnxStringBuilder.Port = port;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.Server = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
//sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
}

C# Authorize.net Create Profile Issue

The following code is charging the card, however it is not creating the profile....any tips? I'm assuming I'm missing something, or using the wrong Type...
var opaqueData = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce };
//standard api call to retrieve response
var paymentType = new paymentType { Item = opaqueData };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // authorize and capture transaction
amount = paymentAmount,
payment = paymentType,
customer = new customerDataType()
{
type = customerTypeEnum.individual,
id = userID.ToString()
},
profile = new customerProfilePaymentType()
{
createProfile = true
}
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the contoller that will call the service
var controller = new createTransactionController(request);
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
UPDATE:
Since apparently OpaqueData is not allowed, I changed it to make the profile manually. I am getting the following Error: "Error: I00001 Successful."
// Add Payment method to Customer.
customerPaymentProfileType opaquePaymentProfile = new customerPaymentProfileType();
opaquePaymentProfile.payment = paymentType;
opaquePaymentProfile.customerType = customerTypeEnum.individual;
var request2 = new createCustomerPaymentProfileRequest
{
paymentProfile = opaquePaymentProfile,
validationMode = validationModeEnum.none,
customerProfileId = userID.ToString()
};
var controller2 = new createCustomerPaymentProfileController(request2);
controller2.Execute();
//Send Request to EndPoint
createCustomerPaymentProfileResponse response2 = controller2.GetApiResponse();
if (response2 != null && response2.messages.resultCode == messageTypeEnum.Ok)
{
if (response2 != null && response2.messages.message != null)
{
//Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId);
}
}
else
{
Utility.AppendTextToFile("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text, Server.MapPath("/pub/auth.txt"));
}
Update #2
Very confused as auth.net documentation says this code means success...so why don't I see the CIM payment method created??? RESPONSE CODE DOCS
Update #3
So I was printing out the main response message instead of the CIM request message, duh. The actual error was: "E00114 Invalid OTS Token."
Based on the the documentation, that error is usually from a used Key, so I am now generating 2 keys (One to process and One to store via CIM) but am now getting this error: "E00040 The record cannot be found."....Any ideas?
So the answer to this question is:
You can not auto create a payment profile using opaque card data, so the answer is to make it manually once you have a successful charge.
You can not use the same opaque card data to charge and store, as they are one time use, so for my web method I ended up passing 2 opaque data keys.
You have to make different calls for setting up a brand new customer and an existing customer just adding a new card. I have pasted an excerpt of my end solution below:
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? AuthorizeNet.Environment.PRODUCTION : AuthorizeNet.Environment.SANDBOX);
// define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? System.Configuration.ConfigurationManager.AppSettings["Authorize-LoginID"] : System.Configuration.ConfigurationManager.AppSettings["Authorize-LoginID-SandBox"]),
ItemElementName = ItemChoiceType.transactionKey,
Item = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? System.Configuration.ConfigurationManager.AppSettings["Authorize-TransactionKey"] : System.Configuration.ConfigurationManager.AppSettings["Authorize-TransactionKey-SandBox"])
};
if (paymentNonce.Trim() != "")
{
//set up data based on transaction
var opaqueData = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce };
//standard api call to retrieve response
var paymentType = new paymentType { Item = opaqueData };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // authorize and capture transaction
amount = paymentAmount,
payment = paymentType,
customer = new customerDataType()
{
type = customerTypeEnum.individual,
id = "YOUR_DB_USERID"
},
profile = new customerProfilePaymentType()
{
createProfile = false
}
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the contoller that will call the service
var controller = new createTransactionController(request);
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
//validate
if (response != null)
{
if (response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse.messages != null)
{
responseData.Success = true;
transactionID = response.transactionResponse.transId;
string merchID = "STORED AUTHORIZE.NET CUSTOMERID, return blank string if none!";
var opaqueData2 = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce2 };
//standard api call to retrieve response
var paymentType2 = new paymentType { Item = opaqueData2 };
customerPaymentProfileType opaquePaymentProfile = new customerPaymentProfileType();
opaquePaymentProfile.payment = paymentType2;
opaquePaymentProfile.customerType = customerTypeEnum.individual;
if (merchID == "")
{
// CREATE NEW AUTH.NET AIM CUSTOMER
List<customerPaymentProfileType> paymentProfileList = new List<customerPaymentProfileType>();
paymentProfileList.Add(opaquePaymentProfile);
customerProfileType customerProfile = new customerProfileType();
customerProfile.merchantCustomerId = "YOUR_DB_USERID";
customerProfile.paymentProfiles = paymentProfileList.ToArray();
var cimRequest = new createCustomerProfileRequest { profile = customerProfile, validationMode = validationModeEnum.none };
var cimController = new createCustomerProfileController(cimRequest); // instantiate the contoller that will call the service
cimController.Execute();
createCustomerProfileResponse cimResponse = cimController.GetApiResponse();
if (cimResponse != null && cimResponse.messages.resultCode == messageTypeEnum.Ok)
{
if (cimResponse != null && cimResponse.messages.message != null)
{
// STORE cimResponse.customerProfileId IN DATABASE FOR USER
}
}
else
{
for (int i = 0; i < cimResponse.messages.message.Length; i++)
Utility.AppendTextToFile("New Error (" + merchID + ") #" + i.ToString() + ": " + cimResponse.messages.message[i].code + " " + cimResponse.messages.message[i].text, Server.MapPath("/pub/auth.txt"));
}
}
else
{
// ADD PAYMENT PROFILE TO EXISTING AUTH.NET AIM CUSTOMER
var cimRequest = new createCustomerPaymentProfileRequest
{
paymentProfile = opaquePaymentProfile,
validationMode = validationModeEnum.none,
customerProfileId = merchID.Trim()
};
var cimController = new createCustomerPaymentProfileController(cimRequest);
cimController.Execute();
//Send Request to EndPoint
createCustomerPaymentProfileResponse cimResponse = cimController.GetApiResponse();
if (cimResponse != null && cimResponse.messages.resultCode == messageTypeEnum.Ok)
{
if (cimResponse != null && cimResponse.messages.message != null)
{
//Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId);
}
}
else
{
for (int i = 0; i < cimResponse.messages.message.Length; i++)
Utility.AppendTextToFile("Add Error (" + merchID + ") #" + i.ToString() + ": " + cimResponse.messages.message[i].code + " " + cimResponse.messages.message[i].text, Server.MapPath("/pub/auth.txt"));
}
}
}
else
{
responseData.Message = "Card Declined";
responseData.Success = false;
if (response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
}
}
else
{
responseData.Message = "Failed Transaction";
responseData.Success = false;
if (response.transactionResponse != null && response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
else
{
responseData.Message = response.messages.message[0].text;
}
}
}
else
{
responseData.Message = "Failed Transaction, Try Again!";
responseData.Success = false;
}
}
else
{
// RUN PAYMENT WITH STORED PAYMENT PROFILE ID
customerProfilePaymentType profileToCharge = new customerProfilePaymentType();
profileToCharge.customerProfileId = CustomerID;
profileToCharge.paymentProfile = new paymentProfile { paymentProfileId = PaymentID };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
amount = paymentAmount,
profile = profileToCharge
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the collector that will call the service
var controller = new createTransactionController(request);
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
//validate
if (response != null)
{
if (response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse.messages != null)
{
responseData.Success = true;
transactionID = response.transactionResponse.transId;
}
else
{
responseData.Message = "Card Declined";
responseData.Success = false;
if (response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
}
}
else
{
responseData.Message = "Failed Transaction";
responseData.Success = false;
if (response.transactionResponse != null && response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
else
{
responseData.Message = response.messages.message[0].text;
}
}
}
else
{
responseData.Message = "Failed Transaction, Try Again!";
responseData.Success = false;
}
}

ASP.NET stripe.net Cannot charge a customer that has no active card

protected void ChargePayment(object sender, EventArgs e)
{
StripeCustomer CurrentCustomer = GetCustomer();
if (CurrentCustomer == null)
{
return;
}
var myCharge = new StripeChargeCreateOptions();
myCharge.Currency = "dkk";
myCharge.CustomerId = CurrentCustomer.Id;
myCharge.Description = "KPHF Prorated Charge";
string key = "sk_test_P6GjMq1OVwmxZv5YNozAX6dY";
var chargeService = new StripeChargeService(key);
try
{
chargeService.Create(myCharge);
}
catch (StripeException ex)
{
exError.Text = ex.Message;
}
}
private StripeCustomer GetCustomer()
{
MembershipUser CurrentUser = Membership.GetUser();
var myCustomer = new StripeCustomerCreateOptions();
var myCustomer2 = new StripeCreditCardOptions();
myCustomer.Email = cMail.Text;
myCustomer2.TokenId = CreditCard.Text;
myCustomer2.ExpirationMonth = CardMonth.SelectedItem.Text;
myCustomer2.ExpirationYear = CardYear.SelectedItem.Text;
myCustomer2.Cvc = cvc.Text;
myCustomer.PlanId = "1";
var customerService = new StripeCustomerService("sk_test_P6GjMq1OVwmxZv5YNozAX6dY");
try
{
StripeCustomer result = customerService.Create(myCustomer);
return result;
}
catch (StripeException ex)
{
exError.Text = ex.Message;
return null;
}
After entering credit card info I do get customer created in the stripe system, but he's not being charged and I get following exception: "Cannot charge a customer that has no active card". Any help or tips?
you are not attaching the card with the customer. You have created the card object but not attached with the customer. Follow this syntax to add the card
var myCustomer = new StripeCustomerCreateOptions();
myCustomer.Email = "pork#email.com";
myCustomer.Description = "Johnny Tenderloin (pork#email.com)";
// setting up the card
myCustomer.SourceCard = new SourceCard()
{
Number = "4242424242424242",
ExpirationYear = "2022",
ExpirationMonth = "10",
Cvc = "1223" // optional
};
myCustomer.PlanId = *planId*; // only if you have a plan
myCustomer.TaxPercent = 20; // only if you are passing a plan, this tax percent will be added to the price.
myCustomer.Coupon = *couponId*; // only if you have a coupon
myCustomer.TrialEnd = DateTime.UtcNow.AddMonths(1); // when the customers trial ends (overrides the plan if applicable)
myCustomer.Quantity = 1; // optional, defaults to 1
var customerService = new StripeCustomerService();
StripeCustomer stripeCustomer = customerService.Create(myCustomer)
you can read more about it here stripe .net

C# Memory management (Memory leak?)

I am working on a program in WPF that basically retrieves JSON data from a WEB API and parses it then saves it to database with EF.
The problem is the memory usage of the program keeps on increasing as the time goes by. (From 20MB to 2gigs).
The following is the code that I am using.
Is there any optimization i can perform to keep the memory under a limit and say the unused objects gets deleted periodically.
void getMatchInfo_Work(object sender, DoWorkEventArgs e)
{
HttpClient client = new HttpClient();
DataConnection dc = new DataConnection();
dc.Configuration.AutoDetectChangesEnabled = false;
dc.Configuration.ValidateOnSaveEnabled = false;
do{
do
{
using (Stream s = client.GetStreamAsync("http://api.steampowered.com/IDOTA2Match_570/GetMatchHistoryBySequenceNum" +
"/v1/?key="+devkey+"&start_at_match_seq_num=" + matchseq.ToString()).Result)
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
JsonSerializer serializer = new JsonSerializer();
MatchMain match;
MatchDesc player;
RootElement matchSeq = serializer.Deserialize<RootElement>(reader);
if (matchSeq.result.status == 1)
{
foreach (var m in matchSeq.result.matches)
{
match = new MatchMain();
match.MatchID = m.match_id;
match.Win = m.radiant_win;
match.Duration = m.duration;
match.StartTime = ConvertFromUnixTimestamp(m.start_time);
match.TimeStamp = m.start_time;
match.SeqNo = m.match_seq_num;
matchseq = m.match_seq_num + 1;
match.RadTower = m.tower_status_radiant;
match.DireTower = m.tower_status_dire;
match.RadRax = m.barracks_status_radiant;
match.DireRax = m.barracks_status_dire;
match.cluster = m.cluster;
match.FBTime = m.first_blood_time;
match.LobbyType = m.lobby_type;
match.HumanCount = m.human_players;
match.LeagueID = m.leagueid;
match.GameMode = m.game_mode;
dc.MatchMain.Add(match);
count++;
foreach (var p in m.players)
{
player = new MatchDesc();
player.MatchID = m.match_id;
player.AccountID = p.account_id;
player.PlayerSlot = p.player_slot;
player.HeroID = p.hero_id;
player.First = p.item_0;
player.Second = p.item_1;
player.Third = p.item_2;
player.Fourth = p.item_3;
player.Fifth = p.item_4;
player.Sixth = p.item_5;
player.Kills = p.kills;
player.Deaths = p.deaths;
player.Assists = p.assists;
player.LeaverStatus = p.leaver_status;
player.Gold = p.gold;
player.LastHits = p.last_hits;
player.Denies = p.denies;
player.GPM = p.gold_per_min;
player.XPM = p.xp_per_min;
player.GoldSpent = p.gold_spent;
player.HeroDamage = p.hero_damage;
player.TowerDamage = p.tower_damage;
player.Healing = p.hero_healing;
player.HeroLevel = p.level;
dc.MatchDesc.Add(player);
}
getMatchInfo.ReportProgress(1);
}
dc.SaveChanges();
}
else
{
result = 0;
}
}
} while (result == 1);
Thread.Sleep(60000);
}while( result>-999);
}
void getMatchInfo_Progress(object sender, ProgressChangedEventArgs e)
{
if (result != 0)
{
txtProgress.Text = count + " matches updated in database and continuing.";
}
else
{
txtProgress.Text = count + " matches updated in database and waiting for API.";
}
txtTime.Text =sw.Elapsed.Hours.ToString()+" hours "+ sw.Elapsed.Minutes.ToString()+" minutes "+
sw.Elapsed.Seconds.ToString()+" seconds";
}
Edit: Button click code
private void btnRetrieveData_Click(object sender, RoutedEventArgs e)
{
getMatchInfo.DoWork += new DoWorkEventHandler(getMatchInfo_Work);
getMatchInfo.ProgressChanged += new ProgressChangedEventHandler(getMatchInfo_Progress);
getMatchInfo.WorkerReportsProgress = true;
txtProgress.Text = "Process started";
matchseq = Convert.ToInt64(txtSeqNo.Text);
devkey = txtKey.Text;
sw.Start();
getMatchInfo.RunWorkerAsync();
}
DataConnection context keeps tracking all objects that it ever saw. Put creation of dc inside the loop and dispose it every time. You don't need the context after each SaveChanges is called.

Categories

Resources