Ejemplo n.º 1
0
        public static bool HasEdits(IApplication app, TransactionManager tm)
        {
            try
            {
                IWorkspaceEdit workspace = (IWorkspaceEdit)tm.Current().PGDBConnection;

                bool processQA = false;
                bool hasEdits = false;
                workspace.HasEdits(ref hasEdits);

                UID pUID = new UIDClass();
                pUID.Value = "esriEditor.Editor";
                IEditor editor = (IEditor)app.FindExtensionByCLSID(pUID);
                IEditTask task = editor.CurrentTask;
                IEditTask resetTask = editor.get_Task(0);
                editor.CurrentTask = resetTask;
                editor.CurrentTask = task;

                IEditor2 editor2 = (IEditor2)app.FindExtensionByCLSID(pUID);
                bool hasCachedEdits = editor2.HasEdits();

                return hasCachedEdits || hasEdits;
            }
            catch (Exception e)
            {
                Logger.Write("Error testing if transaction has edits: " + e.Message + " : " + e.StackTrace, Logger.LogLevel.Debug);
                throw new Exception("Error", e);
            }
        }
Ejemplo n.º 2
0
        public RunTestsForm(ref dao.QATestCollection tests, IMap map, TransactionManager tm, QAManager qa)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            if (tests == null)
                throw new ArgumentNullException("tests", "Must pass collection of QA tests to RunTestsForm");
            if (tests.Count == 0)
                throw new ArgumentException("No QA tests passed to RunTestsForm", "tests");
            if (map == null)
                throw new ArgumentNullException("map", "Must pass the focus map to RunTestsForm");

            this._tests = tests;
            this._tm = tm;
            this._qa = qa;
            this._map = map;
            this._defaults = new util.SystemDefaults();

            // Throw TM stuff at the QA tests and see if it sticks
            if (tm.Current() != null)
            {
                object[] theArgs = new object[2] {
                                                 new ISDUTLib.tm.dao.EditsDAO((IFeatureWorkspace)tm.Current().PGDBConnection, tm.transactionConfig()),
                                                 tm.transactionConfig()
                                             };
                for (int i = 0; i < this._tests.Count; i++)
                {
                    this._tests.get_Test(i).Test.UserData = theArgs;
                }
            }
        }
Ejemplo n.º 3
0
        public static bool SaveEdits(IApplication app, TransactionManager tm)
        {
            bool result = false;
            try
            {
                if (HasEdits(app, tm))
                {
                    UID pUID = new UIDClass();
                    pUID.Value = "esriEditor.Editor";
                    IWorkspaceEdit workspace = (IWorkspaceEdit)tm.Current().PGDBConnection;
                    IEditor2 editor2 = (IEditor2)app.FindExtensionByCLSID(pUID);

                    editor2.StopEditing(true);
                    editor2.StartEditing((IWorkspace)workspace);
                    workspace.StopEditing(true);
                    workspace.StartEditing(false);
                }

                result = true;
            }
            catch (Exception e)
            {
                Logger.Write("Error saving edits to PGDB", Logger.LogLevel.Debug);
                MessageBox.Show("An error occured while attempting to save current edits.");
                result = false;
            }
            return result;
        }
        public void AfmReturnsRightNumberOfJObjects()
        {
            _testName = MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString();
            Cleanup();

            var formatter = new BSONFormatter();
            var core = new FileCore<int, long>() { IdSeed = new Seed32(999), SegmentSeed = new Seed64(), MinimumCoreStride = 512 };

            var addEntities = TestResourceFactory.GetMockClassAObjects(10000).ToList();

            foreach (var entity in addEntities)
                entity.Id = _seed.Increment();

            IDictionary<int, long> returnSegments = null;

            using (var afm = new AtomicFileManager<MockClassA>(_testName + ".database", core))
            {
                afm.Load<int>();

                using (var manager = new TransactionManager<int, MockClassA>
                    (new MockTransactionFactory<int, MockClassA>()
                    , new TransactionSynchronizer<int, MockClassA>()))
                {
                    manager.TransactionCommitted += new TransactionCommit<int, MockClassA>(
                        delegate(ITransaction<int, MockClassA> tranny)
                        {
                            returnSegments = afm.CommitTransaction(tranny, new Dictionary<int, long>());

                            tranny.MarkComplete();
                        });

                    using (var tLock1 = manager.BeginTransaction())
                    {
                        addEntities.ForEach(delegate(MockClassA entity)
                        {
                            tLock1.Transaction.Enlist(Action.Create, entity.Id, entity);
                        });

                        tLock1.Transaction.Commit();

                        Assert.AreEqual(10000, afm.Length);
                    }

                    foreach (var group in afm.AsEnumerable())
                    {
                        var match = group.Where(i => i.SelectToken("Id").Value<int>() > 9999).ToList();

                        if (match == null || !match.Any())
                            continue;

                        var result = match.First(r => r.Value<int>("Id") == 10000).ToObject<MockClassC>();

                        Assert.IsNotNull(result);
                        Assert.AreEqual(10000, result.Id);
                        break;
                    }
                }
            }
        }
 private void Instead01(TransactionManager tm, Customer cus)
 {
     MessageBox.Show("Something...");
     // Begin the transaction after the message box,
     // e.g. if you want to prompt them to do something before saving.
     tm.BeginTransaction();
     DataRepository.CustomerProvider.Insert(tm, cus);
     tm.Commit();
 }
 private void Instead02(TransactionManager tm, Customer cus)
 {
     tm.BeginTransaction();
     DataRepository.CustomerProvider.Insert(tm, cus);
     tm.Commit();
     // Or, show the message box after the transaction completed,
     // e.g. to notify them of an event after saving
     MessageBox.Show("Something...");
 }
    public IList<Transaction> Get(int pageNumber, int pageSize, string filter)
    {
        var transactionManager = new TransactionManager();
 
        return transactionManager.GetTransactions(new ListOptions
        {
            PageSize = pageSize,
            PageNumber = pageNumber
        });
    }
Ejemplo n.º 8
0
 public IDatabaseSession CreateSession(string connectionString)
 {
     var sqlConnectionProvider = new SqlConnectionProvider(connectionString);
     var transactionManager = new TransactionManager(sqlConnectionProvider);
     var databaseConnectionManager = new DatabaseCommandProvider(sqlConnectionProvider, transactionManager);
     var databaseCommandCreator = new DatabaseCommandFactory(databaseConnectionManager);
     var databaseReaderFactory = new SqlDatabaseReaderFactory();
     var connectionHandler = new ConnectionHandler();
     return new DatabaseSession(databaseCommandCreator, transactionManager, databaseReaderFactory, connectionHandler);
 }
        // SAMPLE 01
        //
        // As mentioned in "C01_TransactionManager," the idea behind transactions
        // is that it should surround a block of code that either saves everything
        // or nothing.
        //
        // Here is the thing to remember: While the transaction is open it will prevent
        // anything from accessing the database tables that you are busy with. This is
        // to prevent "dirty" or incomplete records.
        //
        // The caveat: you want your transaction to execute as fast as possible. Be
        // like a ninja: get in, do your thing, and get out.
        //
        private void BadlyMisplacedCode(TransactionManager tm, Customer cus)
        {
            tm.BeginTransaction();
            DataRepository.CustomerProvider.Insert(tm, cus);
            MessageBox.Show("Something...");
            tm.Commit();

            // Can you see it?
            // This code will block the Customer table on the entire branch until the user
            // clicks "OK" on the message box. The impact of this is enourmous.
        }
        public IList<Transaction> GetTransactionsByCategory(string from, string to, string balanceType, string category)
        {
            var dateFrom = DateTime.ParseExact(from, "yyyyMMdd", CultureInfo.InvariantCulture);
            var dateTo = DateTime.ParseExact(to, "yyyyMMdd", CultureInfo.InvariantCulture);
            var type = (BalanceType) Enum.Parse(typeof (BalanceType), balanceType, true);

            var transactionManager = new TransactionManager();
            var list = transactionManager.GetTransactions(dateFrom, dateTo, type, category);

            return list;
        }
Ejemplo n.º 11
0
      /// <summary>
      /// Apply a record to placeholders
      /// </summary>
		/// <param name="placeHolders">List of placeholder which should be applied</param>
		/// <param name="recordName">Name of record</param>
		/// <returns>Return true if one or more was applied</returns>
      public static void ApplyRecord(IEnumerable<PlaceHolder> placeHolders, string recordName)
      {
         using (Transaction transaction = new TransactionManager().CreateTransaction())
         {
            foreach (PlaceHolder placeHolder in placeHolders)
            {
               placeHolder.ApplyRecord(recordName, true); // apply (with page data)
               transaction.Commit(); // needed if not placed in project
            }
         }
      }
        public void ReadTransactionsFromFile_Valid_ObserverNeverCalled()
        {
            var mockObserver = new Moq.Mock<Observer>();
            List<Observer> ol = new List<Observer>();
            ol.Add(mockObserver.Object);
            List<Product> listOfProducts = new List<Product>();
            TransactionManager tm = new TransactionManager(ol, listOfProducts);

            tm.ReadTransactionsFromFile(new StreamReader(@"C:\Users\vbhujan\Documents\Cart.txt"));

            mockObserver.Verify(o => o.update(), Times.Never);
        }
Ejemplo n.º 13
0
        public LsbLinuxHostInstaller(LinuxServiceSettings settings, Installer[] installers, LinuxServiceLogWriter logWriter)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            _settings = settings;
            _installers = installers;
            _logWriter = logWriter;

            _installTransaction = new TransactionManager<LinuxServiceSettings>(_logWriter)
                .Stage(Properties.Resources.CreateServiceFileStage, CreateServiceFile, DeleteServiceFile)
                .Stage(Properties.Resources.SetServiceFileAsExecutableStage, SetServiceFileAsExecutable)
                .Stage(Properties.Resources.RegisterServiceFileStage, RegisterServiceFile, UnregisterServiceFile);
        }
Ejemplo n.º 14
0
      /// <summary>
      /// Create a record to a placeHolder by name and apply a record
      /// </summary>
		/// <param name="placeHolders">List of placeholder which should be applied</param>
		/// <param name="placeHolderName">Name of placeholder</param>
		/// <param name="recordName">Name of record</param>
      /// <param name="variableName">Variable to set</param>
      /// <param name="value">New value of the variable</param>
		/// <returns>Return true if one or more was applied</returns>
      public bool CreateRecordWithValueAndApply(PlaceHolder[] placeHolders, string placeHolderName, string recordName, string variableName, string value)
		{
			List<PlaceHolder> foundPlaceHolder = placeHolders
				.Where(placeHolder => placeHolder.Name.Equals(placeHolderName)) // name
				.ToList();

			foreach (PlaceHolder placeHolder in foundPlaceHolder)
			{
				placeHolder.AddRecord(recordName);
				placeHolder.set_Value(recordName, variableName, value);
				using (Transaction transaction = new TransactionManager().CreateTransaction())
				{
					placeHolder.ApplyRecord(recordName, true); // apply (with page data)
					transaction.Commit(); // needed if not placed in project
				}
			}

			return foundPlaceHolder.Any(); // true == found | false == not found
		}
Ejemplo n.º 15
0
        public override bool Delete(long id, TransactionManager trans)
        {
            var sqlStatement = "Delete From BoxContract Where Id = @Id";
            var parms = new[] { new OleDbParameter("@Id", OleDbType.BigInt) { Value = id } };
            try
            {
                if (trans == null)
                    AccessHelper.ExecuteNonQuery(this.ConnectionString, sqlStatement, parms);
                else
                    AccessHelper.ExecuteNonQuery(trans.TransactionObject as OleDbTransaction, sqlStatement, parms);

                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
                return false ;
            }
        }
Ejemplo n.º 16
0
        public override bool Delete(string itemName, TransactionManager trans)
        {
            var sqlStatement = "Delete From Item Where ItemName = @ItemName";
            var parms = new[] {
                new OleDbParameter("@ItemName",OleDbType.VarWChar,50){Value = itemName},
            };
            try
            {
                if (trans == null)
                    AccessHelper.ExecuteNonQuery(this.ConnectionString, sqlStatement, parms);
                else
                    AccessHelper.ExecuteNonQuery(trans.TransactionObject as OleDbTransaction, sqlStatement, parms);

                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
                return false;
            }
        }
Ejemplo n.º 17
0
        public void AmbientTransactionCommitsIteself()
        {
            var seed = new Seed32();
            var hits = 0;

            using (var manager = new TransactionManager<int, MockClassA>() )
            {
                manager.TransactionCommitted += new TransactionCommit<int, MockClassA>
                    (delegate(ITransaction<int, MockClassA> transaction)
                    {
                        Assert.AreEqual(3, transaction.GetEnlistedActions().Count());
                        hits++;

                        transaction.MarkComplete();

                        hits = 1;
                    });

                var testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList();
                testEntities.ForEach(e => e.Id = seed.Increment());

                using (var tLock1 = manager.GetActiveTransaction(false))
                {
                    foreach (var entity in testEntities)
                        tLock1.Transaction.Enlist(Action.Create, entity.Id, entity);

                    var sw = new Stopwatch();
                    sw.Start();

                    while (sw.ElapsedMilliseconds < 5500)
                        Thread.Sleep(10);
                }

                Thread.Sleep(500);

                Assert.AreEqual(1, hits);
            }
        }
Ejemplo n.º 18
0
 public Engine(HoePrOptions options)
 {
     _HoePrOptions           = options;
     FbRaumInfo.HoePrOptions = options;
     _TransMan = _AcAp.Application.DocumentManager.MdiActiveDocument.Database.TransactionManager;
 }
        /// <summary>
        ///     Gets rows from the datasource based on the PK_UnitMeasure_UnitMeasureCode index.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_unitMeasureCode">Primary key.</param>
        /// <param name="start">Row number at which to start reading, the first row is 0.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <remarks></remarks>
        /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.UnitMeasure"/> class.</returns>
        public Nettiers.AdventureWorks.Entities.UnitMeasure GetByUnitMeasureCode(TransactionManager transactionManager, System.String _unitMeasureCode, int start, int pageLength)
        {
            int count = -1;

            return(GetByUnitMeasureCode(transactionManager, _unitMeasureCode, start, pageLength, out count));
        }
        /// <summary>
        ///     Gets rows from the datasource based on the PK_BankAccounts index.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_bankAccountId"></param>
        /// <param name="start">Row number at which to start reading, the first row is 0.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <remarks></remarks>
        /// <returns>Returns an instance of the <see cref="EmployeeDB.BLL.BankAccounts"/> class.</returns>
        public EmployeeDB.BLL.BankAccounts GetByBankAccountId(TransactionManager transactionManager, System.Int32 _bankAccountId, int start, int pageLength)
        {
            int count = -1;

            return(GetByBankAccountId(transactionManager, _bankAccountId, start, pageLength, out count));
        }
 /// <summary>
 ///     Gets a row from the DataSource based on its primary key.
 /// </summary>
 /// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
 /// <param name="key">The unique identifier of the row to retrieve.</param>
 /// <param name="start">Row number at which to start reading, the first row is 0.</param>
 /// <param name="pageLength">Number of rows to return.</param>
 /// <returns>Returns an instance of the Entity class.</returns>
 public override EmployeeDB.BLL.BankAccounts Get(TransactionManager transactionManager, EmployeeDB.BLL.BankAccountsKey key, int start, int pageLength)
 {
     return(GetByBankAccountId(transactionManager, key.BankAccountId, start, pageLength));
 }
        /// <summary>
        ///     Gets rows from the datasource based on the FK_BankAccounts_Employee key.
        ///		FK_BankAccounts_Employee Description:
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_employeeId"></param>
        /// <returns>Returns a typed collection of EmployeeDB.BLL.BankAccounts objects.</returns>
        /// <remarks></remarks>
        public TList <BankAccounts> GetByEmployeeId(TransactionManager transactionManager, System.Int32 _employeeId)
        {
            int count = -1;

            return(GetByEmployeeId(transactionManager, _employeeId, 0, int.MaxValue, out count));
        }
 /// <summary>
 ///     Deletes a row from the DataSource.
 /// </summary>
 /// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
 /// <param name="key">The unique identifier of the row to delete.</param>
 /// <returns>Returns true if operation suceeded.</returns>
 public override bool Delete(TransactionManager transactionManager, EmployeeDB.BLL.BankAccountsKey key)
 {
     return(Delete(transactionManager, key.BankAccountId));
 }
		/// <summary>
		/// Lets you efficiently bulk insert many entities to the database.
		/// </summary>
		/// <param name="transactionManager">The transaction manager.</param>
		/// <param name="entities">The entities.</param>
		/// <remarks>
		///		After inserting into the datasource, the Nettiers.AdventureWorks.Entities.StoreContact object will be updated
		/// 	to refelect any changes made by the datasource. (ie: identity or computed columns)
		/// </remarks>	
		public override void BulkInsert(TransactionManager transactionManager, TList<Nettiers.AdventureWorks.Entities.StoreContact> entities)
		{
			//System.Data.SqlClient.SqlBulkCopy bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints); //, null);
			
			System.Data.SqlClient.SqlBulkCopy bulkCopy = null;
	
			if (transactionManager != null && transactionManager.IsOpen)
			{			
				System.Data.SqlClient.SqlConnection cnx = transactionManager.TransactionObject.Connection as System.Data.SqlClient.SqlConnection;
				System.Data.SqlClient.SqlTransaction transaction = transactionManager.TransactionObject as System.Data.SqlClient.SqlTransaction;
				bulkCopy = new System.Data.SqlClient.SqlBulkCopy(cnx, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints, transaction); //, null);
			}
			else
			{
				bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints); //, null);
			}
			
			bulkCopy.BulkCopyTimeout = 360;
			bulkCopy.DestinationTableName = "StoreContact";
			
			DataTable dataTable = new DataTable();
			DataColumn col0 = dataTable.Columns.Add("CustomerID", typeof(System.Int32));
			col0.AllowDBNull = false;		
			DataColumn col1 = dataTable.Columns.Add("ContactID", typeof(System.Int32));
			col1.AllowDBNull = false;		
			DataColumn col2 = dataTable.Columns.Add("ContactTypeID", typeof(System.Int32));
			col2.AllowDBNull = false;		
			DataColumn col3 = dataTable.Columns.Add("rowguid", typeof(System.Guid));
			col3.AllowDBNull = false;		
			DataColumn col4 = dataTable.Columns.Add("ModifiedDate", typeof(System.DateTime));
			col4.AllowDBNull = false;		
			
			bulkCopy.ColumnMappings.Add("CustomerID", "CustomerID");
			bulkCopy.ColumnMappings.Add("ContactID", "ContactID");
			bulkCopy.ColumnMappings.Add("ContactTypeID", "ContactTypeID");
			bulkCopy.ColumnMappings.Add("rowguid", "rowguid");
			bulkCopy.ColumnMappings.Add("ModifiedDate", "ModifiedDate");
			
			foreach(Nettiers.AdventureWorks.Entities.StoreContact entity in entities)
			{
				if (entity.EntityState != EntityState.Added)
					continue;
					
				DataRow row = dataTable.NewRow();
				
					row["CustomerID"] = entity.CustomerId;
							
				
					row["ContactID"] = entity.ContactId;
							
				
					row["ContactTypeID"] = entity.ContactTypeId;
							
				
					row["rowguid"] = entity.Rowguid;
							
				
					row["ModifiedDate"] = entity.ModifiedDate;
							
				
				dataTable.Rows.Add(row);
			}		
			
			// send the data to the server		
			bulkCopy.WriteToServer(dataTable);		
			
			// update back the state
			foreach(Nettiers.AdventureWorks.Entities.StoreContact entity in entities)
			{
				if (entity.EntityState != EntityState.Added)
					continue;
			
				entity.AcceptChanges();
			}
		}
Ejemplo n.º 25
0
 internal ChannelConfigurator(ChannelMultiplexer multiplexer, Type channelType, TransactionManager transactionManager)
 {
     _multiplexer       = multiplexer;
     _channelType       = channelType;
     TransactionManager = transactionManager;
 }
        /// <summary>
        /// Deep Save the entire object graph of the Nettiers.AdventureWorks.Entities.UnitMeasure object with criteria based of the child
        /// Type property array and DeepSaveType.
        /// </summary>
        /// <param name="transactionManager">The transaction manager.</param>
        /// <param name="entity">Nettiers.AdventureWorks.Entities.UnitMeasure instance</param>
        /// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param>
        /// <param name="childTypes">Nettiers.AdventureWorks.Entities.UnitMeasure Property Collection Type Array To Include or Exclude from Save</param>
        /// <param name="innerList">A Hashtable of child types for easy access.</param>
        public override bool DeepSave(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.UnitMeasure entity, DeepSaveType deepSaveType, System.Type[] childTypes, DeepSession innerList)
        {
            if (entity == null)
            {
                return(false);
            }

            #region Composite Parent Properties
            //Save Source Composite Properties, however, don't call deep save on them.
            //So they only get saved a single level deep.
            #endregion Composite Parent Properties

            // Save Root Entity through Provider
            if (!entity.IsDeleted)
            {
                this.Save(transactionManager, entity);
            }

            //used to hold DeepSave method delegates and fire after all the local children have been saved.
            Dictionary <string, KeyValuePair <Delegate, object> > deepHandles = new Dictionary <string, KeyValuePair <Delegate, object> >();

            #region List<BillOfMaterials>
            if (CanDeepSave(entity.BillOfMaterialsCollection, "List<BillOfMaterials>|BillOfMaterialsCollection", deepSaveType, innerList))
            {
                // update each child parent id with the real parent id (mostly used on insert)
                foreach (BillOfMaterials child in entity.BillOfMaterialsCollection)
                {
                    if (child.UnitMeasureCodeSource != null)
                    {
                        child.UnitMeasureCode = child.UnitMeasureCodeSource.UnitMeasureCode;
                    }
                    else
                    {
                        child.UnitMeasureCode = entity.UnitMeasureCode;
                    }
                }

                if (entity.BillOfMaterialsCollection.Count > 0 || entity.BillOfMaterialsCollection.DeletedItems.Count > 0)
                {
                    //DataRepository.BillOfMaterialsProvider.Save(transactionManager, entity.BillOfMaterialsCollection);

                    deepHandles.Add("BillOfMaterialsCollection",
                                    new KeyValuePair <Delegate, object>((DeepSaveHandle <BillOfMaterials>)DataRepository.BillOfMaterialsProvider.DeepSave,
                                                                        new object[] { transactionManager, entity.BillOfMaterialsCollection, deepSaveType, childTypes, innerList }
                                                                        ));
                }
            }
            #endregion


            #region List<Product>
            if (CanDeepSave(entity.ProductCollectionGetByWeightUnitMeasureCode, "List<Product>|ProductCollectionGetByWeightUnitMeasureCode", deepSaveType, innerList))
            {
                // update each child parent id with the real parent id (mostly used on insert)
                foreach (Product child in entity.ProductCollectionGetByWeightUnitMeasureCode)
                {
                    if (child.WeightUnitMeasureCodeSource != null)
                    {
                        child.WeightUnitMeasureCode = child.WeightUnitMeasureCodeSource.UnitMeasureCode;
                    }
                    else
                    {
                        child.WeightUnitMeasureCode = entity.UnitMeasureCode;
                    }
                }

                if (entity.ProductCollectionGetByWeightUnitMeasureCode.Count > 0 || entity.ProductCollectionGetByWeightUnitMeasureCode.DeletedItems.Count > 0)
                {
                    //DataRepository.ProductProvider.Save(transactionManager, entity.ProductCollectionGetByWeightUnitMeasureCode);

                    deepHandles.Add("ProductCollectionGetByWeightUnitMeasureCode",
                                    new KeyValuePair <Delegate, object>((DeepSaveHandle <Product>)DataRepository.ProductProvider.DeepSave,
                                                                        new object[] { transactionManager, entity.ProductCollectionGetByWeightUnitMeasureCode, deepSaveType, childTypes, innerList }
                                                                        ));
                }
            }
            #endregion


            #region List<ProductVendor>
            if (CanDeepSave(entity.ProductVendorCollection, "List<ProductVendor>|ProductVendorCollection", deepSaveType, innerList))
            {
                // update each child parent id with the real parent id (mostly used on insert)
                foreach (ProductVendor child in entity.ProductVendorCollection)
                {
                }

                if (entity.ProductVendorCollection.Count > 0 || entity.ProductVendorCollection.DeletedItems.Count > 0)
                {
                    //DataRepository.ProductVendorProvider.Save(transactionManager, entity.ProductVendorCollection);

                    deepHandles.Add("ProductVendorCollection",
                                    new KeyValuePair <Delegate, object>((DeepSaveHandle <ProductVendor>)DataRepository.ProductVendorProvider.DeepSave,
                                                                        new object[] { transactionManager, entity.ProductVendorCollection, deepSaveType, childTypes, innerList }
                                                                        ));
                }
            }
            #endregion


            #region List<Product>
            if (CanDeepSave(entity.ProductCollectionGetBySizeUnitMeasureCode, "List<Product>|ProductCollectionGetBySizeUnitMeasureCode", deepSaveType, innerList))
            {
                // update each child parent id with the real parent id (mostly used on insert)
                foreach (Product child in entity.ProductCollectionGetBySizeUnitMeasureCode)
                {
                    if (child.SizeUnitMeasureCodeSource != null)
                    {
                        child.SizeUnitMeasureCode = child.SizeUnitMeasureCodeSource.UnitMeasureCode;
                    }
                    else
                    {
                        child.SizeUnitMeasureCode = entity.UnitMeasureCode;
                    }
                }

                if (entity.ProductCollectionGetBySizeUnitMeasureCode.Count > 0 || entity.ProductCollectionGetBySizeUnitMeasureCode.DeletedItems.Count > 0)
                {
                    //DataRepository.ProductProvider.Save(transactionManager, entity.ProductCollectionGetBySizeUnitMeasureCode);

                    deepHandles.Add("ProductCollectionGetBySizeUnitMeasureCode",
                                    new KeyValuePair <Delegate, object>((DeepSaveHandle <Product>)DataRepository.ProductProvider.DeepSave,
                                                                        new object[] { transactionManager, entity.ProductCollectionGetBySizeUnitMeasureCode, deepSaveType, childTypes, innerList }
                                                                        ));
                }
            }
            #endregion

            //Fire all DeepSave Items
            foreach (KeyValuePair <Delegate, object> pair in deepHandles.Values)
            {
                pair.Key.DynamicInvoke((object[])pair.Value);
            }

            // Save Root Entity through Provider, if not already saved in delete mode
            if (entity.IsDeleted)
            {
                this.Save(transactionManager, entity);
            }


            deepHandles = null;

            return(true);
        }
        /// <summary>
        /// Lets you efficiently bulk insert many entities to the database.
        /// </summary>
        /// <param name="transactionManager">The transaction manager.</param>
        /// <param name="entities">The entities.</param>
        /// <remarks>
        ///		After inserting into the datasource, the LibraryManagement.Domain.Kit object will be updated
        ///     to refelect any changes made by the datasource. (ie: identity or computed columns)
        /// </remarks>
        public override void BulkInsert(TransactionManager transactionManager, TList <LibraryManagement.Domain.Kit> entities)
        {
            //System.Data.SqlClient.SqlBulkCopy bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints); //, null);

            System.Data.SqlClient.SqlBulkCopy bulkCopy = null;

            if (transactionManager != null && transactionManager.IsOpen)
            {
                System.Data.SqlClient.SqlConnection  cnx         = transactionManager.TransactionObject.Connection as System.Data.SqlClient.SqlConnection;
                System.Data.SqlClient.SqlTransaction transaction = transactionManager.TransactionObject as System.Data.SqlClient.SqlTransaction;
                bulkCopy = new System.Data.SqlClient.SqlBulkCopy(cnx, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints, transaction);                 //, null);
            }
            else
            {
                bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints);                 //, null);
            }

            bulkCopy.BulkCopyTimeout      = 360;
            bulkCopy.DestinationTableName = "tblKit";

            DataTable  dataTable = new DataTable();
            DataColumn col0      = dataTable.Columns.Add("id", typeof(System.String));

            col0.AllowDBNull = false;
            DataColumn col1 = dataTable.Columns.Add("description", typeof(System.String));

            col1.AllowDBNull = true;
            DataColumn col2 = dataTable.Columns.Add("unitsymb", typeof(System.String));

            col2.AllowDBNull = true;
            DataColumn col3 = dataTable.Columns.Add("rtprice", typeof(System.Decimal));

            col3.AllowDBNull = true;
            DataColumn col4 = dataTable.Columns.Add("open_date", typeof(System.DateTime));

            col4.AllowDBNull = true;
            DataColumn col5 = dataTable.Columns.Add("status", typeof(System.Boolean));

            col5.AllowDBNull = true;

            bulkCopy.ColumnMappings.Add("id", "id");
            bulkCopy.ColumnMappings.Add("description", "description");
            bulkCopy.ColumnMappings.Add("unitsymb", "unitsymb");
            bulkCopy.ColumnMappings.Add("rtprice", "rtprice");
            bulkCopy.ColumnMappings.Add("open_date", "open_date");
            bulkCopy.ColumnMappings.Add("status", "status");

            foreach (LibraryManagement.Domain.Kit entity in entities)
            {
                if (entity.EntityState != EntityState.Added)
                {
                    continue;
                }

                DataRow row = dataTable.NewRow();

                row["id"] = entity.Id;


                row["description"] = entity.Description;


                row["unitsymb"] = entity.Unitsymb;


                row["rtprice"] = entity.Rtprice.HasValue ? (object)entity.Rtprice  : System.DBNull.Value;


                row["open_date"] = entity.OpenDate.HasValue ? (object)entity.OpenDate  : System.DBNull.Value;


                row["status"] = entity.Status.HasValue ? (object)entity.Status  : System.DBNull.Value;


                dataTable.Rows.Add(row);
            }

            // send the data to the server
            bulkCopy.WriteToServer(dataTable);

            // update back the state
            foreach (LibraryManagement.Domain.Kit entity in entities)
            {
                if (entity.EntityState != EntityState.Added)
                {
                    continue;
                }

                entity.AcceptChanges();
            }
        }
        /// <summary>
        /// Deep Loads the <see cref="IEntity"/> object with criteria based of the child
        /// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
        /// </summary>
        /// <remarks>
        /// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph.
        /// </remarks>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="entity">The <see cref="Nettiers.AdventureWorks.Entities.UnitMeasure"/> object to load.</param>
        /// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
        /// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
        /// <param name="childTypes">Nettiers.AdventureWorks.Entities.UnitMeasure Property Collection Type Array To Include or Exclude from Load</param>
        /// <param name="innerList">A collection of child types for easy access.</param>
        /// <exception cref="ArgumentNullException">entity or childTypes is null.</exception>
        /// <exception cref="ArgumentException">deepLoadType has invalid value.</exception>
        public override void DeepLoad(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.UnitMeasure entity, bool deep, DeepLoadType deepLoadType, System.Type[] childTypes, DeepSession innerList)
        {
            if (entity == null)
            {
                return;
            }

            //used to hold DeepLoad method delegates and fire after all the local children have been loaded.
            Dictionary <string, KeyValuePair <Delegate, object> > deepHandles = new Dictionary <string, KeyValuePair <Delegate, object> >();

            // Deep load child collections  - Call GetByUnitMeasureCode methods when available

            #region BillOfMaterialsCollection
            //Relationship Type One : Many
            if (CanDeepLoad(entity, "List<BillOfMaterials>|BillOfMaterialsCollection", deepLoadType, innerList))
            {
                                #if NETTIERS_DEBUG
                System.Diagnostics.Debug.WriteLine("- property 'BillOfMaterialsCollection' loaded. key " + entity.EntityTrackingKey);
                                #endif

                entity.BillOfMaterialsCollection = DataRepository.BillOfMaterialsProvider.GetByUnitMeasureCode(transactionManager, entity.UnitMeasureCode);

                if (deep && entity.BillOfMaterialsCollection.Count > 0)
                {
                    deepHandles.Add("BillOfMaterialsCollection",
                                    new KeyValuePair <Delegate, object>((DeepLoadHandle <BillOfMaterials>)DataRepository.BillOfMaterialsProvider.DeepLoad,
                                                                        new object[] { transactionManager, entity.BillOfMaterialsCollection, deep, deepLoadType, childTypes, innerList }
                                                                        ));
                }
            }
            #endregion


            #region ProductCollectionGetByWeightUnitMeasureCode
            //Relationship Type One : Many
            if (CanDeepLoad(entity, "List<Product>|ProductCollectionGetByWeightUnitMeasureCode", deepLoadType, innerList))
            {
                                #if NETTIERS_DEBUG
                System.Diagnostics.Debug.WriteLine("- property 'ProductCollectionGetByWeightUnitMeasureCode' loaded. key " + entity.EntityTrackingKey);
                                #endif

                entity.ProductCollectionGetByWeightUnitMeasureCode = DataRepository.ProductProvider.GetByWeightUnitMeasureCode(transactionManager, entity.UnitMeasureCode);

                if (deep && entity.ProductCollectionGetByWeightUnitMeasureCode.Count > 0)
                {
                    deepHandles.Add("ProductCollectionGetByWeightUnitMeasureCode",
                                    new KeyValuePair <Delegate, object>((DeepLoadHandle <Product>)DataRepository.ProductProvider.DeepLoad,
                                                                        new object[] { transactionManager, entity.ProductCollectionGetByWeightUnitMeasureCode, deep, deepLoadType, childTypes, innerList }
                                                                        ));
                }
            }
            #endregion


            #region ProductVendorCollection
            //Relationship Type One : Many
            if (CanDeepLoad(entity, "List<ProductVendor>|ProductVendorCollection", deepLoadType, innerList))
            {
                                #if NETTIERS_DEBUG
                System.Diagnostics.Debug.WriteLine("- property 'ProductVendorCollection' loaded. key " + entity.EntityTrackingKey);
                                #endif

                entity.ProductVendorCollection = DataRepository.ProductVendorProvider.GetByUnitMeasureCode(transactionManager, entity.UnitMeasureCode);

                if (deep && entity.ProductVendorCollection.Count > 0)
                {
                    deepHandles.Add("ProductVendorCollection",
                                    new KeyValuePair <Delegate, object>((DeepLoadHandle <ProductVendor>)DataRepository.ProductVendorProvider.DeepLoad,
                                                                        new object[] { transactionManager, entity.ProductVendorCollection, deep, deepLoadType, childTypes, innerList }
                                                                        ));
                }
            }
            #endregion


            #region ProductCollectionGetBySizeUnitMeasureCode
            //Relationship Type One : Many
            if (CanDeepLoad(entity, "List<Product>|ProductCollectionGetBySizeUnitMeasureCode", deepLoadType, innerList))
            {
                                #if NETTIERS_DEBUG
                System.Diagnostics.Debug.WriteLine("- property 'ProductCollectionGetBySizeUnitMeasureCode' loaded. key " + entity.EntityTrackingKey);
                                #endif

                entity.ProductCollectionGetBySizeUnitMeasureCode = DataRepository.ProductProvider.GetBySizeUnitMeasureCode(transactionManager, entity.UnitMeasureCode);

                if (deep && entity.ProductCollectionGetBySizeUnitMeasureCode.Count > 0)
                {
                    deepHandles.Add("ProductCollectionGetBySizeUnitMeasureCode",
                                    new KeyValuePair <Delegate, object>((DeepLoadHandle <Product>)DataRepository.ProductProvider.DeepLoad,
                                                                        new object[] { transactionManager, entity.ProductCollectionGetBySizeUnitMeasureCode, deep, deepLoadType, childTypes, innerList }
                                                                        ));
                }
            }
            #endregion


            //Fire all DeepLoad Items
            foreach (KeyValuePair <Delegate, object> pair in deepHandles.Values)
            {
                pair.Key.DynamicInvoke((object[])pair.Value);
            }
            deepHandles = null;
        }
 /// <summary>
 ///     Deletes a row from the DataSource.
 /// </summary>
 /// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
 /// <param name="key">The unique identifier of the row to delete.</param>
 /// <returns>Returns true if operation suceeded.</returns>
 public override bool Delete(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.UnitMeasureKey key)
 {
     return(Delete(transactionManager, key.UnitMeasureCode));
 }
 /// <summary>
 ///     Gets rows from the datasource based on the PK_UnitMeasure_UnitMeasureCode index.
 /// </summary>
 /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
 /// <param name="_unitMeasureCode">Primary key.</param>
 /// <param name="start">Row number at which to start reading, the first row is 0.</param>
 /// <param name="pageLength">Number of rows to return.</param>
 /// <param name="count">The total number of records.</param>
 /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.UnitMeasure"/> class.</returns>
 public abstract Nettiers.AdventureWorks.Entities.UnitMeasure GetByUnitMeasureCode(TransactionManager transactionManager, System.String _unitMeasureCode, int start, int pageLength, out int count);
Ejemplo n.º 31
0
        private void Manager_Closed(object sender, EventArgs e)
        {
            _manager.Closed -= Manager_Closed;

            _manager = null;
        }
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="_transactionId">Primary key for TransactionHistory records.. Primary Key.</param>	
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
		public override bool Delete(TransactionManager transactionManager, System.Int32 _transactionId)
		{
			SqlDatabase database = new SqlDatabase(this._connectionString);
			DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Production.usp_adwTiers_TransactionHistory_Delete", _useStoredProcedure);
			database.AddInParameter(commandWrapper, "@TransactionId", DbType.Int32, _transactionId);
			
			//Provider Data Requesting Command Event
			OnDataRequesting(new CommandEventArgs(commandWrapper, "Delete")); 

			int results = 0;
			
			if (transactionManager != null)
			{	
				results = Utility.ExecuteNonQuery(transactionManager, commandWrapper);
			}
			else
			{
				results = Utility.ExecuteNonQuery(database,commandWrapper);
			}
			
			//Stop Tracking Now that it has been updated and persisted.
			if (DataRepository.Provider.EnableEntityTracking)
			{
				string entityKey = EntityLocator.ConstructKeyFromPkItems(typeof(TransactionHistory)
					,_transactionId);
				EntityManager.StopTracking(entityKey);
			}
			
			//Provider Data Requested Command Event
			OnDataRequested(new CommandEventArgs(commandWrapper, "Delete")); 

			commandWrapper = null;
			
			return Convert.ToBoolean(results);
		}//end Delete
Ejemplo n.º 33
0
        private void Beginscherm_Load(object sender, EventArgs e)
        {
            PinInvoer          pinInvoer = new PinInvoer();
            Hoofdmenu          hoofdmenu = new Hoofdmenu();
            ArduinoData        arduino   = new ArduinoData();
            Stock              stock     = new Stock(arduino);
            Hash               security  = new Hash();
            TransactionManager transactionManager;
            Boolean            reset = false;
            Boolean            pinCorrect;

            String[] pasInformation;
            bool     EE = true;

            //User user;
            try
            {
                while (true) ///Infinite loop so that the program returns here after every cancelation.
                {
                    while (true)
                    {
                        pinCorrect         = false;
                        pasInformation     = new String[4];
                        reset              = false;
                        transactionManager = null;
                        int      KlantID;
                        String   rekeningID;
                        String   pasID;
                        HTTPget  httpget  = new HTTPget();
                        HTTPpost httppost = new HTTPpost();
                        while (true)
                        {
                            String s = arduino.getFirstString();
                            if (s.Contains(",NEWUID"))
                            {
                                pasInformation = s.Split('\n', '\n', '\n');
                                Int32.TryParse(pasInformation[2], out KlantID);
                                rekeningID = pasInformation[1];
                                pasID      = pasInformation[0];
                                break;
                            }
                            else if (s.Contains("open"))
                            {
                                Cursor.Show();
                                stock.restock();
                            }
                        }
                        if (httpget.getActiefStand(pasID) == false)
                        {
                            BlockScreen tmp = new BlockScreen();
                            break;
                        }
                        pinInvoer.Show();
                        while (pinCorrect == false)
                        {
                            int     insertedDigits = 0;
                            String  pincode        = "";
                            Boolean confirmed      = false;
                            while (confirmed == false) ///Waits for user input until 4 digits have been submitted.
                            {
                                String input = arduino.getString();
                                if (checkInput(input) == true && insertedDigits < 4)
                                {
                                    pinInvoer.printStar();
                                    pinInvoer.falsepininfo.Visible = false;
                                    insertedDigits++;
                                    pincode += input.ElementAt(0);
                                }
                                else if (input.Contains("#KEY"))
                                {
                                    reset = true;
                                    break;
                                }
                                else if (input.Contains("CKEY"))
                                {
                                    pinInvoer.clear();
                                    insertedDigits = 0;
                                    pincode        = "";
                                }
                                if (insertedDigits == 4)
                                {
                                    if (input.Contains("*"))
                                    {
                                        confirmed = true;
                                    }
                                }
                            }
                            pinInvoer.clear();
                            if (reset == true)
                            {
                                break;
                            }
                            if (pincode == "1337" && EE) //Added easter egg
                            {
                                pinInvoer.pictureBox2.Visible = true;
                                pinInvoer.Refresh();
                                System.Threading.Thread.Sleep(8000);
                                reset = true;
                                pinInvoer.pictureBox2.Visible = false;
                                break;
                            }
                            if (security.checkHash(rekeningID, pincode) == false)
                            {
                                pinInvoer.falsepininfo.Visible = true;
                                HTTPpost tmp = new HTTPpost();
                                tmp.Incrementfalsepin(pasID);
                                HTTPget tmp2 = new HTTPget();
                                if (tmp2.getPinclass(pasID).poging >= 2)
                                {
                                    reset = true;
                                }
                            }
                            else
                            {
                                httppost.resetfalsepin(pasID);
                                pinCorrect = true;
                            }
                        }
                        pinInvoer.Hide();
                        if (reset == true)
                        {
                            break;
                        }
                        hoofdmenu.Show();
                        transactionManager = new TransactionManager(rekeningID, KlantID, arduino, pasID, stock);
                        while (true)
                        {
                            int choice = arduino.getChoice();
                            if (choice != 0)
                            {
                                transactionManager.executeChoice(choice);
                                if (transactionManager.getEndOfSession() == true)
                                {
                                    hoofdmenu.Hide();
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            catch (Exception) //Made the application safe, as soon as an exception is found, Close everything and show the out of order Form, main thread isnt even running anymore
            {
                ErrorScreen error     = new ErrorScreen();
                List <Form> openForms = new List <Form>();
                foreach (Form f in Application.OpenForms)
                {
                    openForms.Add(f);
                }
                foreach (Form f in openForms)
                {
                    if (f.Name != "ErrorScreen")
                    {
                        f.Close();
                    }
                }
                while (true)
                {
                }   //Loop forever :)
            }
        }
		/// <summary>
		/// 	Returns rows from the DataSource that meet the parameter conditions.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
		/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
		/// <param name="start">Row number at which to start reading.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out. The number of rows that match this query.</param>
		/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.TransactionHistory objects.</returns>
		public override TList<TransactionHistory> Find(TransactionManager transactionManager, IFilterParameterCollection parameters, string orderBy, int start, int pageLength, out int count)
		{
			SqlFilterParameterCollection filter = null;
			
			if (parameters == null)
				filter = new SqlFilterParameterCollection();
			else 
				filter = parameters.GetParameters();
				
			SqlDatabase database = new SqlDatabase(this._connectionString);
			DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Production.usp_adwTiers_TransactionHistory_Find_Dynamic", typeof(TransactionHistoryColumn), filter, orderBy, start, pageLength);
		
			SqlFilterParameter param;

			for ( int i = 0; i < filter.Count; i++ )
			{
				param = filter[i];
				database.AddInParameter(commandWrapper, param.Name, param.DbType, param.GetValue());
			}

			TList<TransactionHistory> rows = new TList<TransactionHistory>();
			IDataReader reader = null;
			
			try
			{
				//Provider Data Requesting Command Event
				OnDataRequesting(new CommandEventArgs(commandWrapper, "Find", rows)); 

				if ( transactionManager != null )
				{
					reader = Utility.ExecuteReader(transactionManager, commandWrapper);
				}
				else
				{
					reader = Utility.ExecuteReader(database, commandWrapper);
				}
				
				Fill(reader, rows, 0, int.MaxValue);
				count = rows.Count;
				
				if ( reader.NextResult() )
				{
					if ( reader.Read() )
					{
						count = reader.GetInt32(0);
					}
				}
				
				//Provider Data Requested Command Event
				OnDataRequested(new CommandEventArgs(commandWrapper, "Find", rows)); 
			}
			finally
			{
				if ( reader != null )
					reader.Close();
					
				commandWrapper = null;
			}
			
			return rows;
		}
        /// <summary>
        ///     Gets rows from the datasource based on the FK_BankAccounts_Employee key.
        ///		FK_BankAccounts_Employee Description:
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_employeeId"></param>
        /// <param name="start">Row number at which to start reading, the first row is 0.</param>
        ///  <param name="pageLength">Number of rows to return.</param>
        /// <remarks></remarks>
        /// <returns>Returns a typed collection of EmployeeDB.BLL.BankAccounts objects.</returns>
        public TList <BankAccounts> GetByEmployeeId(TransactionManager transactionManager, System.Int32 _employeeId, int start, int pageLength)
        {
            int count = -1;

            return(GetByEmployeeId(transactionManager, _employeeId, start, pageLength, out count));
        }
		}//end getall
		
		#endregion
				
		#region GetPaged Methods
				
		/// <summary>
		/// Gets a page of rows from the DataSource.
		/// </summary>
		/// <param name="start">Row number at which to start reading.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">Number of rows in the DataSource.</param>
		/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
		/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.TransactionHistory objects.</returns>
		public override TList<TransactionHistory> GetPaged(TransactionManager transactionManager, string whereClause, string orderBy, int start, int pageLength, out int count)
		{
			SqlDatabase database = new SqlDatabase(this._connectionString);
			DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Production.usp_adwTiers_TransactionHistory_GetPaged", _useStoredProcedure);
		
			
            if (commandWrapper.CommandType == CommandType.Text
                && commandWrapper.CommandText != null)
            {
                commandWrapper.CommandText = commandWrapper.CommandText.Replace(SqlUtil.PAGE_INDEX, string.Concat(SqlUtil.PAGE_INDEX, Guid.NewGuid().ToString("N").Substring(0, 8)));
            }
			
			database.AddInParameter(commandWrapper, "@WhereClause", DbType.String, whereClause);
			database.AddInParameter(commandWrapper, "@OrderBy", DbType.String, orderBy);
			database.AddInParameter(commandWrapper, "@PageIndex", DbType.Int32, start);
			database.AddInParameter(commandWrapper, "@PageSize", DbType.Int32, pageLength);
		
			IDataReader reader = null;
			//Create Collection
			TList<TransactionHistory> rows = new TList<TransactionHistory>();
			
			try
			{
				//Provider Data Requesting Command Event
				OnDataRequesting(new CommandEventArgs(commandWrapper, "GetPaged", rows)); 

				if (transactionManager != null)
				{
					reader = Utility.ExecuteReader(transactionManager, commandWrapper);
				}
				else
				{
					reader = Utility.ExecuteReader(database, commandWrapper);
				}
				
				Fill(reader, rows, 0, int.MaxValue);
				count = rows.Count;

				if(reader.NextResult())
				{
					if(reader.Read())
					{
						count = reader.GetInt32(0);
					}
				}
				
				//Provider Data Requested Command Event
				OnDataRequested(new CommandEventArgs(commandWrapper, "GetPaged", rows)); 

			}
			catch(Exception)
			{			
				throw;
			}
			finally
			{
				if (reader != null) 
					reader.Close();
				
				commandWrapper = null;
			}
			
			return rows;
		}
 /// <summary>
 ///     Deletes a row from the DataSource.
 /// </summary>
 /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
 /// <param name="_bankAccountId">. Primary Key.</param>
 /// <remarks>Deletes based on primary key(s).</remarks>
 /// <returns>Returns true if operation suceeded.</returns>
 public abstract bool Delete(TransactionManager transactionManager, System.Int32 _bankAccountId);
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_TransactionHistory_TransactionID index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_transactionId">Primary key for TransactionHistory records.</param>
		/// <param name="start">Row number at which to start reading.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query.</param>
		/// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> class.</returns>
		/// <remarks></remarks>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
		public override Nettiers.AdventureWorks.Entities.TransactionHistory GetByTransactionId(TransactionManager transactionManager, System.Int32 _transactionId, int start, int pageLength, out int count)
		{
			SqlDatabase database = new SqlDatabase(this._connectionString);
			DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Production.usp_adwTiers_TransactionHistory_GetByTransactionId", _useStoredProcedure);
			
				database.AddInParameter(commandWrapper, "@TransactionId", DbType.Int32, _transactionId);
			
			IDataReader reader = null;
			TList<TransactionHistory> tmp = new TList<TransactionHistory>();
			try
			{
				//Provider Data Requesting Command Event
				OnDataRequesting(new CommandEventArgs(commandWrapper, "GetByTransactionId", tmp)); 

				if (transactionManager != null)
				{
					reader = Utility.ExecuteReader(transactionManager, commandWrapper);
				}
				else
				{
					reader = Utility.ExecuteReader(database, commandWrapper);
				}		
		
				//Create collection and fill
				Fill(reader, tmp, start, pageLength);
				count = -1;
				if(reader.NextResult())
				{
					if(reader.Read())
					{
						count = reader.GetInt32(0);
					}
				}
				
				//Provider Data Requested Command Event
				OnDataRequested(new CommandEventArgs(commandWrapper, "GetByTransactionId", tmp));
			}
			finally 
			{
				if (reader != null) 
					reader.Close();
					
				commandWrapper = null;
			}
			
			if (tmp.Count == 1)
			{
				return tmp[0];
			}
			else if (tmp.Count == 0)
			{
				return null;
			}
			else
			{
				throw new DataException("Cannot find the unique instance of the class.");
			}
			
			//return rows;
		}
 /// <summary>
 ///     Gets rows from the datasource based on the PK_BankAccounts index.
 /// </summary>
 /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
 /// <param name="_bankAccountId"></param>
 /// <param name="start">Row number at which to start reading, the first row is 0.</param>
 /// <param name="pageLength">Number of rows to return.</param>
 /// <param name="count">The total number of records.</param>
 /// <returns>Returns an instance of the <see cref="EmployeeDB.BLL.BankAccounts"/> class.</returns>
 public abstract EmployeeDB.BLL.BankAccounts GetByBankAccountId(TransactionManager transactionManager, System.Int32 _bankAccountId, int start, int pageLength, out int count);
		/// <summary>
		/// 	Inserts a Nettiers.AdventureWorks.Entities.TransactionHistory object into the datasource using a transaction.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="entity">Nettiers.AdventureWorks.Entities.TransactionHistory object to insert.</param>
		/// <remarks>
		///		After inserting into the datasource, the Nettiers.AdventureWorks.Entities.TransactionHistory object will be updated
		/// 	to refelect any changes made by the datasource. (ie: identity or computed columns)
		/// </remarks>	
		/// <returns>Returns true if operation is successful.</returns>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
		public override bool Insert(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.TransactionHistory entity)
		{
			SqlDatabase database = new SqlDatabase(this._connectionString);
			DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Production.usp_adwTiers_TransactionHistory_Insert", _useStoredProcedure);
			
			database.AddOutParameter(commandWrapper, "@TransactionId", DbType.Int32, 4);
			database.AddInParameter(commandWrapper, "@ProductId", DbType.Int32, entity.ProductId );
			database.AddInParameter(commandWrapper, "@ReferenceOrderId", DbType.Int32, entity.ReferenceOrderId );
			database.AddInParameter(commandWrapper, "@ReferenceOrderLineId", DbType.Int32, entity.ReferenceOrderLineId );
			database.AddInParameter(commandWrapper, "@TransactionDate", DbType.DateTime, entity.TransactionDate );
			database.AddInParameter(commandWrapper, "@TransactionType", DbType.StringFixedLength, entity.TransactionType );
			database.AddInParameter(commandWrapper, "@Quantity", DbType.Int32, entity.Quantity );
			database.AddInParameter(commandWrapper, "@ActualCost", DbType.Currency, entity.ActualCost );
			database.AddInParameter(commandWrapper, "@ModifiedDate", DbType.DateTime, entity.ModifiedDate );
			
			int results = 0;
			
			//Provider Data Requesting Command Event
			OnDataRequesting(new CommandEventArgs(commandWrapper, "Insert", entity));
				
			if (transactionManager != null)
			{
				results = Utility.ExecuteNonQuery(transactionManager, commandWrapper);
			}
			else
			{
				results = Utility.ExecuteNonQuery(database,commandWrapper);
			}
					
			object _transactionId = database.GetParameterValue(commandWrapper, "@TransactionId");
			entity.TransactionId = (System.Int32)_transactionId;
			
			
			entity.AcceptChanges();
	
			//Provider Data Requested Command Event
			OnDataRequested(new CommandEventArgs(commandWrapper, "Insert", entity));

			return Convert.ToBoolean(results);
		}	
        /// <summary>
        ///     Gets rows from the datasource based on the PK_BankAccounts index.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_bankAccountId"></param>
        /// <remarks></remarks>
        /// <returns>Returns an instance of the <see cref="EmployeeDB.BLL.BankAccounts"/> class.</returns>
        public EmployeeDB.BLL.BankAccounts GetByBankAccountId(TransactionManager transactionManager, System.Int32 _bankAccountId)
        {
            int count = -1;

            return(GetByBankAccountId(transactionManager, _bankAccountId, 0, int.MaxValue, out count));
        }
Ejemplo n.º 42
0
            public FbRaumInfo(ObjectId polygon, List <ObjectId> raumblocks, List <ObjectId> vermPunkte, TransactionManager tm)
            {
                Init();

                _TransMan = tm;
                Polygon   = polygon;

                if (!GetPolyHeight())
                {
                    TheStatus = Status.ErrorGetPolyHeight;
                }

                FindHKBlock(raumblocks);

                FindVermPunkte(vermPunkte);
            }
 /// <summary>
 ///     Gets rows from the datasource based on the FK_BankAccounts_Employee key.
 ///		FK_BankAccounts_Employee Description:
 /// </summary>
 /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
 /// <param name="_employeeId"></param>
 /// <param name="start">Row number at which to start reading, the first row is 0.</param>
 /// <param name="pageLength">Number of rows to return.</param>
 /// <param name="count">The total number of records.</param>
 /// <returns>Returns a typed collection of EmployeeDB.BLL.BankAccounts objects.</returns>
 public abstract TList <BankAccounts> GetByEmployeeId(TransactionManager transactionManager, System.Int32 _employeeId, int start, int pageLength, out int count);
        /// <summary>
        ///     Gets rows from the datasource based on the PK_tblKit index.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_id"></param>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">out parameter to get total records for query.</param>
        /// <returns>Returns an instance of the <see cref="LibraryManagement.Domain.Kit"/> class.</returns>
        /// <remarks></remarks>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
        public override LibraryManagement.Domain.Kit GetById(TransactionManager transactionManager, System.String _id, int start, int pageLength, out int count)
        {
            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.tblKit_GetById", _useStoredProcedure);

            database.AddInParameter(commandWrapper, "@Id", DbType.StringFixedLength, _id);

            IDataReader reader = null;
            TList <Kit> tmp    = new TList <Kit>();

            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "GetById", tmp));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                //Create collection and fill
                Fill(reader, tmp, start, pageLength);
                count = -1;
                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "GetById", tmp));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }

            if (tmp.Count == 1)
            {
                return(tmp[0]);
            }
            else if (tmp.Count == 0)
            {
                return(null);
            }
            else
            {
                throw new DataException("Cannot find the unique instance of the class.");
            }

            //return rows;
        }
 /// <summary>
 ///     Deletes a row from the DataSource.
 /// </summary>
 /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
 /// <param name="_unitMeasureCode">Primary key.. Primary Key.</param>
 /// <remarks>Deletes based on primary key(s).</remarks>
 /// <returns>Returns true if operation suceeded.</returns>
 public abstract bool Delete(TransactionManager transactionManager, System.String _unitMeasureCode);
        /// <summary>
        ///     Gets rows from the datasource based on the PK_UnitMeasure_UnitMeasureCode index.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_unitMeasureCode">Primary key.</param>
        /// <remarks></remarks>
        /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.UnitMeasure"/> class.</returns>
        public Nettiers.AdventureWorks.Entities.UnitMeasure GetByUnitMeasureCode(TransactionManager transactionManager, System.String _unitMeasureCode)
        {
            int count = -1;

            return(GetByUnitMeasureCode(transactionManager, _unitMeasureCode, 0, int.MaxValue, out count));
        }
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_StoreContact_Store_CustomerID key.
		///		FK_StoreContact_Store_CustomerID Description: Foreign key constraint referencing Store.CustomerID.
		/// </summary>
		/// <param name="start">Row number at which to start reading.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_customerId">Store identification number. Foreign key to Customer.CustomerID.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.StoreContact objects.</returns>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
		public override TList<StoreContact> GetByCustomerId(TransactionManager transactionManager, System.Int32 _customerId, int start, int pageLength, out int count)
		{
			SqlDatabase database = new SqlDatabase(this._connectionString);
			DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Sales.usp_adwTiers_StoreContact_GetByCustomerId", _useStoredProcedure);
			
				database.AddInParameter(commandWrapper, "@CustomerId", DbType.Int32, _customerId);
			
			IDataReader reader = null;
			TList<StoreContact> rows = new TList<StoreContact>();
			try
			{
				//Provider Data Requesting Command Event
				OnDataRequesting(new CommandEventArgs(commandWrapper, "GetByCustomerId", rows)); 

				if (transactionManager != null)
				{
					reader = Utility.ExecuteReader(transactionManager, commandWrapper);
				}
				else
				{
					reader = Utility.ExecuteReader(database, commandWrapper);
				}
			
				//Create Collection
				Fill(reader, rows, start, pageLength);
				count = -1;
				if(reader.NextResult())
				{
					if(reader.Read())
					{
						count = reader.GetInt32(0);
					}
				}
				
				//Provider Data Requested Command Event
				OnDataRequested(new CommandEventArgs(commandWrapper, "GetByCustomerId", rows)); 
			}
			finally
			{
				if (reader != null) 
					reader.Close();
					
				commandWrapper = null;
			}
			return rows;
		}	
 /// <summary>
 ///     Gets a row from the DataSource based on its primary key.
 /// </summary>
 /// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
 /// <param name="key">The unique identifier of the row to retrieve.</param>
 /// <param name="start">Row number at which to start reading, the first row is 0.</param>
 /// <param name="pageLength">Number of rows to return.</param>
 /// <returns>Returns an instance of the Entity class.</returns>
 public override Nettiers.AdventureWorks.Entities.UnitMeasure Get(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.UnitMeasureKey key, int start, int pageLength)
 {
     return(GetByUnitMeasureCode(transactionManager, key.UnitMeasureCode, start, pageLength));
 }
		/// <summary>
		/// 	Inserts a Nettiers.AdventureWorks.Entities.StoreContact object into the datasource using a transaction.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="entity">Nettiers.AdventureWorks.Entities.StoreContact object to insert.</param>
		/// <remarks>
		///		After inserting into the datasource, the Nettiers.AdventureWorks.Entities.StoreContact object will be updated
		/// 	to refelect any changes made by the datasource. (ie: identity or computed columns)
		/// </remarks>	
		/// <returns>Returns true if operation is successful.</returns>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
		public override bool Insert(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.StoreContact entity)
		{
			SqlDatabase database = new SqlDatabase(this._connectionString);
			DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Sales.usp_adwTiers_StoreContact_Insert", _useStoredProcedure);
			
			database.AddInParameter(commandWrapper, "@CustomerId", DbType.Int32, entity.CustomerId );
			database.AddInParameter(commandWrapper, "@ContactId", DbType.Int32, entity.ContactId );
			database.AddInParameter(commandWrapper, "@ContactTypeId", DbType.Int32, entity.ContactTypeId );
			database.AddOutParameter(commandWrapper, "@Rowguid", DbType.Guid, 16);
			database.AddInParameter(commandWrapper, "@ModifiedDate", DbType.DateTime, entity.ModifiedDate );
			
			int results = 0;
			
			//Provider Data Requesting Command Event
			OnDataRequesting(new CommandEventArgs(commandWrapper, "Insert", entity));
				
			if (transactionManager != null)
			{
				results = Utility.ExecuteNonQuery(transactionManager, commandWrapper);
			}
			else
			{
				results = Utility.ExecuteNonQuery(database,commandWrapper);
			}
					
			object _rowguid = database.GetParameterValue(commandWrapper, "@Rowguid");
			entity.Rowguid = (System.Guid)_rowguid;
			
			entity.OriginalCustomerId = entity.CustomerId;
			entity.OriginalContactId = entity.ContactId;
			
			entity.AcceptChanges();
	
			//Provider Data Requested Command Event
			OnDataRequested(new CommandEventArgs(commandWrapper, "Insert", entity));

			return Convert.ToBoolean(results);
		}	
        }        //end Delete

        #endregion

        #region Find Functions

        #region Parsed Find Methods
        /// <summary>
        ///     Returns rows meeting the whereClause condition from the DataSource.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">out. The number of rows that match this query.</param>
        /// <remarks>Operators must be capitalized (OR, AND).</remarks>
        /// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.EmployeeAddress objects.</returns>
        public override TList <EmployeeAddress> Find(TransactionManager transactionManager, string whereClause, int start, int pageLength, out int count)
        {
            count = -1;
            if (whereClause.IndexOf(";") > -1)
            {
                return(new TList <EmployeeAddress>());
            }

            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "HumanResources.usp_adwTiers_EmployeeAddress_Find", _useStoredProcedure);

            bool searchUsingOR = false;

            if (whereClause.IndexOf(" OR ") > 0)     // did they want to do "a=b OR c=d OR..."?
            {
                searchUsingOR = true;
            }

            database.AddInParameter(commandWrapper, "@SearchUsingOR", DbType.Boolean, searchUsingOR);

            database.AddInParameter(commandWrapper, "@EmployeeId", DbType.Int32, DBNull.Value);
            database.AddInParameter(commandWrapper, "@AddressId", DbType.Int32, DBNull.Value);
            database.AddInParameter(commandWrapper, "@Rowguid", DbType.Guid, DBNull.Value);
            database.AddInParameter(commandWrapper, "@ModifiedDate", DbType.DateTime, DBNull.Value);

            // replace all instances of 'AND' and 'OR' because we already set searchUsingOR
            whereClause = whereClause.Replace(" AND ", "|").Replace(" OR ", "|");
            string[] clauses = whereClause.ToLower().Split('|');

            // Here's what's going on below: Find a field, then to get the value we
            // drop the field name from the front, trim spaces, drop the '=' sign,
            // trim more spaces, and drop any outer single quotes.
            // Now handles the case when two fields start off the same way - like "Friendly='Yes' AND Friend='john'"

            char[] equalSign   = { '=' };
            char[] singleQuote = { '\'' };
            foreach (string clause in clauses)
            {
                if (clause.Trim().StartsWith("employeeid ") || clause.Trim().StartsWith("employeeid="))
                {
                    database.SetParameterValue(commandWrapper, "@EmployeeId",
                                               clause.Trim().Remove(0, 10).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
                    continue;
                }
                if (clause.Trim().StartsWith("addressid ") || clause.Trim().StartsWith("addressid="))
                {
                    database.SetParameterValue(commandWrapper, "@AddressId",
                                               clause.Trim().Remove(0, 9).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
                    continue;
                }
                if (clause.Trim().StartsWith("rowguid ") || clause.Trim().StartsWith("rowguid="))
                {
                    database.SetParameterValue(commandWrapper, "@Rowguid", new Guid(
                                                   clause.Trim().Remove(0, 7).Trim().TrimStart(equalSign).Trim().Trim(singleQuote)));
                    continue;
                }
                if (clause.Trim().StartsWith("modifieddate ") || clause.Trim().StartsWith("modifieddate="))
                {
                    database.SetParameterValue(commandWrapper, "@ModifiedDate",
                                               clause.Trim().Remove(0, 12).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
                    continue;
                }

                throw new ArgumentException("Unable to use this part of the where clause in this version of Find: " + clause);
            }

            IDataReader reader = null;
            //Create Collection
            TList <EmployeeAddress> rows = new TList <EmployeeAddress>();


            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "Find", rows));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                Fill(reader, rows, start, pageLength);

                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "Find", rows));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }
            return(rows);
        }
		}//end Delete
		#endregion

		#region Find Functions

		#region Parsed Find Methods
		/// <summary>
		/// 	Returns rows meeting the whereClause condition from the DataSource.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
		/// <param name="start">Row number at which to start reading.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out. The number of rows that match this query.</param>
		/// <remarks>Operators must be capitalized (OR, AND).</remarks>
		/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.TransactionHistory objects.</returns>
		public override TList<TransactionHistory> Find(TransactionManager transactionManager, string whereClause, int start, int pageLength, out int count)
		{
			count = -1;
			if (whereClause.IndexOf(";") > -1)
				return new TList<TransactionHistory>();
	
			SqlDatabase database = new SqlDatabase(this._connectionString);
			DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Production.usp_adwTiers_TransactionHistory_Find", _useStoredProcedure);

		bool searchUsingOR = false;
		if (whereClause.IndexOf(" OR ") > 0) // did they want to do "a=b OR c=d OR..."?
			searchUsingOR = true;
		
		database.AddInParameter(commandWrapper, "@SearchUsingOR", DbType.Boolean, searchUsingOR);
		
		database.AddInParameter(commandWrapper, "@TransactionId", DbType.Int32, DBNull.Value);
		database.AddInParameter(commandWrapper, "@ProductId", DbType.Int32, DBNull.Value);
		database.AddInParameter(commandWrapper, "@ReferenceOrderId", DbType.Int32, DBNull.Value);
		database.AddInParameter(commandWrapper, "@ReferenceOrderLineId", DbType.Int32, DBNull.Value);
		database.AddInParameter(commandWrapper, "@TransactionDate", DbType.DateTime, DBNull.Value);
		database.AddInParameter(commandWrapper, "@TransactionType", DbType.StringFixedLength, DBNull.Value);
		database.AddInParameter(commandWrapper, "@Quantity", DbType.Int32, DBNull.Value);
		database.AddInParameter(commandWrapper, "@ActualCost", DbType.Currency, DBNull.Value);
		database.AddInParameter(commandWrapper, "@ModifiedDate", DbType.DateTime, DBNull.Value);
	
			// replace all instances of 'AND' and 'OR' because we already set searchUsingOR
			whereClause = whereClause.Replace(" AND ", "|").Replace(" OR ", "|") ; 
			string[] clauses = whereClause.ToLower().Split('|');
		
			// Here's what's going on below: Find a field, then to get the value we
			// drop the field name from the front, trim spaces, drop the '=' sign,
			// trim more spaces, and drop any outer single quotes.
			// Now handles the case when two fields start off the same way - like "Friendly='Yes' AND Friend='john'"
				
			char[] equalSign = {'='};
			char[] singleQuote = {'\''};
	   		foreach (string clause in clauses)
			{
				if (clause.Trim().StartsWith("transactionid ") || clause.Trim().StartsWith("transactionid="))
				{
					database.SetParameterValue(commandWrapper, "@TransactionId", 
						clause.Trim().Remove(0,13).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
					continue;
				}
				if (clause.Trim().StartsWith("productid ") || clause.Trim().StartsWith("productid="))
				{
					database.SetParameterValue(commandWrapper, "@ProductId", 
						clause.Trim().Remove(0,9).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
					continue;
				}
				if (clause.Trim().StartsWith("referenceorderid ") || clause.Trim().StartsWith("referenceorderid="))
				{
					database.SetParameterValue(commandWrapper, "@ReferenceOrderId", 
						clause.Trim().Remove(0,16).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
					continue;
				}
				if (clause.Trim().StartsWith("referenceorderlineid ") || clause.Trim().StartsWith("referenceorderlineid="))
				{
					database.SetParameterValue(commandWrapper, "@ReferenceOrderLineId", 
						clause.Trim().Remove(0,20).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
					continue;
				}
				if (clause.Trim().StartsWith("transactiondate ") || clause.Trim().StartsWith("transactiondate="))
				{
					database.SetParameterValue(commandWrapper, "@TransactionDate", 
						clause.Trim().Remove(0,15).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
					continue;
				}
				if (clause.Trim().StartsWith("transactiontype ") || clause.Trim().StartsWith("transactiontype="))
				{
					database.SetParameterValue(commandWrapper, "@TransactionType", 
						clause.Trim().Remove(0,15).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
					continue;
				}
				if (clause.Trim().StartsWith("quantity ") || clause.Trim().StartsWith("quantity="))
				{
					database.SetParameterValue(commandWrapper, "@Quantity", 
						clause.Trim().Remove(0,8).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
					continue;
				}
				if (clause.Trim().StartsWith("actualcost ") || clause.Trim().StartsWith("actualcost="))
				{
					database.SetParameterValue(commandWrapper, "@ActualCost", 
						clause.Trim().Remove(0,10).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
					continue;
				}
				if (clause.Trim().StartsWith("modifieddate ") || clause.Trim().StartsWith("modifieddate="))
				{
					database.SetParameterValue(commandWrapper, "@ModifiedDate", 
						clause.Trim().Remove(0,12).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
					continue;
				}
	
				throw new ArgumentException("Unable to use this part of the where clause in this version of Find: " + clause);
			}
					
			IDataReader reader = null;
			//Create Collection
			TList<TransactionHistory> rows = new TList<TransactionHistory>();
	
				
			try
			{
				//Provider Data Requesting Command Event
				OnDataRequesting(new CommandEventArgs(commandWrapper, "Find", rows)); 

				if (transactionManager != null)
				{
					reader = Utility.ExecuteReader(transactionManager, commandWrapper);
				}
				else
				{
					reader = Utility.ExecuteReader(database, commandWrapper);
				}		
				
				Fill(reader, rows, start, pageLength);
				
				if(reader.NextResult())
				{
					if(reader.Read())
					{
						count = reader.GetInt32(0);
					}
				}
				
				//Provider Data Requested Command Event
				OnDataRequested(new CommandEventArgs(commandWrapper, "Find", rows)); 
			}
			finally
			{
				if (reader != null) 
					reader.Close();	
					
				commandWrapper = null;
			}
			return rows;
		}
        /// <summary>
        ///     Returns rows from the DataSource that meet the parameter conditions.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
        /// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">out. The number of rows that match this query.</param>
        /// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.EmployeeAddress objects.</returns>
        public override TList <EmployeeAddress> Find(TransactionManager transactionManager, IFilterParameterCollection parameters, string orderBy, int start, int pageLength, out int count)
        {
            SqlFilterParameterCollection filter = null;

            if (parameters == null)
            {
                filter = new SqlFilterParameterCollection();
            }
            else
            {
                filter = parameters.GetParameters();
            }

            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "HumanResources.usp_adwTiers_EmployeeAddress_Find_Dynamic", typeof(EmployeeAddressColumn), filter, orderBy, start, pageLength);

            SqlFilterParameter param;

            for (int i = 0; i < filter.Count; i++)
            {
                param = filter[i];
                database.AddInParameter(commandWrapper, param.Name, param.DbType, param.GetValue());
            }

            TList <EmployeeAddress> rows   = new TList <EmployeeAddress>();
            IDataReader             reader = null;

            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "Find", rows));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                Fill(reader, rows, 0, int.MaxValue);
                count = rows.Count;

                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "Find", rows));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }

            return(rows);
        }
		/// <summary>
		/// 	Gets All rows from the DataSource.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="start">Row number at which to start reading.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out. The number of rows that match this query.</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.TransactionHistory objects.</returns>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
		public override TList<TransactionHistory> GetAll(TransactionManager transactionManager, int start, int pageLength, out int count)
		{
			SqlDatabase database = new SqlDatabase(this._connectionString);
			DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Production.usp_adwTiers_TransactionHistory_Get_List", _useStoredProcedure);
			
			IDataReader reader = null;
		
			//Create Collection
			TList<TransactionHistory> rows = new TList<TransactionHistory>();
			
			try
			{
				//Provider Data Requesting Command Event
				OnDataRequesting(new CommandEventArgs(commandWrapper, "GetAll", rows)); 
					
				if (transactionManager != null)
				{
					reader = Utility.ExecuteReader(transactionManager, commandWrapper);
				}
				else
				{
					reader = Utility.ExecuteReader(database, commandWrapper);
				}		
		
				Fill(reader, rows, start, pageLength);
				count = -1;
				if(reader.NextResult())
				{
					if(reader.Read())
					{
						count = reader.GetInt32(0);
					}
				}
				
				//Provider Data Requested Command Event
				OnDataRequested(new CommandEventArgs(commandWrapper, "GetAll", rows)); 
			}
			finally 
			{
				if (reader != null) 
					reader.Close();
					
				commandWrapper = null;	
			}
			return rows;
		}//end getall
        }        //end getall

        #endregion

        #region GetPaged Methods

        /// <summary>
        /// Gets a page of rows from the DataSource.
        /// </summary>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">Number of rows in the DataSource.</param>
        /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
        /// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <remarks></remarks>
        /// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.EmployeeAddress objects.</returns>
        public override TList <EmployeeAddress> GetPaged(TransactionManager transactionManager, string whereClause, string orderBy, int start, int pageLength, out int count)
        {
            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "HumanResources.usp_adwTiers_EmployeeAddress_GetPaged", _useStoredProcedure);


            if (commandWrapper.CommandType == CommandType.Text &&
                commandWrapper.CommandText != null)
            {
                commandWrapper.CommandText = commandWrapper.CommandText.Replace(SqlUtil.PAGE_INDEX, string.Concat(SqlUtil.PAGE_INDEX, Guid.NewGuid().ToString("N").Substring(0, 8)));
            }

            database.AddInParameter(commandWrapper, "@WhereClause", DbType.String, whereClause);
            database.AddInParameter(commandWrapper, "@OrderBy", DbType.String, orderBy);
            database.AddInParameter(commandWrapper, "@PageIndex", DbType.Int32, start);
            database.AddInParameter(commandWrapper, "@PageSize", DbType.Int32, pageLength);

            IDataReader reader = null;
            //Create Collection
            TList <EmployeeAddress> rows = new TList <EmployeeAddress>();

            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "GetPaged", rows));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                Fill(reader, rows, 0, int.MaxValue);
                count = rows.Count;

                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "GetPaged", rows));
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }

            return(rows);
        }
		/// <summary>
		/// 	Gets rows from the datasource based on the IX_TransactionHistory_ReferenceOrderID_ReferenceOrderLineID index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_referenceOrderId">Purchase order, sales order, or work order identification number.</param>
		/// <param name="_referenceOrderLineId">Line number associated with the purchase order, sales order, or work order.</param>
		/// <param name="start">Row number at which to start reading.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query.</param>
		/// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns>
		/// <remarks></remarks>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
		public override TList<TransactionHistory> GetByReferenceOrderIdReferenceOrderLineId(TransactionManager transactionManager, System.Int32 _referenceOrderId, System.Int32 _referenceOrderLineId, int start, int pageLength, out int count)
		{
			SqlDatabase database = new SqlDatabase(this._connectionString);
			DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Production.usp_adwTiers_TransactionHistory_GetByReferenceOrderIdReferenceOrderLineId", _useStoredProcedure);
			
				database.AddInParameter(commandWrapper, "@ReferenceOrderId", DbType.Int32, _referenceOrderId);
				database.AddInParameter(commandWrapper, "@ReferenceOrderLineId", DbType.Int32, _referenceOrderLineId);
			
			IDataReader reader = null;
			TList<TransactionHistory> tmp = new TList<TransactionHistory>();
			try
			{
				//Provider Data Requesting Command Event
				OnDataRequesting(new CommandEventArgs(commandWrapper, "GetByReferenceOrderIdReferenceOrderLineId", tmp)); 

				if (transactionManager != null)
				{
					reader = Utility.ExecuteReader(transactionManager, commandWrapper);
				}
				else
				{
					reader = Utility.ExecuteReader(database, commandWrapper);
				}		
		
				//Create collection and fill
				Fill(reader, tmp, start, pageLength);
				count = -1;
				if(reader.NextResult())
				{
					if(reader.Read())
					{
						count = reader.GetInt32(0);
					}
				}
				
				//Provider Data Requested Command Event
				OnDataRequested(new CommandEventArgs(commandWrapper, "GetByReferenceOrderIdReferenceOrderLineId", tmp));
			}
			finally 
			{
				if (reader != null) 
					reader.Close();
					
				commandWrapper = null;
			}
			
			return tmp;
			
			//return rows;
		}
        /// <summary>
        ///     Gets rows from the datasource based on the PK_EmployeeAddress_EmployeeID_AddressID index.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_employeeId">Primary key. Foreign key to Employee.EmployeeID.</param>
        /// <param name="_addressId">Primary key. Foreign key to Address.AddressID.</param>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">out parameter to get total records for query.</param>
        /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.EmployeeAddress"/> class.</returns>
        /// <remarks></remarks>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
        public override Nettiers.AdventureWorks.Entities.EmployeeAddress GetByEmployeeIdAddressId(TransactionManager transactionManager, System.Int32 _employeeId, System.Int32 _addressId, int start, int pageLength, out int count)
        {
            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "HumanResources.usp_adwTiers_EmployeeAddress_GetByEmployeeIdAddressId", _useStoredProcedure);

            database.AddInParameter(commandWrapper, "@EmployeeId", DbType.Int32, _employeeId);
            database.AddInParameter(commandWrapper, "@AddressId", DbType.Int32, _addressId);

            IDataReader             reader = null;
            TList <EmployeeAddress> tmp    = new TList <EmployeeAddress>();

            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "GetByEmployeeIdAddressId", tmp));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                //Create collection and fill
                Fill(reader, tmp, start, pageLength);
                count = -1;
                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "GetByEmployeeIdAddressId", tmp));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }

            if (tmp.Count == 1)
            {
                return(tmp[0]);
            }
            else if (tmp.Count == 0)
            {
                return(null);
            }
            else
            {
                throw new DataException("Cannot find the unique instance of the class.");
            }

            //return rows;
        }
		/// <summary>
		/// Lets you efficiently bulk insert many entities to the database.
		/// </summary>
		/// <param name="transactionManager">The transaction manager.</param>
		/// <param name="entities">The entities.</param>
		/// <remarks>
		///		After inserting into the datasource, the Nettiers.AdventureWorks.Entities.TransactionHistory object will be updated
		/// 	to refelect any changes made by the datasource. (ie: identity or computed columns)
		/// </remarks>	
		public override void BulkInsert(TransactionManager transactionManager, TList<Nettiers.AdventureWorks.Entities.TransactionHistory> entities)
		{
			//System.Data.SqlClient.SqlBulkCopy bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints); //, null);
			
			System.Data.SqlClient.SqlBulkCopy bulkCopy = null;
	
			if (transactionManager != null && transactionManager.IsOpen)
			{			
				System.Data.SqlClient.SqlConnection cnx = transactionManager.TransactionObject.Connection as System.Data.SqlClient.SqlConnection;
				System.Data.SqlClient.SqlTransaction transaction = transactionManager.TransactionObject as System.Data.SqlClient.SqlTransaction;
				bulkCopy = new System.Data.SqlClient.SqlBulkCopy(cnx, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints, transaction); //, null);
			}
			else
			{
				bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints); //, null);
			}
			
			bulkCopy.BulkCopyTimeout = 360;
			bulkCopy.DestinationTableName = "TransactionHistory";
			
			DataTable dataTable = new DataTable();
			DataColumn col0 = dataTable.Columns.Add("TransactionID", typeof(System.Int32));
			col0.AllowDBNull = false;		
			DataColumn col1 = dataTable.Columns.Add("ProductID", typeof(System.Int32));
			col1.AllowDBNull = false;		
			DataColumn col2 = dataTable.Columns.Add("ReferenceOrderID", typeof(System.Int32));
			col2.AllowDBNull = false;		
			DataColumn col3 = dataTable.Columns.Add("ReferenceOrderLineID", typeof(System.Int32));
			col3.AllowDBNull = false;		
			DataColumn col4 = dataTable.Columns.Add("TransactionDate", typeof(System.DateTime));
			col4.AllowDBNull = false;		
			DataColumn col5 = dataTable.Columns.Add("TransactionType", typeof(System.String));
			col5.AllowDBNull = false;		
			DataColumn col6 = dataTable.Columns.Add("Quantity", typeof(System.Int32));
			col6.AllowDBNull = false;		
			DataColumn col7 = dataTable.Columns.Add("ActualCost", typeof(System.Decimal));
			col7.AllowDBNull = false;		
			DataColumn col8 = dataTable.Columns.Add("ModifiedDate", typeof(System.DateTime));
			col8.AllowDBNull = false;		
			
			bulkCopy.ColumnMappings.Add("TransactionID", "TransactionID");
			bulkCopy.ColumnMappings.Add("ProductID", "ProductID");
			bulkCopy.ColumnMappings.Add("ReferenceOrderID", "ReferenceOrderID");
			bulkCopy.ColumnMappings.Add("ReferenceOrderLineID", "ReferenceOrderLineID");
			bulkCopy.ColumnMappings.Add("TransactionDate", "TransactionDate");
			bulkCopy.ColumnMappings.Add("TransactionType", "TransactionType");
			bulkCopy.ColumnMappings.Add("Quantity", "Quantity");
			bulkCopy.ColumnMappings.Add("ActualCost", "ActualCost");
			bulkCopy.ColumnMappings.Add("ModifiedDate", "ModifiedDate");
			
			foreach(Nettiers.AdventureWorks.Entities.TransactionHistory entity in entities)
			{
				if (entity.EntityState != EntityState.Added)
					continue;
					
				DataRow row = dataTable.NewRow();
				
					row["TransactionID"] = entity.TransactionId;
							
				
					row["ProductID"] = entity.ProductId;
							
				
					row["ReferenceOrderID"] = entity.ReferenceOrderId;
							
				
					row["ReferenceOrderLineID"] = entity.ReferenceOrderLineId;
							
				
					row["TransactionDate"] = entity.TransactionDate;
							
				
					row["TransactionType"] = entity.TransactionType;
							
				
					row["Quantity"] = entity.Quantity;
							
				
					row["ActualCost"] = entity.ActualCost;
							
				
					row["ModifiedDate"] = entity.ModifiedDate;
							
				
				dataTable.Rows.Add(row);
			}		
			
			// send the data to the server		
			bulkCopy.WriteToServer(dataTable);		
			
			// update back the state
			foreach(Nettiers.AdventureWorks.Entities.TransactionHistory entity in entities)
			{
				if (entity.EntityState != EntityState.Added)
					continue;
			
				entity.AcceptChanges();
			}
		}
        /// <summary>
        /// Lets you efficiently bulk insert many entities to the database.
        /// </summary>
        /// <param name="transactionManager">The transaction manager.</param>
        /// <param name="entities">The entities.</param>
        /// <remarks>
        ///		After inserting into the datasource, the Nettiers.AdventureWorks.Entities.EmployeeAddress object will be updated
        ///     to refelect any changes made by the datasource. (ie: identity or computed columns)
        /// </remarks>
        public override void BulkInsert(TransactionManager transactionManager, TList <Nettiers.AdventureWorks.Entities.EmployeeAddress> entities)
        {
            //System.Data.SqlClient.SqlBulkCopy bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints); //, null);

            System.Data.SqlClient.SqlBulkCopy bulkCopy = null;

            if (transactionManager != null && transactionManager.IsOpen)
            {
                System.Data.SqlClient.SqlConnection  cnx         = transactionManager.TransactionObject.Connection as System.Data.SqlClient.SqlConnection;
                System.Data.SqlClient.SqlTransaction transaction = transactionManager.TransactionObject as System.Data.SqlClient.SqlTransaction;
                bulkCopy = new System.Data.SqlClient.SqlBulkCopy(cnx, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints, transaction);                 //, null);
            }
            else
            {
                bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints);                 //, null);
            }

            bulkCopy.BulkCopyTimeout      = 360;
            bulkCopy.DestinationTableName = "EmployeeAddress";

            DataTable  dataTable = new DataTable();
            DataColumn col0      = dataTable.Columns.Add("EmployeeID", typeof(System.Int32));

            col0.AllowDBNull = false;
            DataColumn col1 = dataTable.Columns.Add("AddressID", typeof(System.Int32));

            col1.AllowDBNull = false;
            DataColumn col2 = dataTable.Columns.Add("rowguid", typeof(System.Guid));

            col2.AllowDBNull = false;
            DataColumn col3 = dataTable.Columns.Add("ModifiedDate", typeof(System.DateTime));

            col3.AllowDBNull = false;

            bulkCopy.ColumnMappings.Add("EmployeeID", "EmployeeID");
            bulkCopy.ColumnMappings.Add("AddressID", "AddressID");
            bulkCopy.ColumnMappings.Add("rowguid", "rowguid");
            bulkCopy.ColumnMappings.Add("ModifiedDate", "ModifiedDate");

            foreach (Nettiers.AdventureWorks.Entities.EmployeeAddress entity in entities)
            {
                if (entity.EntityState != EntityState.Added)
                {
                    continue;
                }

                DataRow row = dataTable.NewRow();

                row["EmployeeID"] = entity.EmployeeId;


                row["AddressID"] = entity.AddressId;


                row["rowguid"] = entity.Rowguid;


                row["ModifiedDate"] = entity.ModifiedDate;


                dataTable.Rows.Add(row);
            }

            // send the data to the server
            bulkCopy.WriteToServer(dataTable);

            // update back the state
            foreach (Nettiers.AdventureWorks.Entities.EmployeeAddress entity in entities)
            {
                if (entity.EntityState != EntityState.Added)
                {
                    continue;
                }

                entity.AcceptChanges();
            }
        }
		/// <summary>
		/// 	Update an existing row in the datasource.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="entity">Nettiers.AdventureWorks.Entities.TransactionHistory object to update.</param>
		/// <remarks>
		///		After updating the datasource, the Nettiers.AdventureWorks.Entities.TransactionHistory object will be updated
		/// 	to refelect any changes made by the datasource. (ie: identity or computed columns)
		/// </remarks>
		/// <returns>Returns true if operation is successful.</returns>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
		public override bool Update(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.TransactionHistory entity)
		{
			SqlDatabase database = new SqlDatabase(this._connectionString);
			DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Production.usp_adwTiers_TransactionHistory_Update", _useStoredProcedure);
			
			database.AddInParameter(commandWrapper, "@TransactionId", DbType.Int32, entity.TransactionId );
			database.AddInParameter(commandWrapper, "@ProductId", DbType.Int32, entity.ProductId );
			database.AddInParameter(commandWrapper, "@ReferenceOrderId", DbType.Int32, entity.ReferenceOrderId );
			database.AddInParameter(commandWrapper, "@ReferenceOrderLineId", DbType.Int32, entity.ReferenceOrderLineId );
			database.AddInParameter(commandWrapper, "@TransactionDate", DbType.DateTime, entity.TransactionDate );
			database.AddInParameter(commandWrapper, "@TransactionType", DbType.StringFixedLength, entity.TransactionType );
			database.AddInParameter(commandWrapper, "@Quantity", DbType.Int32, entity.Quantity );
			database.AddInParameter(commandWrapper, "@ActualCost", DbType.Currency, entity.ActualCost );
			database.AddInParameter(commandWrapper, "@ModifiedDate", DbType.DateTime, entity.ModifiedDate );
			
			int results = 0;
			
			//Provider Data Requesting Command Event
			OnDataRequesting(new CommandEventArgs(commandWrapper, "Update", entity));

			if (transactionManager != null)
			{
				results = Utility.ExecuteNonQuery(transactionManager, commandWrapper);
			}
			else
			{
				results = Utility.ExecuteNonQuery(database,commandWrapper);
			}
			
			//Stop Tracking Now that it has been updated and persisted.
			if (DataRepository.Provider.EnableEntityTracking)
				EntityManager.StopTracking(entity.EntityTrackingKey);
			
			
			entity.AcceptChanges();
			
			//Provider Data Requested Command Event
			OnDataRequested(new CommandEventArgs(commandWrapper, "Update", entity));

			return Convert.ToBoolean(results);
		}
 public SetUserDisplay(TransactionManager mgr, UserMainView umv)
 {
     InitializeComponent();
     this.umv = umv;
     this.mgr = mgr;
 }