public void Dispose() { mCmd?.Dispose(); mTxn?.Dispose(); mCmd = null; mTxn = null; }
private void removeBtn_Click(object sender, EventArgs e) { ClearDisplay(); Env env = new Env(EnvCreateFlags.None); try { Env.OpenFlags envFlags = Env.OpenFlags.Create | Env.OpenFlags.InitLock | Env.OpenFlags.InitLog | Env.OpenFlags.InitMPool | Env.OpenFlags.InitTxn | Env.OpenFlags.Recover; env.Open(homeDir, envFlags, 0); // remove existing database file Txn txn = env.TxnBegin(null, Txn.BeginFlags.None); env.DbRemove(txn, myDb, null, Env.WriteFlags.None); txn.Commit(Txn.CommitMode.None); env.Close(); // remove existing environment env = new Env(EnvCreateFlags.None); env.Remove(homeDir, Env.RemoveFlags.None); } catch (Exception ex) { errBox.Text = ex.ToString(); tabControl.SelectTab("errorPage"); } finally { env.Close(); } }
public async Task TestTxnErrFinished() { var dg = GetDgraphClient(); try { var op = new Operation { Schema = "email: string @index(exact) .\n" }; await dg.Alter(op); var txn = new Txn(dg); var mu = new Mutation { SetNquads = ByteString.CopyFromUtf8("_:user1 <email> \"[email protected]\"."), CommitNow = true }; await txn.Mutate(mu); await ThrowsAsync <TransactionException>(() => txn.Mutate(mu)); } finally { await ClearDB(); } }
public static async Task CancelOrderDemo(SwitcheoRestService switcheoService, AccountSignerTransactionManager accountSigner) { var cancelRequest = await switcheoService.PrepareCancelOrder("69c60da5-5832-4705-8390-de4bb4ed62c5"); // turn into json var signableParams = JsonConvert.SerializeObject(cancelRequest); // serialize request params var serializedParams = SwitcheoHelper.PrepareParametersRequest(signableParams); // signs the serialized params var signature = accountSigner.SignMessage(serializedParams); // adds the 'address' and 'signature' fields to the json var apiParams = SwitcheoHelper.AddTransactFields(signableParams, signature, accountSigner.AddressScriptHash.ToString().Remove(0, 2)); // sends the 'create cancellation' request CreateResponse response = await switcheoService.CreateCancellation(apiParams); Debug.WriteLine(JsonConvert.SerializeObject(response)); // check response to make sure is what you want // execute cancellation var tx = Transaction.FromJson(Txn.ToJson(response.Transaction)); var depositId = response.Id.ToString(); var signatureTx = accountSigner.SignTransaction(tx, false).ToHexString(); // if everything is good it should return OK var execute = await switcheoService.ExecuteCancellation(signatureTx, depositId); Debug.WriteLine(JsonConvert.SerializeObject(execute)); }
public void Delete <T>(IEnumerable <T> items) where T : class { dbName = typeof(T).FullName; initDatabase(); Txn trans = env.TxnBegin(null, Txn.BeginFlags.ReadCommitted); foreach (T t in items) { MemoryStream memKey = new MemoryStream(); MemoryStream memVal = new MemoryStream(); formatter.Serialize(memKey, t.GetHashCode()); formatter.Serialize(memVal, t); DbEntry key = DbEntry.InOut(memKey.ToArray()); DeleteStatus status = dbInstance.Delete(trans, ref key); if (status == DeleteStatus.NotFound) { Debug.Print("key {0} not found", t.GetHashCode()); } } trans.Commit(Txn.CommitMode.None); env.Close(); }
public async Task HeloTest() { await ConversationTest( Txn.From("^220 "), Txn.To("HELO test.com"), Txn.From("^250 ") ); }
public async Task EhloTest() { await ConversationTest( Txn.From("^220 "), Txn.To("EHLO test.com"), Txn.From(@"\A(250-.*\n)*250 .*\Z") ); }
/// <summary> /// Abandon all the operations of the transaction instead of saving them. /// </summary> public void Abort() { if (!_released) { _released = true; Txn.Abort(_txnPtr); } }
private void viewBtn_Click(object sender, EventArgs e) { ClearDisplay(); // open database and read records back - the database is transactional Env env = new Env(EnvCreateFlags.None); try { DbBTree btree; Env.OpenFlags envFlags = Env.OpenFlags.Create | Env.OpenFlags.InitLock | Env.OpenFlags.InitLog | Env.OpenFlags.InitMPool | Env.OpenFlags.InitTxn | Env.OpenFlags.Recover; env.Open(homeDir, envFlags, 0); Db db = env.CreateDatabase(DbCreateFlags.None); Txn txn = env.TxnBegin(null, Txn.BeginFlags.None); DbFile tmpDb = db.Open(txn, Path.Combine(homeDir, myDb), null, DbType.Unknown, Db.OpenFlags.None, 0); txn.Commit(Txn.CommitMode.None); if (tmpDb.DbType == DbType.BTree) { btree = (DbBTree)tmpDb; } else { throw new ApplicationException("Unexpected database type."); } List <Customer> custList = new List <Customer>(); // DbBTreeCursor implements IDisposable - will be closed through "using" using (DbBTreeCursor cursor = btree.OpenCursor(null, DbFileCursor.CreateFlags.None)) { Customer cust = null; while (GetNextRecord(cursor, ref cust)) { custList.Add(cust); } } db.Close(); DataGridViewColumn nameCol = new DataGridViewTextBoxColumn(); nameCol.Name = "NameCol"; nameCol.HeaderText = "Name"; nameCol.DataPropertyName = "Name"; dataGridView.Columns.Add(nameCol); dataGridView.DataSource = custList; tabControl.SelectTab("dataPage"); } catch (Exception ex) { errBox.Text = ex.ToString(); tabControl.SelectTab("errorPage"); } finally { env.Close(); } }
/// <summary> /// Create a transaction for use with the environment. /// /// The transaction handle may be discarded using Abort() or Commit(); /// NOTE: A transaction and its cursors must only be used by a single /// thread, and a thread may only have a single transaction at a time. /// If MDBX_NOTLS is in use, this does not apply to read-only transactions. /// NOTE: Cursors may not span transactions. /// </summary> /// <param name="flags"></param> /// <returns></returns> public MdbxTransaction BeginTransaction(TransactionOption flags = TransactionOption.Unspecific) { if (!closed && _envPtr != IntPtr.Zero) { IntPtr ptr = Txn.Begin(_envPtr, IntPtr.Zero, flags); return(new MdbxTransaction(this, ptr)); } throw new InvalidOperationException("MDBX environment is not open."); }
/// <summary> /// Commit all the operations of a transaction into the database. /// /// The transaction handle is freed. It and its cursors must not be used /// again after this call, except with mdbx_cursor_renew(). /// </summary> public void Commit() { if (!_released) { _released = true; Txn.Commit(_txnPtr); } else { throw new InvalidOperationException("MDBX transaction handle was freed. It can't be used again unless Reset() is called"); } }
private void btnDelete_Click(object sender, EventArgs e) { if (this.dgvGrid.Rows.Count == 0) { return; } if (MessageBox.Show("선택된 데이터를 삭제하시겠습니까?", "Delete", MessageBoxButtons.YesNo) == DialogResult.No) { return; } #region Transaction Decl SqlCommand Cmd = new SqlCommand(); SqlTransaction Txn; #endregion #region Connection Open Conn = new SqlConnection(ConnInfo); Conn.Open(); #endregion #region Transaction Init Txn = Conn.BeginTransaction("Begin Transaction"); Cmd.Transaction = Txn; Cmd.Connection = Conn; #endregion try { string delCustCode = dgvGrid.CurrentRow.Cells["CUSTCODE"].Value.ToString(); #region Transaction Commit Cmd.CommandText = $"DELETE TB_CUST_NHJ WHERE CUSTCODE = '{delCustCode}'"; Cmd.ExecuteNonQuery(); Txn.Commit(); #endregion MessageBox.Show("성공적으로 데이터를 삭제하였습니다."); btnSearch_Click(null, null); } catch (Exception ex) { // 오류가 났을 때는 ROLLBACK Txn.Rollback(); MessageBox.Show(ex.ToString()); } finally { Conn.Close(); } }
/// <summary> /// 初始化 /// </summary> private void Init() { env = new Env(EnvCreateFlags.None); Env.OpenFlags envFlags = Env.OpenFlags.Create | Env.OpenFlags.InitLock | Env.OpenFlags.InitLog | Env.OpenFlags.InitMPool | Env.OpenFlags.InitTxn | Env.OpenFlags.Recover; env.Open(directory, envFlags, 0); txn = env.TxnBegin(null, Txn.BeginFlags.None); db = env.CreateDatabase(DbCreateFlags.None); btree = (DbHash)db.Open(txn, dbName, null, DbType.Hash, Db.OpenFlags.Create, 0); }
internal async Task <Match> ConverseAsync(Txn txn) { switch (txn.Direction) { case TxnDirection.ToServer: await ToAsync(txn.Message); return(null); case TxnDirection.FromServer: return(await FromAsync(txn.Message)); } Assert.Contains(txn.Direction, new[] { TxnDirection.FromServer, TxnDirection.ToServer }); throw new Exception(); // unreachable }
private void AddRecord(DbBTree btree, Txn txn, Customer value, TextWriter writer) { // use standard .NET serialization, with the binary formatter keyStream.Position = 0; formatter.Serialize(keyStream, value.Name); DbEntry key = DbEntry.InOut(keyStream.GetBuffer(), 0, (int)keyStream.Position); dataStream.Position = 0; formatter.Serialize(dataStream, value); DbEntry data = DbEntry.InOut(dataStream.GetBuffer(), 0, (int)dataStream.Position); // calling PutNew means we don't want to overwrite an existing record WriteStatus status = btree.PutNew(txn, ref key, ref data); // if we tried to insert a duplicate, let's report it if (status == WriteStatus.KeyExist) { writer.WriteLine("Duplicate record: " + value.Name); } }
public async Task <IActionResult> Create([Bind("id,ReferenceNo,Type,LinkedDepositID,TradeDate,ClientTradingProfileID,Status,ClientPriceRate,ClientCurrencyPairID,ClientDfrRate,ClientUniqueDfr,ClientExRate,ClientCurrencyIDIn,ClientAmountIn,ClientCurrencyIDOut,ClientAmountOut,ClientPayOutAccountID,ProviderTradingProfileID,ProviderCurrencyID,ProviderCostDate,ProviderCostRate,ProviderExpectedPayInAmount,ProviderBankAccountID,Remark,PayoutDone,PayoutDoneByID,MiniAccount,OvernightDeposit,DateTimeModified,ModifiedByID,DateTimeAdded,AddedByID")] Txn txn) { if (ModelState.IsValid) { txn.DateTimeModified = Utility.GetLocalDateTime(); txn.DateTimeAdded = Utility.GetLocalDateTime(); txn.ModifiedByID = HttpContext.Session.GetInt32("UserID"); txn.AddedByID = HttpContext.Session.GetInt32("UserID"); if (txn.PayoutDone) { txn.PayoutDoneByID = HttpContext.Session.GetInt32("UserID"); } _context.Add(txn); if (txn.Type == "L") { var deposit = await _context.Txn.FindAsync(txn.LinkedDepositID); deposit.Status = "C"; deposit.DateTimeModified = Utility.GetLocalDateTime(); _context.Update(deposit); } await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewBag.ClientTradingProfile = new SelectList(_context.ClientTradingProfile.OrderBy(x => x.ClientTradingProfileName).ToList(), "id", "ClientTradingProfileName"); ViewBag.CurrencyPair = new SelectList(_context.CurrencyPair.OrderBy(x => x.CurrencyPairName).ToList(), "id", "CurrencyPairName"); ViewBag.Currency = new SelectList(_context.Currency.OrderBy(x => x.CurrencyName).ToList(), "id", "CurrencyName"); ViewBag.ProviderBankAccount = new SelectList(_context.ProviderBankAccount.OrderBy(x => x.AccountName).ToList(), "id", "AccountName"); //ViewBag.ProviderTradingProfile = new SelectList(_context.ProviderTradingProfile.OrderBy(x => x.ProviderTradingProfileName).ToList(), "id", "ProviderTradingProfileName"); ViewBag.Deposit = new SelectList(_context.Txn.ToList().Where(t => t.Type == "D" && t.Status != "C").OrderBy(x => x.ReferenceNo), "id", "ReferenceNo"); ViewBag.ProviderTradingProfile = new SelectList(_context.ProviderTradingProfileView.OrderBy(x => x.ProviderTradingProfileName) .Select(x => new { id = x.id, text = x.ProviderTradingProfileName + ", " + x.CurrencyPairName }).ToList(), "id", "text"); return(View(txn)); }
void initDatabase() { Db db = null; Txn txn = null; try { env = new Env(EnvCreateFlags.None); // configure for error and message reporting env.ErrorStream = Console.OpenStandardError( ); env.MessageStream = Console.OpenStandardOutput( ); // initialize environment for locking, logging, memory pool and transactions Env.OpenFlags envFlags = Env.OpenFlags.Create | Env.OpenFlags.InitLock | Env.OpenFlags.InitLog | Env.OpenFlags.InitMPool | Env.OpenFlags.InitTxn | Env.OpenFlags.Recover; env.Open(dbHome, envFlags, 0); // create, configure and open database under a transaction txn = env.TxnBegin(null, Txn.BeginFlags.None); db = env.CreateDatabase(DbCreateFlags.None); // set the BTree comparison function db.BTreeCompare = AppCompare; // error and message reporting already configured on environment // db.ErrorStream = errStream; // db.ErrorPrefix = Path.GetFileName(Application.ExecutablePath); // db.MessageStream = msgStream; dbInstance = (DbBTree)db.Open( txn, dbName, null, DbType.BTree, Db.OpenFlags.Create, 0); txn.Commit(Txn.CommitMode.None); } catch { } isInited = true; }
// GET: Txn/CreateLQuote public IActionResult CreateLQuote() { ViewBag.ClientTradingProfile = new SelectList(_context.ClientTradingProfile.OrderBy(x => x.ClientTradingProfileName).ToList(), "id", "ClientTradingProfileName"); ViewBag.CurrencyPair = new SelectList(_context.CurrencyPair.OrderBy(x => x.CurrencyPairName).ToList(), "id", "CurrencyPairName"); ViewBag.Currency = new SelectList(_context.Currency.OrderBy(x => x.CurrencyName).ToList(), "id", "CurrencyName"); ViewBag.ProviderBankAccount = new SelectList(_context.ProviderBankAccount.OrderBy(x => x.AccountName).ToList(), "id", "AccountName"); //ViewBag.ProviderTradingProfile = new SelectList(_context.ProviderTradingProfile.OrderBy(x => x.ProviderTradingProfileName).ToList(), "id", "ProviderTradingProfileName"); ViewBag.Deposit = new SelectList(_context.Txn.ToList().Where(t => t.Type == "D" && t.Status != "C").OrderBy(x => x.ReferenceNo), "id", "ReferenceNo"); ViewBag.ProviderTradingProfile = new SelectList(_context.ProviderTradingProfileView.OrderBy(x => x.ProviderTradingProfileName) .Select(x => new { id = x.id, text = x.ProviderTradingProfileName + ", " + x.CurrencyPairName }).ToList(), "id", "text"); Txn txn = new Txn(); txn.ReferenceNo = "L" + Utility.GetLocalDateTime().ToString("yyyyMMddHHmmss"); txn.Type = "L"; txn.TradeDate = Utility.GetLocalDateTime().Date; return(View("Create", txn)); }
public void Save <T>(IEnumerable <T> items) where T : class { dbName = typeof(T).FullName; initDatabase(); Txn trans = env.TxnBegin(null, Txn.BeginFlags.ReadCommitted); foreach (T t in items) { MemoryStream memKey = new MemoryStream( ); MemoryStream memVal = new MemoryStream(); formatter.Serialize(memKey, t.GetHashCode()); formatter.Serialize(memVal, t); memKey.Flush(); memVal.Flush(); DbEntry key = DbEntry.InOut(memKey.ToArray()); DbEntry value = DbEntry.InOut(memVal.ToArray()); WriteStatus status = dbInstance.PutUnique(trans, ref key, ref value); if (status == WriteStatus.KeyExist) { Debug.Print("key {0} duplicated", t.GetHashCode()); } if (status == WriteStatus.KeyExist) { Delete <T>(t); WriteStatus st = dbInstance.PutUnique(trans, ref key, ref value); } } trans.Commit(Txn.CommitMode.Sync); env.Close(); }
public async Task <IActionResult> Edit(int id, [Bind("id,ReferenceNo,Type,LinkedDepositID,TradeDate,ClientTradingProfileID,Status,ClientPriceRate,ClientCurrencyPairID,ClientDfrRate,ClientUniqueDfr,ClientExRate,ClientCurrencyIDIn,ClientAmountIn,ClientCurrencyIDOut,ClientAmountOut,ClientPayOutAccountID,ProviderTradingProfileID,ProviderCurrencyID,ProviderCostDate,ProviderCostRate,ProviderExpectedPayInAmount,ProviderBankAccountID,Remark,PayoutDone,PayoutDoneByID,MiniAccount,OvernightDeposit,DateTimeModified,ModifiedByID,DateTimeAdded,AddedByID")] Txn txn) { if (id != txn.id) { return(NotFound()); } if (ModelState.IsValid) { try { Txn txnOld; if (txn.Type == "L") { txnOld = await _context.Txn.AsNoTracking().SingleOrDefaultAsync(m => m.id == txn.id); if (txnOld.LinkedDepositID != txn.LinkedDepositID) { var depositOld = await _context.Txn.FindAsync(txnOld.LinkedDepositID); depositOld.Status = ""; depositOld.DateTimeModified = Utility.GetLocalDateTime(); _context.Update(depositOld); var depositNew = await _context.Txn.FindAsync(txn.LinkedDepositID); depositNew.Status = "C"; depositNew.DateTimeModified = Utility.GetLocalDateTime(); _context.Update(depositNew); } } txn.DateTimeModified = Utility.GetLocalDateTime(); txn.ModifiedByID = HttpContext.Session.GetInt32("UserID"); if (!txn.PayoutDone) { txn.PayoutDoneByID = null; } else if (txn.PayoutDoneByID == null) { txn.PayoutDoneByID = HttpContext.Session.GetInt32("UserID"); } _context.Update(txn); await _context.SaveChangesAsync(); //check ClientPayoutMissing, update Status var reportTxn = await _context.ReportTxnOriginal.AsNoTracking().SingleOrDefaultAsync(m => m.TxnID == txn.id); if (reportTxn == null || reportTxn.ClientPayoutMissing >= reportTxn.ClientAmountOut) { txn.Status = ""; } else if (reportTxn.ClientPayoutMissing > 0) { txn.Status = "P"; } else { txn.Status = "C"; } _context.Update(txn); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TxnExists(txn.id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewBag.ClientTradingProfile = new SelectList(_context.ClientTradingProfile.OrderBy(x => x.ClientTradingProfileName).ToList(), "id", "ClientTradingProfileName"); ViewBag.CurrencyPair = new SelectList(_context.CurrencyPair.OrderBy(x => x.CurrencyPairName).ToList(), "id", "CurrencyPairName"); ViewBag.Currency = new SelectList(_context.Currency.OrderBy(x => x.CurrencyName).ToList(), "id", "CurrencyName"); ViewBag.ProviderBankAccount = new SelectList(_context.ProviderBankAccount.OrderBy(x => x.AccountName).ToList(), "id", "AccountName"); //ViewBag.ProviderTradingProfile = new SelectList(_context.ProviderTradingProfile.OrderBy(x => x.ProviderTradingProfileName).ToList(), "id", "ProviderTradingProfileName"); ViewBag.Deposit = new SelectList(_context.Txn.ToList().Where(t => (t.Type == "D" && t.Status != "C") || t.id == txn.LinkedDepositID).OrderBy(x => x.ReferenceNo), "id", "ReferenceNo"); ViewBag.ProviderTradingProfile = new SelectList(_context.ProviderTradingProfileView.OrderBy(x => x.ProviderTradingProfileName) .Select(x => new { id = x.id, text = x.ProviderTradingProfileName + ", " + x.CurrencyPairName }).ToList(), "id", "text"); return(View(txn)); }
/// <summary> /// Renew a read-only transaction. /// /// This acquires a new reader lock for a transaction handle that had been /// released by mdbx_txn_reset(). It must be called before a reset transaction /// may be used again. /// </summary> public void Renew() { Txn.Renew(_txnPtr); }
/// <summary> /// Reset a read-only transaction. /// /// Abort the transaction like Abort(), but keep the transaction /// handle. Therefore Renew() may reuse the handle. This saves /// allocation overhead if the process will start a new read-only transaction /// soon, and also locking overhead if MDBX_NOTLS is in use. The reader table /// lock is released, but the table slot stays tied to its thread or /// MDBX_txn. Use mdbx_txn_abort() to discard a reset handle, and to free /// its lock table slot if MDBX_NOTLS is in use. /// </summary> public void Reset() { Txn.Reset(_txnPtr); }
/// <summary> /// This returns the identifier associated with this transaction. For a /// read-only transaction, this corresponds to the snapshot being read; /// concurrent readers will frequently have the same transaction ID. /// </summary> /// <returns></returns> public ulong GetID() { return(Txn.GetID(_txnPtr)); }
internal Appender(SQLiteCommand cmd, Txn txn) { mCmd = cmd; mTxn = txn; }
internal Remover(SQLiteCommand cmd, Txn txn) { mCmd = cmd; mTxn = txn; }
public async Task WelcomeMessageTest() { await ConversationTest( Txn.From("^220 ") ); }
private void loadBtn_Click(object sender, EventArgs e) { ClearDisplay(); MemoryStream errStream = new MemoryStream(); MemoryStream msgStream = new MemoryStream(); TextWriter errWriter = new StreamWriter(errStream); TextWriter msgWriter = new StreamWriter(msgStream); Db db = null; Txn txn = null; Env env = null; try { env = new Env(EnvCreateFlags.None); // configure for error and message reporting env.ErrorStream = errStream; env.ErrorPrefix = Path.GetFileName(Application.ExecutablePath); env.MessageStream = msgStream; // initialize environment for locking, logging, memory pool and transactions Env.OpenFlags envFlags = Env.OpenFlags.Create | Env.OpenFlags.InitLock | Env.OpenFlags.InitLog | Env.OpenFlags.InitMPool | Env.OpenFlags.InitTxn | Env.OpenFlags.Recover; env.Open(homeDir, envFlags, 0); // create, configure and open database under a transaction txn = env.TxnBegin(null, Txn.BeginFlags.None); db = env.CreateDatabase(DbCreateFlags.None); // set the BTree comparison function db.BTreeCompare = AppCompare; // error and message reporting already configured on environment // db.ErrorStream = errStream; // db.ErrorPrefix = Path.GetFileName(Application.ExecutablePath); // db.MessageStream = msgStream; DbBTree btree = (DbBTree)db.Open( txn, myDb, null, DbType.BTree, Db.OpenFlags.Create, 0); txn.Commit(Txn.CommitMode.None); // create a sequence named '###sequence1' under a transaction txn = env.TxnBegin(null, Txn.BeginFlags.None); Sequence seq = btree.CreateSequence(); byte[] seqName = utf8.GetBytes("###sequence1"); DbEntry seqNameEntry = DbEntry.InOut(seqName); seq.Open(txn, ref seqNameEntry, Sequence.OpenFlags.Create); seq.Close(); txn.Commit(Txn.CommitMode.None); // open sequence again, retrieve values and then remove the sequence seq = btree.CreateSequence(); txn = env.TxnBegin(null, Txn.BeginFlags.None); // seq.CacheSize = 1000; // cannot use transactions when CacheSize > 0 seq.Open(txn, ref seqNameEntry, Sequence.OpenFlags.None); Int64 seqVal; for (int indx = 0; indx < 500; indx++) { seqVal = seq.Get(txn, 1, Sequence.ReadFlags.None); } seq.Remove(txn, Sequence.RemoveFlags.None); txn.Commit(Txn.CommitMode.None); // add a few records under a transaction Customer cust; txn = env.TxnBegin(null, Txn.BeginFlags.None); cust = new Customer("John Doe", "122 Yonge Street", "Toronto", "ON", "M5R 5T9", DateTime.Parse("Dec 22, 1965")); AddRecord(btree, txn, cust, errWriter); cust = new Customer("Jane Doby", "23 Bloor Street", "Oshawa", "ON", "L1H 2K9", DateTime.Parse("Jun 1, 1962")); AddRecord(btree, txn, cust, errWriter); cust = new Customer("Rusty Nail", "77 Bond Street", "Markham", "ON", "L3T 7Y8", DateTime.Parse("Sep 9, 1915")); AddRecord(btree, txn, cust, errWriter); cust = new Customer("Rosy Cheek", "11 Adelaide Street", "Whitby", "ON", "K3P 4H4", DateTime.Parse("Jan 2, 1980")); AddRecord(btree, txn, cust, errWriter); // this last one is a duplicate of the first record cust = new Customer("John Doe", "1459 King Street", "Toronto", "ON", "N8N 2L0", DateTime.Parse("Apr 14, 1973")); AddRecord(btree, txn, cust, errWriter); txn.Commit(Txn.CommitMode.None); msgWriter.WriteLine("=================================================="); msgWriter.WriteLine("K E Y S T A T I S T I C S"); msgWriter.WriteLine("=================================================="); // get a key range, under a transaction txn = env.TxnBegin(null, Txn.BeginFlags.None); keyStream.Position = 0; formatter.Serialize(keyStream, "John Doe"); DbEntry key = DbEntry.InOut(keyStream.GetBuffer(), 0, (int)keyStream.Position); DbBTree.KeyRange keyRange = btree.GetKeyRange(txn, ref key); txn.Commit(Txn.CommitMode.None); msgWriter.WriteLine(); string msg = "KeyRange for 'John Doe': Less = {0}, Equal = {1}, Greater = {2}"; msgWriter.WriteLine(string.Format(msg, keyRange.Less, keyRange.Equal, keyRange.Greater)); msgWriter.WriteLine(); // retrieve some database statistics TxnStats stats = env.GetTxnStats(StatFlags.None); DbBTree.Stats btstats = btree.GetStats(null, DbFile.StatFlags.None); CacheFileStats[] cfStats = env.GetCacheFileStats(StatFlags.None); // we can also have them written to the message stream msgWriter.WriteLine("=================================================="); msgWriter.WriteLine("T R A N S A C T I O N S T A T I S T I C S"); msgWriter.WriteLine("=================================================="); msgWriter.WriteLine(); msgWriter.Flush(); env.PrintTxnStats(StatPrintFlags.None); msgWriter.WriteLine(); msgWriter.WriteLine("=================================================="); msgWriter.WriteLine("L O G S T A T I S T I C S"); msgWriter.WriteLine("=================================================="); msgWriter.WriteLine(); msgWriter.Flush(); env.PrintLogStats(StatPrintFlags.All); msgWriter.WriteLine(); msgWriter.WriteLine("=================================================="); msgWriter.WriteLine("L O C K S T A T I S T I C S"); msgWriter.WriteLine("=================================================="); msgWriter.WriteLine(); msgWriter.Flush(); env.PrintLogStats(StatPrintFlags.All); msgWriter.WriteLine(); msgWriter.WriteLine("=================================================="); msgWriter.WriteLine("C A C H E S T A T I S T I C S"); msgWriter.WriteLine("=================================================="); msgWriter.WriteLine(); msgWriter.Flush(); env.PrintCacheStats(CacheStatPrintFlags.All); msgWriter.WriteLine(); msgWriter.WriteLine("=================================================="); msgWriter.WriteLine("B T R E E S T A T I S T I C S"); msgWriter.WriteLine("=================================================="); msgWriter.WriteLine(); msgWriter.Flush(); btree.PrintStats(DbFile.StatPrintFlags.All); } catch (BdbException) { if (txn != null && !txn.IsDisposed) { txn.Abort(); } // errors are reported through error stream already return; } catch (Exception ex) { if (txn != null && !txn.IsDisposed) { txn.Abort(); } errWriter.WriteLine(ex.ToString()); return; } finally { if (db != null) { db.Close(); } if (env != null) { env.Close(); } msgWriter.Flush(); string msgText = utf8.GetString(msgStream.GetBuffer()); if (msgText != "") { msgBox.Text = msgText; } msgWriter.Close(); errWriter.Flush(); string errText = utf8.GetString(errStream.GetBuffer()); if (errText != "") { errBox.Text = errText; tabControl.SelectTab("errorPage"); } errWriter.Close(); } }
public void On_Connection_Message(object MsgObj) { try { List <ReturnMessage> ReturnMsgList; string Msg = MsgObj.ToString(); logger.Debug(_Config.DeviceName + "Recieve:" + Msg.Replace("\r", "")); //lock (_Decoder) //{ ReturnMsgList = _Decoder.GetMessage(Msg); //} if (ReturnMsgList == null) { logger.Debug(_Config.DeviceName + " Decode parse error:" + Msg.Replace("\r", "")); return; } if (ReturnMsgList.Count == 0) { logger.Debug(_Config.DeviceName + " Decode parse error:" + Msg.Replace("\r", "")); } foreach (ReturnMessage ReturnMsg in ReturnMsgList) { logger.Debug(_Config.DeviceName + "Each ReturnMsg:" + JsonConvert.SerializeObject(ReturnMsg)); try { Transaction Txn; Node Node; if (ReturnMsg != null) { Node = NodeManagement.GetByController(_Config.DeviceName, ReturnMsg.NodeAdr); if (Node == null) { logger.Debug("Node not found!" + _Config.DeviceName + " - " + ReturnMsg.NodeAdr); return; } //lock (TransactionList) //{ lock (Node) { if (ReturnMsg.Type == ReturnMessage.ReturnType.Event) { _ReportTarget.On_Event_Trigger(Node, ReturnMsg); } else if (TransactionList.TryRemove(ReturnMsg.NodeAdr + ReturnMsg.IsInterrupt.ToString(), out Txn)) { logger.Debug("Txn removed."); switch (ReturnMsg.Type) { case ReturnMessage.ReturnType.Excuted: if (!Txn.CommandType.Equals("CMD") && !Txn.CommandType.Equals("MOV")) { logger.Debug("Txn timmer stoped."); Txn.SetTimeOutMonitor(false); } else { Txn.SetTimeOutMonitor(false); Txn.SetTimeOut(15000); Txn.SetTimeOutMonitor(true); TransactionList.TryAdd(ReturnMsg.NodeAdr + ReturnMsg.IsInterrupt.ToString(), Txn); } _ReportTarget.On_Command_Excuted(Node, Txn, ReturnMsg); break; case ReturnMessage.ReturnType.Finished: logger.Debug("Txn timmer stoped."); Txn.SetTimeOutMonitor(false); _ReportTarget.On_Command_Finished(Node, Txn, ReturnMsg); break; case ReturnMessage.ReturnType.Error: Txn.SetTimeOutMonitor(false); _ReportTarget.On_Command_Error(Node, Txn, ReturnMsg); break; case ReturnMessage.ReturnType.Information: logger.Debug("Txn timmer stoped."); Txn.SetTimeOutMonitor(false); _ReportTarget.On_Command_Finished(Node, Txn, ReturnMsg); //SpinWait.SpinUntil(() => false, 300); ThreadPool.QueueUserWorkItem(new WaitCallback(conn.Send), ReturnMsg.FinCommand); logger.Debug(_Config.DeviceName + "Send:" + ReturnMsg.FinCommand); break; } } else { logger.Debug(_Config.DeviceName + "(On_Connection_Message Txn is not found. msg:" + Msg); switch (ReturnMsg.Type) { case ReturnMessage.ReturnType.Information: case ReturnMessage.ReturnType.ReInformation: ThreadPool.QueueUserWorkItem(new WaitCallback(conn.Send), ReturnMsg.FinCommand); logger.Debug(_Config.DeviceName + "Send:" + ReturnMsg.FinCommand); break; } } } //} } else { logger.Debug(_Config.DeviceName + "(On_Connection_Message Message decode fail:" + Msg); } } catch (Exception e) { logger.Error(_Config.DeviceName + "(On_Connection_Message " + _Config.IPAdress + ":" + _Config.Port.ToString() + ")" + e.Message + "\n" + e.StackTrace); } } } catch (Exception e) { logger.Error(_Config.DeviceName + "(On_Connection_Message " + _Config.IPAdress + ":" + _Config.Port.ToString() + ")" + e.Message + "\n" + e.StackTrace); } }
private void btnSave_Click(object sender, EventArgs e) { if (dgvGrid.Rows.Count == 0) { return; } if (MessageBox.Show("선택된 데이터를 저장하시겠습니까??", "Save", MessageBoxButtons.YesNo) == DialogResult.No) { return; } #region Variable Init string custCode = dgvGrid.CurrentRow.Cells["CUSTCODE"].Value.ToString(); string custType = dgvGrid.CurrentRow.Cells["CUSTTYPE"].Value.ToString(); string custName = dgvGrid.CurrentRow.Cells["CUSTNAME"].Value.ToString(); string bizClass = dgvGrid.CurrentRow.Cells["BIZCLASS"].Value.ToString(); string bizType = dgvGrid.CurrentRow.Cells["BIZTYPE"].Value.ToString(); string useFlag = dgvGrid.CurrentRow.Cells["USEFLAG"].Value.ToString(); string firstDate = dgvGrid.CurrentRow.Cells["FIRSTDATE"].Value.ToString(); if (custCode == "" || custType == "" || firstDate == "") { MessageBox.Show("'거래처 코드', '거래처 타입', '거래일자' 는 빈칸으로 남겨둘 수 없습니다."); return; } if (custType == "고객사" || custType == "C") { custType = "C"; } else { custType = "V"; } if (useFlag == "미사용" || useFlag == "N") { useFlag = "N"; } else { useFlag = "Y"; } #endregion #region Transaction Decl SqlCommand Cmd = new SqlCommand(); SqlTransaction Txn; #endregion #region Connection Open Conn = new SqlConnection(ConnInfo); Conn.Open(); #endregion #region Transaction Init Txn = Conn.BeginTransaction("Test Transaction"); Cmd.Transaction = Txn; Cmd.Connection = Conn; #endregion #region Transaction Commit Cmd.CommandText = "UPDATE TB_CUST_KBM " + $" SET CUSTNAME = '{custName}', " + $" CUSTTYPE = '{custType}', " + $" BIZCLASS = '{bizClass}', " + $" BIZTYPE = '{bizType}', " + $" USEFLAG = '{useFlag}', " + $" FIRSTDATE = '{firstDate}', " + $" EDITOR = '{Common.LogInId}'," + $" EDITDATE = GETDATE() " + $" WHERE CUSTCODE = '{custCode}' " + " IF (@@ROWCOUNT =0) " + " INSERT INTO TB_CUST_KBM (CUSTCODE, CUSTTYPE, CUSTNAME, BIZCLASS, BIZTYPE, USEFLAG, FIRSTDATE, MAKEDATE, MAKER) " + $"VALUES ( '{custCode}', '{custType}', '{custName}', '{bizClass}', '{bizType}', '{useFlag}', '{firstDate}', GETDATE(), '{Common.LogInId}')"; Cmd.ExecuteNonQuery(); Txn.Commit(); #endregion MessageBox.Show("성공적으로 저장하였습니다."); Conn.Close(); }
public IList <T> Lookup <T>(ICondition condition) where T : class { dbName = typeof(T).FullName; initDatabase(); List <T> result = new List <T>( ); Txn trans = env.TxnBegin(null, Txn.BeginFlags.None); switch (condition.Name) { case "SELECT_ALL": using (DbBTreeCursor cursor = dbInstance.OpenCursor(null, DbFileCursor.CreateFlags.None)) { T cust = null; IEnumerable <KeyDataPair> lst = cursor.ItemsForward(false, DbFileCursor.ReadFlags.None); foreach (KeyDataPair pair in lst) { using (MemoryStream mem = new MemoryStream(pair.Data.Buffer)) { T t = (T)formatter.Deserialize(mem); result.Add(t); } } } break; case "SELECT_BY_CODE": SelectByCodeCondition cond = condition as SelectByCodeCondition; if (cond == null) { throw new InvalidDataException(String.Format("Invalid {0} condition", condition.Name)); } foreach (int i in cond.HashCodes) { T t = null; byte[] buf = new byte[1024]; MemoryStream key = new MemoryStream( ); MemoryStream value = new MemoryStream(); formatter.Serialize(key, i); DbEntry dbKey = DbEntry.InOut(key.ToArray()); DbEntry dbVal = DbEntry.Out(buf); while (true) { ReadStatus status = dbInstance.GetExact(trans, ref dbKey, ref dbVal, DbFile.ReadFlags.None); switch (status) { case ReadStatus.BufferSmall: if (dbVal.Buffer.Length < dbVal.Size) { value.SetLength(dbVal.Size); dbVal = DbEntry.Out(value.GetBuffer()); } continue; case ReadStatus.KeyEmpty: goto brk; case ReadStatus.NotFound: goto brk; case ReadStatus.Success: value.Position = 0; value.SetLength(dbVal.Size); value.Write(dbVal.Buffer, 0, dbVal.Size); value.Flush(); value.Seek(0, SeekOrigin.Begin); t = (T)formatter.Deserialize(value); result.Add(t); key.Dispose(); value.Dispose(); break; } } brk :; } break; default: throw new NotImplementedException(String.Format("Condition {0} is not implemented", condition.Name)); } trans.Commit(Txn.CommitMode.Sync); env.Close(); return(result); }