public override City FindByPK(IPrimaryKey pk)
 {
     SqlCommandType = Constants.DBCommandType.SQL;
     CMDText        = FINDBYPK_STMT;
     MapToObject    = new CityMapToObject(logger);
     return(base.FindByPK(pk));
 }
Esempio n. 2
0
        public Uri GetEntityApiUri(IPrimaryKey entity)
        {
            if (_templates == null)
            {
                lock (_lock)
                {
                    if (_templates == null)
                    {
                        _templates = CompileUrls();
                    }
                }
            }

            var testedType = GetMatchingType(entity.GetType());

            if (testedType == null)
            {
                return(null);
            }

            return(new UriBuilder(GetUrlBase())
            {
                Path = GetPath(testedType, entity)
            }.Uri);
        }
Esempio n. 3
0
        protected async Task <int> Delete(IPrimaryKey pk)
        {
            int rows = 0;

            try
            {
                if (dbc.Connection.State != ConnectionState.Open)
                {
                    await dbc.Open();
                }

                if (unitOfWork != null)
                {
                    await unitOfWork.Enlist();
                }
                using (SqlCommand cmd = new SqlCommand(CMDText, dbc.Connection))
                {
                    cmd.Parameters.Add(new SqlParameter("@pk", pk.Key));
                    rows = await cmd.ExecuteNonQueryAsync();
                }
            }
            catch (SqlException ex)
            {
                logger.LogError(ex.Message);
            }
            logger.LogInformation($"Delete complete for {typeof(TEntity)} entity.");
            return(rows);
        }
Esempio n. 4
0
        public void TestDeleteFlagsSetContactPerson()
        {
            ContactPersonCompositeKey myContact = new ContactPersonCompositeKey();

            Assert.IsTrue(myContact.Status.IsNew); // this object is new
            myContact.SetPropertyValue("DateOfBirth", new DateTime(1980, 01, 22));
            myContact.SetPropertyValue("FirstName", "Brad");
            myContact.SetPropertyValue("Surname", "Vincent");
            myContact.SetPropertyValue("PK1Prop1", Guid.NewGuid());
            myContact.SetPropertyValue("PK1Prop2", Guid.NewGuid());

            myContact.Save();                       //save the object to the DB
            Assert.IsFalse(myContact.Status.IsNew); // this object is saved and thus no longer
            // new
            Assert.IsFalse(myContact.Status.IsDeleted);

            IPrimaryKey id = myContact.ID; //Save the objectsID so that it can be loaded from the Database

            Assert.AreEqual(id, myContact.ID);
            myContact.MarkForDelete();
            Assert.IsTrue(myContact.Status.IsDeleted);
            myContact.Save();
            Assert.IsTrue(myContact.Status.IsDeleted);
            Assert.IsTrue(myContact.Status.IsNew);
        }
Esempio n. 5
0
        public void TestDontGetTheFreshestObject_Strategy()
        {
            //------------------------------Setup Test
            ClassDef.ClassDefs.Clear();
            SetupDefaultContactPersonBO();
            ContactPersonTestBO originalContactPerson = new ContactPersonTestBO();

            originalContactPerson.Surname = "FirstSurname";
            originalContactPerson.Save();
            IPrimaryKey origCPID = originalContactPerson.ID;

            BORegistry.BusinessObjectManager = new BusinessObjectManagerSpy();//Ensures a new BOMan is created and used for each test


            //load second object from DB to ensure that it is now in the object manager
            ContactPersonTestBO myContact2 =
                BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObject <ContactPersonTestBO>(origCPID);

            //-----------------------------Execute Test-------------------------
            //Edit first object and save
            originalContactPerson.Surname = "SecondSurname";
            originalContactPerson.Save();

            ContactPersonTestBO myContact3 =
                BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObject <ContactPersonTestBO>(origCPID);

            //-----------------------------Assert Result-----------------------
            Assert.AreSame(myContact3, myContact2);
            //The two surnames should be equal since the myContact3 was refreshed
            // when it was loaded.
            Assert.AreNotEqual(originalContactPerson.Surname, myContact3.Surname);
            //Just to check the myContact2 should also match since it is physically the
            // same object as myContact3
            Assert.AreNotEqual(originalContactPerson.Surname, myContact2.Surname);
        }
Esempio n. 6
0
        public void RecoverNewObjectFromObjectManagerBeforeAndAfterPersist()
        {
            ContactPersonCompositeKey myContact = new ContactPersonCompositeKey();

            myContact.SetPropertyValue("DateOfBirth", new DateTime(1980, 01, 22));
            myContact.SetPropertyValue("FirstName", "Brad");
            myContact.SetPropertyValue("Surname", "Vincent");
            myContact.SetPropertyValue("PK1Prop1", Guid.NewGuid());
            myContact.SetPropertyValue("PK1Prop2", Guid.NewGuid());
            IPrimaryKey id = myContact.ID; //Save the objectsID so that it can be loaded from the Database

            myContact.Save();              //save the object to the DB

            //			BOPrimaryKey id = myContact.ID; //Save the objectsID so that it can be loaded from the Database
            Assert.AreEqual(id, myContact.ID);

            ContactPersonCompositeKey mySecondContactPerson = ContactPersonCompositeKey.GetContactPersonCompositeKey(id);

            Assert.IsTrue(ReferenceEquals(myContact, mySecondContactPerson));
            Assert.AreEqual(myContact.ID,
                            mySecondContactPerson.ID);
            Assert.AreEqual(myContact.GetPropertyValue("FirstName"), mySecondContactPerson.GetPropertyValue("FirstName"));
            Assert.AreEqual(myContact.GetPropertyValue("DateOfBirth"),
                            mySecondContactPerson.GetPropertyValue("DateOfBirth"));

            //Change the MyContact's Surname see if mySecondContactPerson is changed.
            //this should change since the second contact person was obtained from object manager and
            // these should thus be the same instance.
            myContact.SetPropertyValue("Surname", "New Surname");
            Assert.AreEqual(myContact.GetPropertyValue("Surname"), mySecondContactPerson.GetPropertyValue("Surname"));
        }
Esempio n. 7
0
        public void TestEditTwoInstancesContactPerson()
        {
            ContactPerson myContact = new ContactPerson();

            myContact.DateOfBirth = new DateTime(1980, 01, 22);
            myContact.FirstName   = "Brad";
            myContact.Surname     = "Vincent5";

            myContact.Save();              //save the object to the DB

            IPrimaryKey id = myContact.ID; //Save the objectsID so that it can be loaded from the Database

            Assert.AreEqual(id, myContact.ID);

            ContactPerson mySecondContactPerson =
                BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObject <ContactPerson>(id);

            Assert.AreEqual(myContact.ID,
                            mySecondContactPerson.ID);
            Assert.AreEqual(myContact.FirstName, mySecondContactPerson.FirstName);
            Assert.AreEqual(myContact.DateOfBirth, mySecondContactPerson.DateOfBirth);

            //Change the MyContact's Surname see if mySecondContactPerson is changed.
            //this should change since the second contact person was obtained from object manager and
            // these should thus be the same instance.
            myContact.Surname = "New Surname";
            Assert.AreEqual(myContact.Surname, mySecondContactPerson.Surname);
        }
Esempio n. 8
0
        public void Test_LoadObject_UpdateObjectMan_NonGenericLoad()
        {
            //---------------Set up test pack-------------------
            ClassDef classDef           = ContactPersonTestBO.LoadDefaultClassDef();
            BusinessObjectManager boMan = BusinessObjectManager.Instance;

            ContactPersonTestBO cp = CreateSavedCP();
            IPrimaryKey         id = cp.ID;

            cp = null;

            TestUtil.WaitForGC();
            boMan.ClearLoadedObjects();

            //---------------Assert Precondition----------------
            Assert.AreEqual(0, boMan.Count);

            //---------------Execute Test ----------------------
            ContactPersonTestBO contactPersonTestBO = (ContactPersonTestBO)BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObject(classDef, id);

            //---------------Test Result -----------------------
            Assert.IsNotNull(contactPersonTestBO);
            Assert.AreEqual(1, boMan.Count);
            Assert.IsTrue(boMan.Contains(contactPersonTestBO));

            Assert.IsTrue(boMan.Contains(id));
            Assert.IsTrue(boMan.Contains(id.GetObjectId()));
            Assert.AreSame(contactPersonTestBO, boMan[id.GetObjectId()]);
            Assert.AreSame(contactPersonTestBO, boMan[id]);
        }
Esempio n. 9
0
        private EntityEntry FindEntry(Type t, IPrimaryKey instance, PropertyInfo[] props)
        {
            var values     = props.Select(x => x.GetValue(instance)).ToArray();
            var entryQuery = _dc.Value.ChangeTracker.Entries()
                             .Where(x => x.Entity.GetType() == t)
                             .Where(x =>
            {
                for (int i = 0; i < props.Length; i++)
                {
                    if (!object.Equals(props[i].GetValue(x.Entity), values[i]))
                    {
                        return(false);
                    }
                }

                return(true);
            })
                             .FirstOrDefault();

            if (entryQuery == null)
            {
                return(_dc.Value.Entry(instance));
            }
            return(entryQuery);
        }
 public Contact FindViewByPK(IPrimaryKey pk)
 {
     SqlCommandType = Constants.DBCommandType.SQL;
     CMDText        = FINDBYPKVIEW_STMT;
     MapToObject    = new ContactMapToObjectView(logger);
     return(base.FindByPK(pk));
 }
Esempio n. 11
0
        protected async Task <int> Update(TEntity entity, IPrimaryKey pk)
        {
            int rows = 0;

            try
            {
                if (dbc.Connection.State != ConnectionState.Open)
                {
                    await dbc.Open();
                }

                if (unitOfWork != null)
                {
                    await unitOfWork.Enlist();
                }
                using (SqlCommand cmd = new SqlCommand(CMDText, dbc.Connection))
                {
                    if (SqlCommandType == Constants.DBCommandType.SPROC)
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                    }
                    MapFromObject.Execute(entity, cmd);
                    cmd.Parameters.Add(new SqlParameter("@pk", pk.Key));
                    rows = await cmd.ExecuteNonQueryAsync();
                }
            }
            catch (SqlException ex)
            {
                logger.LogError(ex.Message);
            }
            logger.LogInformation($"Update complete for {typeof(TEntity)} entity.");
            return(rows);
        }
        public void Test_LoadExistingBO_AllowRead_True()
        {
            //---------------Set up test pack-------------------
            MyBoAuthenticationStub.LoadDefaultClassDef();
            IBusinessObjectAuthorisation authorisationStub = GetAuthorisationStub_CanCreate_True();
            MyBoAuthenticationStub       myBoStub          = new MyBoAuthenticationStub();

            myBoStub.SetAuthorisation(authorisationStub);
            myBoStub.Save();

            authorisationStub = GetAuthorisationStub_CanRead_True();
            myBoStub.SetAuthorisation(authorisationStub);
            IPrimaryKey id = myBoStub.ID;

            FixtureEnvironment.ClearBusinessObjectManager();

            //---------------Assert Precondition----------------
            Assert.IsTrue(authorisationStub.IsAuthorised(myBoStub, BusinessObjectActions.CanRead));
            Assert.IsFalse(myBoStub.Status.IsNew);

            //---------------Execute Test ----------------------
            myBoStub = BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObject <MyBoAuthenticationStub>(id);
            object value = myBoStub.GetPropertyValue("Prop1");

            //---------------Test Result -----------------------
            Assert.IsNull(value);
            Assert.IsFalse(myBoStub.Status.IsDirty);
        }
        public void Test_LoadExistingBO_Fail_AllowRead_False()
        {
            //---------------Set up test pack-------------------
            MyBoAuthenticationStub.LoadDefaultClassDef();
            IBusinessObjectAuthorisation authorisationStub = GetAuthorisationStub_CanCreate_True();
            MyBoAuthenticationStub       myBoStub          = new MyBoAuthenticationStub();

            myBoStub.SetAuthorisation(authorisationStub);
            myBoStub.Save();

            authorisationStub = GetAuthorisationStub_CanRead_False();
            myBoStub.SetAuthorisation(authorisationStub);
            IPrimaryKey id = myBoStub.ID;

            FixtureEnvironment.ClearBusinessObjectManager();

            //---------------Assert Precondition----------------
            Assert.IsFalse(authorisationStub.IsAuthorised(myBoStub, BusinessObjectActions.CanRead));
            Assert.IsFalse(myBoStub.Status.IsNew);

            //---------------Execute Test ----------------------
            myBoStub = BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObject <MyBoAuthenticationStub>(id);
            try
            {
                myBoStub.GetPropertyValue("Prop1");
                Assert.Fail("expected Err");
            }
            //---------------Test Result -----------------------
            catch (BusObjReadException ex)
            {
                StringAssert.Contains("The logged on user", ex.Message);
                StringAssert.Contains("is not authorised to read ", ex.Message);
            }
        }
Esempio n. 14
0
        public void Test_ReturnSameObjectFromBusinessObjectLoader()
        {
            //---------------Set up test pack-------------------
            ContactPersonTestBO.LoadClassDefWithAddressTestBOsRelationship();
            BusinessObjectManager boMan = BusinessObjectManager.Instance;
            ContactPersonTestBO   originalContactPerson = CreateSavedCP();
            IPrimaryKey           id = originalContactPerson.ID;

            originalContactPerson = null;
            boMan.ClearLoadedObjects();
            TestUtil.WaitForGC();

            //load second object from DB to ensure that it is now in the object manager
            ContactPersonTestBO myContact2 =
                BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObject <ContactPersonTestBO>(id);

            //---------------Assert Precondition----------------
            Assert.AreNotSame(originalContactPerson, myContact2);

            //---------------Execute Test ----------------------
            ContactPersonTestBO myContact3 =
                BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObject <ContactPersonTestBO>(id);

            //---------------Test Result -----------------------
            Assert.AreNotSame(originalContactPerson, myContact3);
            Assert.AreSame(myContact2, myContact3);
        }
 public override async Task <State> FindByPK(IPrimaryKey pk)
 {
     SqlCommandType = Constants.DBCommandType.SQL;
     CMDText        = FINDBYPK_STMT;
     MapToObject    = new StateMapToObject(logger);
     return(await base.FindByPK(pk));
 }
Esempio n. 16
0
 public async Task <ProjectContact> FindByPKView(IPrimaryKey pk)
 {
     SqlCommandType = Constants.DBCommandType.SQL;
     CMDText        = FINDBYPKVIEW_STMT;
     MapToObject    = new ProjectContactMapToObjectView(logger);
     return(await base.FindByPK(pk));
 }
Esempio n. 17
0
 /// <summary>
 /// Loads a business object of the type identified by a <see cref="ClassDef"/>, using the Primary key given as the criteria
 /// </summary>
 /// <param name="classDef">The ClassDef of the object to load.</param>
 /// <param name="primaryKey">The primary key to use to load the business object</param>
 /// <returns>The business object that was found. If none was found, null is returned. If more than one is found an <see cref="HabaneroDeveloperException"/> error is throw</returns>
 public IBusinessObject GetBusinessObject(IClassDef classDef, IPrimaryKey primaryKey)
 {
     if (_businessObjectLoaders.ContainsKey(classDef.ClassType))
     {
         return(_businessObjectLoaders[classDef.ClassType].GetBusinessObject(classDef, primaryKey));
     }
     return(_defaultBusinessObjectLoader.GetBusinessObject(classDef, primaryKey));
 }
Esempio n. 18
0
 /// <summary>
 /// Loads a business object of type T, using the Primary key given as the criteria
 /// </summary>
 /// <typeparam name="T">The type of object to load. This must be a class that implements IBusinessObject and has a parameterless constructor</typeparam>
 /// <param name="primaryKey">The primary key to use to load the business object</param>
 /// <returns>The business object that was found. If none was found, null is returned. If more than one is found an <see cref="HabaneroDeveloperException"/> error is throw</returns>
 public T GetBusinessObject <T>(IPrimaryKey primaryKey) where T : class, IBusinessObject, new()
 {
     if (_businessObjectLoaders.ContainsKey(typeof(T)))
     {
         return(_businessObjectLoaders[typeof(T)].GetBusinessObject <T>(primaryKey));
     }
     return(_defaultBusinessObjectLoader.GetBusinessObject <T>(primaryKey));
 }
Esempio n. 19
0
        protected override void FillColumnsTable(DiagramTableItem item, Dictionary <int, Box> colNameBoxes, TableBox table)
        {
            var fkColsIndexes = GetFkColIndexes(item.Table);

            IPrimaryKey pk       = item.Table.FindConstraint <IPrimaryKey>();
            int         fldindex = 0;

            table.ColumnDelimiter = new FixedBox {
                BackgroundBrush = Brushes.Black, FixedSize = new Size(1, 1)
            };

            if (pk != null)
            {
                foreach (IColumnStructure col in item.Table.Columns)
                {
                    if (pk.Columns.IndexOfIf(cr => cr.ColumnName == col.ColumnName) >= 0)
                    {
                        var row = table.AddRow();
                        row.AddCell("PK", ColumnBold, Brushes.Black);
                        var cname = row.AddCell(col.ColumnName, col.IsNullable ? ColumnRegular : ColumnBold, Brushes.Black);
                        if (colNameBoxes != null)
                        {
                            colNameBoxes[fldindex] = cname;
                        }
                    }
                    fldindex++;
                }
                table.RowDelimiterOverrides[pk.Columns.Count] = new FixedBox {
                    BackgroundBrush = Brushes.Black, FixedSize = new Size(1, 1), MarginTop = 2, MarginBottom = 2
                };
            }

            foreach (IColumnStructure col in item.Table.Columns)
            {
                if (pk == null || pk.Columns.IndexOfIf(cr => cr.ColumnName == col.ColumnName) < 0)
                {
                    var row = table.AddRow();
                    if (fkColsIndexes.ContainsKey(col.ColumnName))
                    {
                        row.AddCell("FK" + (fkColsIndexes[col.ColumnName] + 1).ToString(), ColumnRegular, Brushes.Black);
                    }
                    else
                    {
                        row.AddCell(new FixedBox {
                            FixedSize = new Size(16, 16)
                        });
                    }
                    var cname = row.AddCell(col.ColumnName, col.IsNullable ? ColumnRegular : ColumnBold, Brushes.Black);
                    if (colNameBoxes != null)
                    {
                        colNameBoxes[fldindex] = cname;
                    }
                }
                fldindex++;
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Obtains set of properties participating primary key of the entity
        /// </summary>
        /// <param name="pk">Entity with primary key</param>
        /// <returns>Set of properties participating primary key</returns>
        public static PropertyInfo[] KeyProperties(this IPrimaryKey pk)
        {
            var t = pk.GetType().GetProperty(nameof(IPrimaryKey <int> .PrimaryKey), BindingFlags.Public | BindingFlags.Instance);

            var keyProps = t.GetValue(pk);

            var extr = FromTuple <LambdaExpression>(keyProps).Select(x => x.AsPropertyExpression());

            return(extr.ToArray());
        }
Esempio n. 21
0
        private void CreateUpdatedContactPersonTestPack()
        {
            ContactPerson myContact = new ContactPerson();

            myContact.DateOfBirth = new DateTime(1969, 01, 29);
            myContact.FirstName   = "FirstName";
            myContact.Surname     = "Surname";
            myContact.Save();
            _updateContactPersonId = myContact.ID;
        }
        public ApplicationUser FindByPKView(IPrimaryKey pk)
        {
            ApplicationUserClaimRepository userClaimRepo = new ApplicationUserClaimRepository(Settings, logger, Connection);

            ApplicationUser user = base.FindByPK(pk);

            user.Claims = userClaimRepo.FindAll().Where(uc => uc.UserId == user.Id).ToList();

            return(user);
        }
 public T GetBusinessObject <T>(IPrimaryKey key) where T : class, IBusinessObject
 {
     if (_dataStore.AllObjects.ContainsKey(key))
     {
         return((T)_dataStore.AllObjects[key]);
     }
     else
     {
         return(null);
     }
 }
 public T GetBusinessObject <T>(IPrimaryKey key) where T : class, IBusinessObject
 {
     if (BusinessObject.AllLoadedBusinessObjects().ContainsKey(key.GetObjectId()))
     {
         return((T)BusinessObject.AllLoadedBusinessObjects()[key.GetObjectId()].Target);
     }
     else
     {
         return((T)BOLoader.Instance.GetBusinessObjectByID(typeof(T), key));
     }
 }
Esempio n. 25
0
        public virtual async Task <TEntity> FindByPK(IPrimaryKey pk)
        {
            int     idx    = 1;
            TEntity entity = null;

            try
            {
                if (dbc.Connection.State != ConnectionState.Open)
                {
                    await dbc.Open();
                }

                using (SqlCommand cmd = new SqlCommand(CMDText, dbc.Connection))
                {
                    if (SqlCommandType == Constants.DBCommandType.SPROC)
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                    }

                    if (pk.IsComposite)
                    {
                        foreach (int k in ((PrimaryKey)pk).CompositeKey)
                        {
                            cmd.Parameters.Add(new SqlParameter("@pk" + idx.ToString(), k));
                            idx++;
                        }
                    }
                    else
                    {
                        cmd.Parameters.Add(new SqlParameter("@pk", pk.Key));
                    }

                    using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
                    {
                        if (reader.Read())
                        {
                            entity = MapToObject.Execute(reader);
                        }
                        else
                        {
                            entity = null;
                        }
                        logger.LogInformation($"FindByPK complete for {typeof(TEntity)} entity.");
                    }
                }
            }
            catch (SqlException ex)
            {
                logger.LogError(ex.Message);
                return(null);
            }

            return(entity);
        }
Esempio n. 26
0
        /// <summary>
        /// returns the ContactPerson identified by id.
        /// </summary>
        /// <remarks>
        /// If the Contact person is already leaded then an identical copy of it will be returned.
        /// </remarks>
        /// <param name="id">The object Value</param>
        /// <returns>The loaded business object</returns>
        /// <exception cref="BusObjDeleteConcurrencyControlException">
        ///  if the object has been deleted already</exception>
        public static ContactPersonCompositeKey GetContactPersonCompositeKey(IPrimaryKey id)
        {
            //ContactPersonCompositeKey myContactPerson =
            //    (ContactPersonCompositeKey) BOLoader.Instance.GetLoadedBusinessObject(id);
            //if (myContactPerson == null)
            //{
            ContactPersonCompositeKey myContactPerson =
                BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObject <ContactPersonCompositeKey>(id);

//            }
            return(myContactPerson);
        }
Esempio n. 27
0
 private DmlfColumnRef[] GetBaseWhereCols()
 {
     if (ResultFields != null)
     {
         return(ResultFields.GetPrimaryKey(DmlfSource.BaseTable).ToArray());
     }
     else
     {
         IPrimaryKey pk = Structure.FindConstraint <IPrimaryKey>();
         return(DmlfColumnRef.BuildFromArray(pk != null ? pk.Columns.GetNames() : Structure.Columns.GetNames(), null));
     }
 }
Esempio n. 28
0
        private void CreateUpdatedContactPersonTestPack()
        {
            ContactPersonCompositeKey myContact = new ContactPersonCompositeKey();

            myContact.SetPropertyValue("DateOfBirth", new DateTime(1969, 01, 29));
            myContact.SetPropertyValue("FirstName", "FirstName");
            myContact.SetPropertyValue("Surname", "Surname");
            myContact.SetPropertyValue("PK1Prop1", Guid.NewGuid());
            myContact.SetPropertyValue("PK1Prop2", Guid.NewGuid());
            myContact.Save();
            updateContactPersonID = myContact.ID;
        }
Esempio n. 29
0
        public static int RegisterTableValue(this object instance, Type ownerType)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            while (Connection.State != ConnectionState.Open)
            {
                Thread.Sleep(100);
            }

            bool isRepo = ownerType != null;

            // Sometimes we could see that a repo has a null ownereType, in this case the FK associated with it will not be saved

            using (var cmd = Connection.CreateCommand())
            {
                string tableName = SqlHelper.GetTableNameFromInstance(instance.GetType(), true);

                string query = $"INSERT INTO {tableName}(id,name,date) VALUES(@id, @name, @date)";

                if (isRepo)
                {
                    var repoData = instance as RepoData;
                    if (ownerType == typeof(OrgData) || ownerType == typeof(UserData))
                    {
                        IPrimaryKey dependant = DefineDependantInstance(repoData, ownerType);

                        if (dependant != null)
                        {
                            cmd.Parameters.AddWithValue("@dep_id", dependant.Id);
                            query = $"INSERT INTO {tableName}(id,{(ownerType == typeof(OrgData) ? "org_id" : "user_id")},name,date) VALUES(@id, @dep_id, @name, @date)";
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }
                }

                cmd.Parameters.AddWithValue("@id", 0);
                cmd.Parameters.AddWithValue("@name", ((dynamic)instance).Name);
                cmd.Parameters.AddWithValue("@date", SqlHelper.GetNow());

                cmd.CommandText = query;
                cmd.CommandType = CommandType.Text;

                cmd.ExecuteNonQuery();
                return((int)cmd.LastInsertedId);
            }
        }
        /// <summary>
        /// Loads a business object of type T, using the Primary key given as the criteria
        /// </summary>
        /// <typeparam name="T">The type of object to load. This must be a class that implements IBusinessObject and has a parameterless constructor</typeparam>
        /// <param name="primaryKey">The primary key to use to load the business object</param>
        /// <returns>The business object that was found. If none was found, null is returned. If more than one is found an <see cref="HabaneroDeveloperException"/> error is throw</returns>
        public T GetBusinessObject <T>(IPrimaryKey primaryKey) where T : class, IBusinessObject, new()
        {
            if (_dataStore.AllObjects.ContainsKey(primaryKey.ObjectID))
            {
                return((T)_dataStore.AllObjects[primaryKey.ObjectID]);
            }

            throw new BusObjDeleteConcurrencyControlException
                      (string.Format
                          ("A Error has occured since the object you are trying to refresh has been deleted by another user."
                          + " There are no records in the database for the Class: {0} identified by {1} \n", typeof(T).Name,
                          primaryKey));
        }
Esempio n. 31
0
        /// <summary>
        /// returns the ContactPerson identified by id.
        /// </summary>
        /// <remarks>
        /// If the Contact person is already leaded then an identical copy of it will be returned.
        /// </remarks>
        /// <param name="id">The object primary Key</param>
        /// <returns>The loaded business object</returns>
        /// <exception cref="BusObjDeleteConcurrencyControlException">
        ///  if the object has been deleted already</exception>
        public static ContactPerson GetContactPerson(IPrimaryKey id)
        {
            //ContactPerson myContactPerson = null;
            //if (BusinessObjectManager.Instance.Contains(id))
            //{
            //    myContactPerson = (ContactPerson) BusinessObjectManager.Instance[id];
            //}

            //if (myContactPerson == null)
            //{
            ContactPerson myContactPerson = BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObject<ContactPerson>(id);
//            }
            return myContactPerson;
        }
        private static void CheckDuplicatePrimaryKey(BusinessObject bo, List<ITransactional> pendingTransactions, IPrimaryKey primaryKey, List<string> errorMessages)
        {
            var primaryKeyCriteria = Criteria.FromPrimaryKey(primaryKey);

            if (bo.ClassDef.HasObjectID) return;
            if (bo.Status.IsNew && primaryKey.HasAutoIncrementingProperty) return;
            var boKey = primaryKey as BOKey;
            if (boKey == null) throw new HabaneroApplicationException(String.Format("The Primary key '{0}' is not a BOKEY", primaryKey));
            if (!boKey.IsDirtyOrNew()) return;
            if (GetDuplicateObjects(bo, pendingTransactions, primaryKeyCriteria).Count > 0)
            {
                var duplicateObjectErrMsg = GetDuplicateObjectErrMsg(primaryKey, GetClassDisplayName(bo));
                if (!errorMessages.Contains(duplicateObjectErrMsg))
                {
                    errorMessages.Add(duplicateObjectErrMsg);
                }
            }
        }
Esempio n. 33
0
 private void CreateUpdatedContactPersonTestPack()
 {
     ContactPersonCompositeKey myContact = new ContactPersonCompositeKey();
     myContact.SetPropertyValue("DateOfBirth", new DateTime(1969, 01, 29));
     myContact.SetPropertyValue("FirstName", "FirstName");
     myContact.SetPropertyValue("Surname", "Surname");
     myContact.SetPropertyValue("PK1Prop1", Guid.NewGuid());
     myContact.SetPropertyValue("PK1Prop2", Guid.NewGuid());
     myContact.Save();
     updateContactPersonID = myContact.ID;
 }
Esempio n. 34
0
 private void CreateUpdatedContactPersonTestPack()
 {
     ContactPerson myContact = new ContactPerson();
     myContact.DateOfBirth = new DateTime(1969, 01, 29);
     myContact.FirstName = "FirstName";
     myContact.Surname = "Surname";
     myContact.Save();
     _updateContactPersonId = myContact.ID;
 }
        /// <summary>
        /// returns the ContactPerson identified by id.
        /// </summary>
        /// <remarks>
        /// If the Contact person is already leaded then an identical copy of it will be returned.
        /// </remarks>
        /// <param name="id">The object Value</param>
        /// <returns>The loaded business object</returns>
        /// <exception cref="BusObjDeleteConcurrencyControlException">
        ///  if the object has been deleted already</exception>
        public static ContactPersonCompositeKey GetContactPersonCompositeKey(IPrimaryKey id)
        {
            //ContactPersonCompositeKey myContactPerson =
            //    (ContactPersonCompositeKey) BOLoader.Instance.GetLoadedBusinessObject(id);
            //if (myContactPerson == null)
            //{
            ContactPersonCompositeKey myContactPerson =
                    BORegistry.DataAccessor.BusinessObjectLoader.GetBusinessObject<ContactPersonCompositeKey>(id);
//            }
            return myContactPerson;
        }