public void TestTransactionLogOptions() { using (TempFile temp = new TempFile()) { temp.Delete(); var opt = new TransactionLogOptions<int, string>(temp.TempPath, PrimitiveSerializer.Int32, PrimitiveSerializer.String); //FileName Assert.AreEqual(temp.TempPath, opt.FileName); //Key/Value serializers Assert.IsTrue(ReferenceEquals(opt.KeySerializer, PrimitiveSerializer.Int32)); Assert.IsTrue(ReferenceEquals(opt.ValueSerializer, PrimitiveSerializer.String)); //FileOptions Assert.AreEqual(FileOptions.WriteThrough, opt.FileOptions); Assert.AreEqual(FileOptions.WriteThrough | FileOptions.Asynchronous, opt.FileOptions |= FileOptions.Asynchronous); //Read Only Assert.AreEqual(false, opt.ReadOnly); Assert.AreEqual(true, opt.ReadOnly = true); //File Buffer Assert.AreEqual(8, opt.FileBuffer); Assert.AreEqual(0x40000, opt.FileBuffer = 0x40000); //Clone Assert.IsFalse(ReferenceEquals(opt, opt.Clone())); using(TransactionLog<int, string> log = new TransactionLog<int,string>(opt)) Assert.AreEqual(0, log.Size); } }
public void Start_the_persistence_engine_with_a_non_empty_transaction_log() { var transaction1 = MakeTransaction( new Trade(1, 5465, "TATA", DateTime.Now.Date, 150), new Trade(2, 5467, "TATA", DateTime.Now.Date, 180) ); var transaction2 = MakeTransaction( new Trade(2, 5467, "TOTO", DateTime.Now.Date, 190) ); var log = new TransactionLog(); log.NewTransaction( SerializationHelper.ObjectToBytes(transaction1, SerializationMode.ProtocolBuffers, null)); log.NewTransaction( SerializationHelper.ObjectToBytes(transaction2, SerializationMode.ProtocolBuffers, null)); log.Dispose(); var engine = new PersistenceEngine(); engine.Start(); engine.WaitForPendingTransactions(); engine.Stop(); var processor = new TestProcessor(); //reload data from persistent storage var unused = new ReliableStorage(processor); unused.LoadPersistentData(); unused.Dispose(); Assert.AreEqual(2, processor.LoadedObjects.Count); var reloaded = processor.LoadedObjects.Select(CachedObject.Unpack <Trade>).First(t => t.Id == 2); Assert.AreEqual("TOTO", reloaded.Folder); //reload data from transaction log. Check no more pending transactions log = new TransactionLog(); Assert.AreEqual(0, log.PendingTransactionsCount); log.Dispose(); }
public void TestAddOperation() { using (TempFile tmp = new TempFile()) using (var log = new TransactionLog<int, string>(Options(tmp))) { var token = log.BeginTransaction(); log.AddValue(ref token, 1, "test"); log.CommitTransaction(ref token); var test = new Dictionary<int, string>(); log.ReplayLog(test); Assert.AreEqual(1, test.Count); Assert.IsTrue(test.ContainsKey(1)); Assert.AreEqual("test", test[1]); } }
public void LogTransaction(CustomerAccount customerAccount, decimal amount, TransactionType transactionType)//overload for customers accounts { var transaction = new TransactionLog { Name = customerAccount.AccountName, Amount = amount, Date = DateTime.Now, AccountCode = Convert.ToInt64(customerAccount.AccountNumber), TransactionType = transactionType, MainAccountCategory = customerAccount.AccountType == AccountType.Loan //Exception: Loan accounts are assets ? MainAccountCategory.Asset : MainAccountCategory.Liability, }; _db.Add(transaction); _db.Save(transaction); }
private static async Task <bool> SendDeviceToCloudMessagesAsync(TransactionLog transactionLog) { try { var messageString = JsonConvert.SerializeObject(transactionLog); var message = new Message(Encoding.ASCII.GetBytes(messageString)); await deviceClient.SendEventAsync(message); return(true); } catch (Exception ex) { var message = ex.Message; return(false); } }
public PieDatabase(TransactionStore store, SerializerSettings settings = null, Func<DataStore> createDataStore = null) { settings = settings ?? new SerializerSettings(); createDataStore = createDataStore ?? (() => new DataStore(settings)); var writeTransaction = new Func<GenericTransaction<DataStore>, string>( tran => JsonConvert.SerializeObject(tran, settings)) .Then(Funcs.AppendStringToStream); var readTransactions = Funcs.StreamToStreamReader.Then(Funcs.ReadStringsFromStreamReader) .ThenForEach( str => JsonConvert.DeserializeObject<GenericTransaction<DataStore>>(str, settings)); _transactionLog = new TransactionLog<DataStore>(createDataStore, writeTransaction, readTransactions, store); DataStore = new Lazy<DataStore>(() => _transactionLog.Value); }
public void TestCommitEmptyAndReplay() { using (TempFile tmp = new TempFile()) using (var log = new TransactionLog <int, string>(Options(tmp))) { var token = log.BeginTransaction(); log.CommitTransaction(ref token);//commit empty token = log.BeginTransaction(); log.AddValue(ref token, 1, "test"); log.CommitTransaction(ref token);//add value var test = new Dictionary <int, string>(); log.ReplayLog(test); Assert.AreEqual(1, test.Count); } }
public void TestAddOperation() { using (TempFile tmp = new TempFile()) using (var log = new TransactionLog <int, string>(Options(tmp))) { var token = log.BeginTransaction(); log.AddValue(ref token, 1, "test"); log.CommitTransaction(ref token); var test = new Dictionary <int, string>(); log.ReplayLog(test); Assert.AreEqual(1, test.Count); Assert.IsTrue(test.ContainsKey(1)); Assert.AreEqual("test", test[1]); } }
public void Transaction(TransactionLogEnum type, string username, string eventCode) { User user = _userRepository.GetAll().Where(x => x.Username.Equals(username)).FirstOrDefault(); if (user != null) { TransactionLog data = new TransactionLog { Action = type.ToString(), Username = user.Username, EventCode = eventCode, Time = Clock.Now }; Log.ForContext("Data", JsonConvert.SerializeObject(data)).Information(TypeLogEnum.TransactionLog.ToString()); } }
public override int GetHashCode() { int hash = 1; if (State != 0) { hash ^= State.GetHashCode(); } if (ExpirationMs != 0UL) { hash ^= ExpirationMs.GetHashCode(); } if (player_ != null) { hash ^= Player.GetHashCode(); } if (friend_ != null) { hash ^= Friend.GetHashCode(); } if (TradingS2CellId != 0L) { hash ^= TradingS2CellId.GetHashCode(); } if (TransactionLog.Length != 0) { hash ^= TransactionLog.GetHashCode(); } if (friendshipLevelData_ != null) { hash ^= FriendshipLevelData.GetHashCode(); } if (IsSpecialTrading != false) { hash ^= IsSpecialTrading.GetHashCode(); } if (preTradingFriendshipLevel_ != null) { hash ^= PreTradingFriendshipLevel.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
private void RefreshFinances() { // clear the panel financeListView.Items.Clear(); TransactionLog temp = new TransactionLog(); foreach (TransactionLog log in this.guest.Wallet.History) { financeListView.Items.Add(new ListViewItem(new string[] { (-log.Amount).ToString(), log.Time.ToString(), log.Reason, })); } }
public static async Task <bool> PushToWebApi(string serverUrl, TransactionLog transactionLog) { try { var json = JsonConvert.SerializeObject(transactionLog); var url = new Uri(serverUrl); var client = new WebClient(); client.Headers.Add("Content-Type", "application/json"); await client.UploadStringTaskAsync(url, json); return(true); } catch (Exception) { return(false); } }
public int InsertLogs(int itemId, int quantiy, DateTime dateReceived, int itemType) { TransactionLogRepository transactionLogRepo = new TransactionLogRepository(); TransactionLog transactionLog = new TransactionLog { ItemId = itemId, Quantity = quantiy, TransactionMethodId = (int)ETransactionMethod.Receiving, CompanyId = Sessions.CompanyId.Value, Date = dateReceived, ItemTypeId = itemType }; transactionLogRepo.Add(transactionLog); return(transactionLog.Id); }
public void InsertTransactionLog(TransactionLog tranLog) { SpCall call = new SpCall("COR.TRANSACTION_LOG_INSERT"); call.SetVarchar("@TRAN_CODE", tranLog.TransactionCode); call.SetBinary("@TRANSACTION_LOG", tranLog.Log); call.SetVarchar("@TRANSACTION_JSON", tranLog.LogJson); call.SetVarchar("@TRANSACTION_STATUS", tranLog.Status); call.SetBigInt("@TRANSACTION_OBJECT_ID", tranLog.LogObjectId); call.SetVarchar("@ACTION_TYPE", tranLog.ActionType); call.SetVarchar("@REQUEST_TYPE", tranLog.RequestType); call.SetDateTime("@CREATE_DATE", DateTime.Now); call.SetVarchar("@CREATE_USER", tranLog.CreatedUser); call.SetDecimal("@DURATION", tranLog.Duration); long id = db.ExecuteScalar <long>(call); tranLog.Id = id; }
public void InsertTransactionHistory() { var transactionRepo = new TransactionRepo(); var log = new TransactionLog { Type = TransactionType.SuccessfulPurchase, PlayerName = "Lionel Messi", SearchPrice = 150000, //SellPrice = 175000, TransactionDate = DateTime.Now, UserName = "******" }; transactionRepo.InsertTransactionLog(log); Assert.IsTrue(log.TransactionId.Length > 0); }
private static void PrintChanges(TransactionLog log) { foreach (var change in log.Changes) { Console.WriteLine(@"Entity: #{0}={1}, Change: {2}", change.Entity.EntityLabel, change.Entity.GetType().Name, change.ChangeType); Console.WriteLine(@" Original entity: {0}", change.OriginalEntity); Console.WriteLine(@" Current entity: {0}", change.CurrentEntity); if (change.ChangeType != ChangeType.Modified) { continue; } foreach (var prop in change.ChangedProperties) { Console.WriteLine(@" Property '{0}' changed from {1} to {2}", prop.Name, prop.OriginalValue, prop.CurrentValue); } } }
public void SetTransactionLog(TransactionLog log) { gridControl1.DataSource = log.TransCollection; // should be based on symbolname // select the last entry and scroll to it gridView1.BestFitColumns(); //gridControl1.RefreshDataSource(); //gridView1.FocusedRowHandle = gridView1.RowCount - 1; /*gridView1.SelectRow(gridView1.RowCount - 1); * if (gridView1.IsRowVisible(gridView1.RowCount - 1) != DevExpress.XtraGrid.Views.Grid.RowVisibleState.Visible) * { * gridView1.MakeRowVisible(gridView1.RowCount - 1, true); * }*/ UpdateButtons(); }
public static void SaveError(int OrderId, string Description, string Request, string Response) { TransactionLog transactionLog = new TransactionLog(); try { transactionLog.OrderId = OrderId; transactionLog.Description = Description; transactionLog.Request = Request; transactionLog.Response = Response; transactionLog.LogDate = DateTime.Now; Repository <TransactionLog> userRep = new Repository <TransactionLog>(); userRep.Add(transactionLog); userRep.Save(); } catch { } }
public TransactionInfo WireTransferToAccount(Claim claim, TransactionRequest request) { if (request.Amount <= 0) { throw new NullReferenceException("Amount to transfer must be greater than 0"); } Users accountUser = _accountMapper.GetAccountNumberByUserName(claim); var accounts = _unitOfWork.Accounts .GetFiltered(i => i.AccountId == accountUser.Account || i.AccountId == request.AccountToTransfer); var accountToRemote = accounts.FirstOrDefault(i => i.AccountId == accountUser.Account); var accountToAdd = accounts.FirstOrDefault(i => i.AccountId == request.AccountToTransfer); if (accountToAdd == null) { return new TransactionInfo { TransactionException = new Exception("Account to Transfer does not exists") } } ; accountToRemote.Balance -= request.Amount; accountToAdd.Balance += request.Amount; var transactionLog = new TransactionLog { DestinationAccount = accountToAdd.AccountId, SourceAccount = accountToRemote.AccountId, TransactionType = TransactionTypes.WireTransfer, UserName = accountUser.UserName, Date = DateTime.Now, Amount = request.Amount }; _unitOfWork.TransactionLog.Add(transactionLog); _unitOfWork.Commit(); return(new TransactionInfo { PrimaryAccount = accountToRemote.AccountId, PrimaryAccountBalance = accountToRemote.Balance, SecondaryAccount = accountToAdd.AccountId, TransactionType = TransactionTypes.WireTransfer }); } }
/// <summary> /// Converts from non sale tender operation type to transaction log. /// </summary> /// <param name="nonSalesTransaction">Non sale tender transaction.</param> /// <returns>Returns the transaction log entity.</returns> private TransactionLog Convert(NonSalesTransaction nonSalesTransaction) { ThrowIf.NullOrWhiteSpace(nonSalesTransaction.Id, "nonSalesTransaction.Id"); var transaction = new TransactionLog(); transaction.Id = nonSalesTransaction.Id; transaction.StoreId = nonSalesTransaction.StoreId; transaction.TransactionType = (TransactionType)nonSalesTransaction.TransactionTypeValue; transaction.StaffId = nonSalesTransaction.StaffId; transaction.ShiftId = nonSalesTransaction.ShiftId; transaction.ShiftTerminalId = nonSalesTransaction.ShiftTerminalId; transaction.TerminalId = nonSalesTransaction.TerminalId; transaction.Description = nonSalesTransaction.Description; transaction.ChannelCurrencyExchangeRate = nonSalesTransaction.ChannelCurrencyExchangeRate; transaction.ChannelCurrency = nonSalesTransaction.ChannelCurrency; return(transaction); }
public static bool SaveTransactionLog(ITransactionLogAppService _tranService, string tranForm, string tranType, string id, string userName) { try { TransactionLog tranLog = new TransactionLog(); tranLog.TranForm = tranForm; tranLog.TranType = tranType; tranLog.TranDateTime = DateTime.Now.ToString(); tranLog.TranNo = id; tranLog.UserName = userName; _tranService.Add(tranLog); _tranService.Save(); return(true); } catch (Exception ex) { return(false); } }
public async Task <IActionResult> Run( [HttpTrigger(Constants.AUTHORIZATION_LEVEL, "post", Route = "accepttaskweek")] HttpRequest req, ILogger log, CancellationToken ct) { TaskWeek data = null; try { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); data = JsonConvert.DeserializeObject <TaskWeek>(requestBody); log.LogTrace($"AcceptTaskWeek function processed a request for taskWeekId:{data.Id}."); var userIdentifier = await GetTargetUserIdentifier(req); if (!await IsParent(req)) { throw new SecurityException("Invalid attempt to accept a taskweek by an invalid user"); } await _taskWeekService.Update(data, false); var account = await _accountService.GetByUser(data.UserIdentifier); account.Balance += data.Value; await _accountService.Update(account, false); var transaction = new TransactionLog() { AccountId = account.Id.Value, UserIdentifier = req.GetUserIdentifier(), Amount = data.Value, CategoryId = (int)Constants.TransactionCategory.Deposit, Date = DateTime.Now, Description = "Weekly allowance deposit." }; await _transactionLogService.Create(transaction, false); await _transactionLogService.SaveChanges(); } catch (Exception exception) { return(new BadRequestObjectResult($"Error trying to execute PutTaskWeek. {exception.Message}")); } return(new OkObjectResult(data.Id.Value)); }
public PieDatabase(TransactionStore store, SerializerSettings settings = null, Func <DataStore> createDataStore = null) { settings = settings ?? new SerializerSettings(); createDataStore = createDataStore ?? (() => new DataStore(settings)); var writeTransaction = new Func <GenericTransaction <DataStore>, string>( tran => JsonConvert.SerializeObject(tran, settings)) .Then(Funcs.AppendStringToStream); var readTransactions = Funcs.StreamToStreamReader.Then(Funcs.ReadStringsFromStreamReader) .ThenForEach( str => JsonConvert.DeserializeObject <GenericTransaction <DataStore> >(str, settings)); _transactionLog = new TransactionLog <DataStore>(createDataStore, writeTransaction, readTransactions, store); DataStore = new Lazy <DataStore>(() => _transactionLog.Value); }
public double CalculateDiscount(int userid, TransactionLog trxRecord) { try { string user = LoggedInuser.LoggedInUser(); if (user != null || user != "" || user != ConfigurationManager.AppSettings["PaelytEmail"]) { var DiscountAmount = 0; var DiscountValue = 0; MyUtility.SaveWallet(trxRecord, "Discount", userid, DiscountValue, DiscountAmount); } return(0); } catch (Exception ex) { WebLog.Log(ex.Message.ToString()); return(0); } }
public void CreateTransactionLog(TransactionLog transactionLog, out string recipientName) { var recipient = _db.Users .FirstOrDefault(el => el.Id == transactionLog.RecipientId); recipientName = recipient.Name; _currentUser.Balance -= transactionLog.Sum; recipient.Balance += transactionLog.Sum; transactionLog.SenderId = _currentUser.Id; transactionLog.CreateDateTime = DateTime.Now; transactionLog.TotalRecipient = recipient.Balance; transactionLog.TotalSender = _currentUser.Balance; _db.TransactionLogs.Add(transactionLog); _db.SaveChanges(); }
/// <summary> /// Converts from non sale tender operation type to transaction log. /// </summary> /// <param name="tenderTransaction">Non sale tender transaction.</param> /// <returns>Returns the transaction log entity.</returns> private TransactionLog Convert(DropAndDeclareTransaction tenderTransaction) { ThrowIf.NullOrWhiteSpace(tenderTransaction.Id, "tenderTransaction.Id"); var transaction = new TransactionLog(); transaction.Id = tenderTransaction.Id; transaction.StoreId = tenderTransaction.StoreId; transaction.TransactionType = (TransactionType)tenderTransaction.TransactionType; transaction.StaffId = tenderTransaction.StaffId; transaction.ShiftId = tenderTransaction.ShiftId; transaction.ShiftTerminalId = tenderTransaction.ShiftTerminalId; transaction.TerminalId = tenderTransaction.TerminalId; transaction.ChannelCurrencyExchangeRate = tenderTransaction.ChannelCurrencyExchangeRate; transaction.ChannelCurrency = tenderTransaction.ChannelCurrency; transaction.Description = tenderTransaction.Description; return(transaction); }
public static int SaveWallet(TransactionLog tLog, string narration, int userID, double discountValue, double discountamount = 0) { int walletID = 0; try { if (userID == 0) { return(walletID); } GlobalTransactEntitiesData pwr = new GlobalTransactEntitiesData(); var qry = pwr.CustomerWallets .Where(x => x.RefNumber == tLog.ReferenceNumber && x.User_FK == userID).ToList(); if (qry == null || qry.Count == 0) { double walletPoint = Convert.ToDouble(tLog.Amount) * 0.01 * discountValue; CustomerWallet cwObj = new CustomerWallet { Credit = discountamount == 0 ? walletPoint : discountamount, CustomerID = tLog.CustomerID, Debit = 0, IsVisible = 1, Narration = narration, RefNumber = tLog.ReferenceNumber, TrnDate = tLog.TrnDate, User_FK = userID, ValueDate = Utility.GetCurrentDateTime().ToString("yyyy/MM/dd") }; pwr.CustomerWallets.Add(cwObj); pwr.SaveChanges(); walletID = cwObj.ID; // return cwObj.ID; } } catch (Exception ex) { // WebLog.Log(ex.Message + "##", ex.StackTrace); } return(walletID); }
public static void AddTransactionHistoryParams(NpgsqlCommand cmd, TransactionLog log) { string postgresSucksAtEnums; switch (log.Type) { case TransactionType.SuccessfulPurchase: postgresSucksAtEnums = "SuccessfulPurchase"; break; case TransactionType.FailedPurchase: postgresSucksAtEnums = "FailedPurchase"; break; case TransactionType.SuccessfulSale: postgresSucksAtEnums = "SuccessfulSale"; break; case TransactionType.FailedSale: postgresSucksAtEnums = "FailedSale"; break; default: throw new ArgumentOutOfRangeException(); } cmd.Parameters.AddWithValue("transactionType", postgresSucksAtEnums); cmd.Parameters.AddWithValue("playerName", log.PlayerName); cmd.Parameters.AddWithValue("searchPrice", log.SearchPrice); if (log.SellPrice == null) { cmd.Parameters.AddWithValue("sellPrice", DBNull.Value); } else { cmd.Parameters.AddWithValue("sellPrice", log.SellPrice); } cmd.Parameters.AddWithValue("transactionDate", log.TransactionDate); cmd.Parameters.AddWithValue("userName", log.UserName); }
public async void GetTransactions() { User user = (User)HttpContext.Items["User"]; try { TransactionLog log = new TransactionLog(); if (user.Username == "admin") { //get transactions from database ArrayList trans = TransactionLog.GetAllTransactions(); HttpContext.Response.ContentType = "application/json"; await HttpContext.Response.Body.WriteAsync(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(trans))); log.Type = "Admin Viewed Logs"; } else { HttpContext.Response.StatusCode = 400; await HttpContext.Response.Body.WriteAsync(Encoding.ASCII.GetBytes("You do not have permission.")); log.Type = "Non Admin Blocked from Logs"; } log.Username = user.Username; HttpContext.Items["Log"] = log; } catch (Exception e) { Console.WriteLine(e.StackTrace); User u = (User)HttpContext.Items["User"]; TransactionLog log = new TransactionLog { Type = "Non Admin Blocked from Logs", Username = u.Username }; HttpContext.Items["Log"] = log; HttpContext.Response.StatusCode = 400; await HttpContext.Response.Body.WriteAsync(Encoding.ASCII.GetBytes("You do not have permission.")); } }
public void TestLogCorruption() { using (TempFile tmp = new TempFile()) { using (var log = new TransactionLog <int, string>(Options(tmp))) { var token = log.BeginTransaction(); log.AddValue(ref token, 1, Guid.NewGuid().ToString()); log.CommitTransaction(ref token); var test = new Dictionary <int, string>(); long offset = 0; log.ReplayLog(test, ref offset); Assert.AreEqual(1, test.Count); } byte[] bytes = tmp.ReadAllBytes(); var TestVariants = new Converter <KeyValuePair <int, byte[]>, byte[]>[] { kv => { kv.Value[kv.Key] ^= 0xff; return(kv.Value); }, kv => { kv.Value[kv.Key] = 0xff; return(kv.Value); }, kv => { byte[] b = kv.Value; Array.Resize(ref b, kv.Key); return(b); }, }; for (int corruptionIx = 0; corruptionIx < bytes.Length; corruptionIx++) { foreach (var testcase in TestVariants) { byte[] corrupt = testcase(new KeyValuePair <int, byte[]>(corruptionIx, (byte[])bytes.Clone())); tmp.WriteAllBytes(corrupt); using (var log = new TransactionLog <int, string>(Options(tmp))) { var test = new Dictionary <int, string>(); log.ReplayLog(test); Assert.AreEqual(0, test.Count); } Assert.IsFalse(File.Exists(tmp.TempPath)); } } } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { //Bu attribute ile donatilmis her action, //kendi islemini kayit altina alir. TransactionLog olarak kayit eder. var IpAddress = HttpContext.Current.Request.UserHostAddress; var sessionData = HttpContext.Current.Session["TurkcellSessionId"]; string TurkcellSession = sessionData == null ? null : sessionData.ToString(); BaseController controllerDefault = (BaseController)filterContext.Controller; //SessionManager s = new SessionManager(); UserFb userData = null; var sessionManager = SessionManager.GetInstance(); var serializer = new Serialize(); if (sessionManager.HasSessionUser) { //Sessionda user bilgileri var ise, bunlari deserilaze edip data'ya aktariyoruz. userData = (UserFb)serializer.DeserializeObject(sessionManager.SessionUser, typeof(UserFb)); } string msisdn = userData == null ? "" : userData.Msisdn; int userId = userData == null ? 0 : userData.Id; string userFbId = userData == null ? "" : userData.FbId; TransactionLog log = new TransactionLog(); log.Status = LogService.LogDefinitions.ActionCall.ToString(); log.Naming = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName + "::" + filterContext.ActionDescriptor.ActionName; log.IP = IpAddress; log.Msisdn = msisdn; log.UserId = userId; log.FbId = userFbId; log.TcellSession = TurkcellSession; log.Details = ActionDescription; LogService logger = LogService.GetInstance(); logger.Log <TransactionLog>(log); base.OnActionExecuting(filterContext); }
/// <summary> /// 创建交易日志 /// </summary> /// <returns></returns> private async Task <TransactionLog> CreateToPayTransactionInfo(PayInputBase input, Exception exception = null) { var transactionInfo = new TransactionInfo() { Amount = input.TotalAmount, CustomData = input.CustomData, OutTradeNo = input.OutTradeNo ?? GenerateOutTradeNo(), PayChannel = input.PayChannel, Subject = input.Subject, TransactionState = TransactionStates.NotPay, //TransactionId = "", Exception = exception }; TransactionLog transactionLog = null; transactionLog = _transactionLogHelper.CreateTransactionLog(transactionInfo); await _transactionLogHelper.SaveAsync(transactionLog); return(transactionLog); }
public void TestMultipleWriteAndReplay() { using (TempFile tmp = new TempFile()) using (var log = new TransactionLog <int, string>(Options(tmp))) { var token = log.BeginTransaction(); log.AddValue(ref token, 1, "test"); log.AddValue(ref token, 2, "test"); log.AddValue(ref token, 3, "test"); log.CommitTransaction(ref token); var test = new Dictionary <int, string>(); log.ReplayLog(test); Assert.AreEqual(3, test.Count); for (int i = 1; i <= 3; i++) { Assert.AreEqual("test", test[i]); } } }
public void TestBenchmarkWriteSpeed() { //Write 2,147,483,776 bytes in: 00:02:09.7934237 (in chunks of 128 bytes) //Write 4,295,032,832 bytes in: 00:00:18.4990581 (in chunks of 65536 bytes) //Logged 2,398,000,000 bytes in: 00:00:36.7621027 string newpath = Path.Combine(@"C:\Temp\LogTest\", Guid.NewGuid() + ".tmp"); using (TempFile tmp = TempFile.Attach(newpath)) { byte[] bytes; DateTime start; //bytes = new byte[128]; //new Random().NextBytes(bytes); //start = DateTime.UtcNow; //using (var io = new FileStream(tmp.TempPath, FileMode.Append, FileAccess.Write, FileShare.Read, 8)) //{ // for (int i = 0; i <= 16777216; i++) // io.Write(bytes, 0, 128); //} //Console.WriteLine("Write {0:n0} bytes in: {1}", tmp.Length, DateTime.UtcNow - start); //tmp.Delete(); var options = new TransactionLogOptions<Guid, byte[]>( tmp.TempPath, PrimitiveSerializer.Guid, PrimitiveSerializer.Bytes) { FileBuffer = ushort.MaxValue, FileOptions = FileOptions.None | FileOptions.SequentialScan, }; Guid[] ids = new Guid[1000000]; for (int i = 0; i < ids.Length; i++) ids[i] = Guid.NewGuid(); bytes = new byte[100]; new Random().NextBytes(bytes); start = DateTime.UtcNow; using (var log = new TransactionLog<Guid, byte[]>(options)) { foreach(Guid id in ids) { var token = log.BeginTransaction(); for (int i = 0; i < 20; i++) log.AddValue(ref token, id, bytes); log.CommitTransaction(ref token); } } Console.WriteLine("Logged {0:n0} bytes in: {1}", tmp.Length, DateTime.UtcNow - start); } }
public void TestSyncFromLogging() { using (var tempFile = new TempFile()) using (var logfile = new TempFile()) using (var tempCopy = new TempFile()) { var options = new BPlusTree<int, string>.OptionsV2(new PrimitiveSerializer(), new PrimitiveSerializer()) { CreateFile = CreatePolicy.Always, FileName = tempFile.TempPath, TransactionLogFileName = logfile.TempPath, }.CalcBTreeOrder(4, 10); var readcopy = options.Clone(); readcopy.FileName = tempCopy.TempPath; readcopy.StoragePerformance = StoragePerformance.Fastest; using (var tree = new BPlusTree<int, string>(options)) using (var copy = new BPlusTree<int, string>(readcopy)) using (var tlog = new TransactionLog<int, string>( new TransactionLogOptions<int, string>(logfile.TempPath, PrimitiveSerializer.Int32, PrimitiveSerializer.String) { ReadOnly = true })) { tree.Add(0, "0"); tree.Commit(); long logpos = 0; copy.EnableCount(); //start by copying the data from tree's file into the copy instance: copy.BulkInsert( BPlusTree<int, string>.EnumerateFile(options), new BulkInsertOptions { InputIsSorted = true, CommitOnCompletion = false, ReplaceContents = true } ); Assert.AreEqual(1, copy.Count); Assert.AreEqual("0", copy[0]); tlog.ReplayLog(copy, ref logpos); Assert.AreEqual(1, copy.Count); //insert some data... tree.AddRange(MakeValues(1, 99)); tlog.ReplayLog(copy, ref logpos); Assert.AreEqual(100, copy.Count); //insert some data... for (int i = 0; i < 100; i++) tree.Remove(i); tlog.ReplayLog(copy, ref logpos); Assert.AreEqual(0, copy.Count); tree.AddRange(MakeValues(1000, 1000)); tlog.ReplayLog(copy, ref logpos); Assert.AreEqual(1000, copy.Count); } } }
public void TestMultipleTransAndReplay() { using (TempFile tmp = new TempFile()) { var opts = Options(tmp); using (var log = new TransactionLog<int, string>(opts)) { var token = log.BeginTransaction(); log.AddValue(ref token, 1, "test"); log.CommitTransaction(ref token); token = log.BeginTransaction(); log.AddValue(ref token, 2, "test"); log.CommitTransaction(ref token); token = log.BeginTransaction(); log.AddValue(ref token, 3, "test"); log.CommitTransaction(ref token); log.Close(); } using (var log = new TransactionLog<int, string>(opts)) { var test = new Dictionary<int, string>(); log.ReplayLog(test); Assert.AreEqual(3, test.Count); for (int i = 1; i <= 3; i++) Assert.AreEqual("test", test[i]); } } }
public void TestRemoveOperation() { using (TempFile tmp = new TempFile()) using (var log = new TransactionLog<int, string>(Options(tmp))) { var token = log.BeginTransaction(); log.RemoveValue(ref token, 1); log.CommitTransaction(ref token); var test = new Dictionary<int, string>(); test.Add(1, null); log.ReplayLog(test); Assert.AreEqual(0, test.Count); } }
public void CommitCallback(TransactionLog transactionLog) { foreach (var eventToRaise in transactionLog.Events) { _arguments.Enqueue(eventToRaise); } }
public void TestLogWithJunkAppended() { string testdata = Guid.NewGuid().ToString(); using (TempFile tmp = new TempFile()) { using (var log = new TransactionLog<int, string>(Options(tmp))) { var token = log.BeginTransaction(); for (int i = 0; i < 20; i++) log.AddValue(ref token, i, testdata); log.CommitTransaction(ref token); } using (var log = new TransactionLog<int, string>(Options(tmp))) { var test = new Dictionary<int, string>(); log.ReplayLog(test); Assert.AreEqual(20, test.Count); for (int i = 0; i < 20; i++) Assert.AreEqual(testdata, test[i]); } long flength; byte[] junk = new byte[512]; new Random().NextBytes(junk); using(Stream io = File.OpenWrite(tmp.TempPath)) { flength = io.Seek(0, SeekOrigin.End); io.Write(junk, 0, junk.Length); } using (var log = new TransactionLog<int, string>(Options(tmp))) { var test = new Dictionary<int, string>(); log.ReplayLog(test); Assert.AreEqual(20, test.Count); for (int i = 0; i < 20; i++) Assert.AreEqual(testdata, test[i]); } // The file will be truncated to a valid position Assert.AreEqual(flength, new FileInfo(tmp.TempPath).Length); } }
public void TestCommitEmptyAndReplay() { using (TempFile tmp = new TempFile()) using (var log = new TransactionLog<int, string>(Options(tmp))) { var token = log.BeginTransaction(); log.CommitTransaction(ref token);//commit empty token = log.BeginTransaction(); log.AddValue(ref token, 1, "test"); log.CommitTransaction(ref token);//add value var test = new Dictionary<int, string>(); log.ReplayLog(test); Assert.AreEqual(1, test.Count); } }
public void test_plan() { var customer = new Customer(); TransactionLog log = new TransactionLog() { Action = "UPSERT", Object = JsonConvert.SerializeObject(customer), ObjectId = $"{customer.PartitionKey}|{customer.RowKey}", TableName = "Customer", Type = "Customer" }; var action = log.Create("UseDevelopmentStorage=True"); action?.Invoke(); }
public void TestSingleRollbackAndReplay() { using (TempFile tmp = new TempFile()) using (var log = new TransactionLog<int, string>(Options(tmp))) { var token = log.BeginTransaction(); log.AddValue(ref token, 1, "test"); log.RollbackTransaction(ref token); var test = new Dictionary<int, string>(); log.ReplayLog(test); Assert.AreEqual(0, test.Count); } }
public void TestProgressiveReplay() { using (TempFile tmp = new TempFile()) using (var log = new TransactionLog<int, string>(Options(tmp))) { var token = log.BeginTransaction(); log.AddValue(ref token, 1, "test"); log.CommitTransaction(ref token); var test = new Dictionary<int, string>(); long position = 0; log.ReplayLog(test, ref position); Assert.AreEqual(1, test.Count); test.Clear(); log.ReplayLog(test, ref position); Assert.AreEqual(0, test.Count); token = log.BeginTransaction(); log.AddValue(ref token, 2, "test"); log.CommitTransaction(ref token); log.ReplayLog(test, ref position); Assert.AreEqual(1, test.Count); Assert.IsTrue(test.ContainsKey(2)); Assert.AreEqual("test", test[2]); } }
public void TestPositionAndReplay() { using (TempFile tmp = new TempFile()) using (var log = new TransactionLog<int, string>(Options(tmp))) { var token = log.BeginTransaction(); log.AddValue(ref token, 1, "test"); log.CommitTransaction(ref token); long size = long.MaxValue; log.ReplayLog(null, ref size); token = log.BeginTransaction(); log.AddValue(ref token, 2, "test"); log.CommitTransaction(ref token); var test = new Dictionary<int, string>(); log.ReplayLog(test, ref size); Assert.AreEqual(1, test.Count); Assert.AreEqual("test", test[2]); } }
public void TestReplayEmpty() { using (TempFile tmp = new TempFile()) using (var log = new TransactionLog<int, string>(Options(tmp))) { var test = new Dictionary<int, string>(); log.ReplayLog(test); Assert.AreEqual(0, test.Count); } }
public void TestLogCorruption() { using (TempFile tmp = new TempFile()) { using (var log = new TransactionLog<int, string>(Options(tmp))) { var token = log.BeginTransaction(); log.AddValue(ref token, 1, Guid.NewGuid().ToString()); log.CommitTransaction(ref token); var test = new Dictionary<int, string>(); long offset = 0; log.ReplayLog(test, ref offset); Assert.AreEqual(1, test.Count); } byte[] bytes = tmp.ReadAllBytes(); var TestVariants = new Converter<KeyValuePair<int, byte[]>, byte[]>[] { kv => { kv.Value[kv.Key] ^= 0xff; return kv.Value; }, kv => { kv.Value[kv.Key] = 0xff; return kv.Value; }, kv => { byte[] b = kv.Value; Array.Resize(ref b, kv.Key); return b; }, }; for (int corruptionIx = 0; corruptionIx < bytes.Length; corruptionIx++) { foreach (var testcase in TestVariants) { byte[] corrupt = testcase(new KeyValuePair<int, byte[]>(corruptionIx, (byte[]) bytes.Clone())); tmp.WriteAllBytes(corrupt); using (var log = new TransactionLog<int, string>(Options(tmp))) { var test = new Dictionary<int, string>(); log.ReplayLog(test); Assert.AreEqual(0, test.Count); } Assert.IsFalse(File.Exists(tmp.TempPath)); } } } }
public void TestLargeWriteAndReplay() { using (TempFile tmp = new TempFile()) using (var log = new TransactionLog<int, string>(Options(tmp))) { string testdata = new String('*', 512); var token = log.BeginTransaction(); for (int i = 0; i < 20; i++) log.AddValue(ref token, i, testdata); log.CommitTransaction(ref token); var test = new Dictionary<int, string>(); log.ReplayLog(test); Assert.AreEqual(20, test.Count); for (int i = 0; i < 20; i++) Assert.AreEqual(testdata, test[i]); } }