Ejemplo n.º 1
0
        public bool CompareListsById(IList newList, IList oldList)
        {
            if (newList == null || oldList == null)
            {
                if (!((newList == null && oldList == null)))
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            if (!(oldList.Count == newList.Count))
            {
                return(false);
            }
            IObjectManager om  = this.Context.ObjectManager;
            IDomainMap     dm  = this.Context.DomainMap;
            Hashtable      ids = new Hashtable();

            foreach (object value in newList)
            {
                IClassMap classMap = dm.MustGetClassMap(value.GetType());
                string    id       = classMap.GetFullName() + om.GetObjectIdentity(value);
                ids[id] = id;
            }

            foreach (object value in oldList)
            {
                IClassMap classMap = dm.MustGetClassMap(value.GetType());
                string    id       = classMap.GetFullName() + om.GetObjectIdentity(value);
                if (!(ids.ContainsKey(id)))
                {
                    return(false);
                }
            }

            ids = new Hashtable();
            foreach (object value in oldList)
            {
                IClassMap classMap = dm.MustGetClassMap(value.GetType());
                string    id       = classMap.GetFullName() + om.GetObjectIdentity(value);
                ids[id] = id;
            }
            foreach (object value in newList)
            {
                IClassMap classMap = dm.MustGetClassMap(value.GetType());
                string    id       = classMap.GetFullName() + om.GetObjectIdentity(value);
                if (!(ids.ContainsKey(id)))
                {
                    return(false);
                }
            }
            return(true);
        }
        private string BuildObjectIdentity(object obj, IPropertyMap newPropertyMap, object newValue)
        {
            string    id       = "";
            IClassMap classMap = m_ObjectManager.Context.DomainMap.MustGetClassMap(obj.GetType());
            string    sep      = classMap.IdentitySeparator;

            //			bool gotObjectStatus = false;
            //			ObjectStatus objStatus = ObjectStatus.Clean;
            if (sep == "")
            {
                sep = "|";
            }
            object value;

            foreach (IPropertyMap propertyMap in classMap.GetIdentityPropertyMaps())
            {
                if (propertyMap == newPropertyMap)
                {
                    value = newValue;
                    if (propertyMap.ReferenceType != ReferenceType.None)
                    {
                        value = m_ObjectManager.GetObjectIdentity(value);
                    }
                }
                else
                {
                    value = m_ObjectManager.GetPropertyValue(obj, propertyMap.Name);
                    if (value == null || m_ObjectManager.GetNullValueStatus(obj, propertyMap.Name) == true)
                    {
                        if (!(m_hashTempIds.ContainsKey(obj)))
                        {
                            m_hashTempIds[obj] = Guid.NewGuid().ToString();
                        }
                        return((string)m_hashTempIds[obj]);
                    }
                    else if (propertyMap.ReferenceType != ReferenceType.None)
                    {
                        //this ensures that a complete id can be created ahead in case of auto-in
                        //m_ObjectManager.GetPropertyValue(obj, propertyMap.Name);
                        value = m_ObjectManager.GetObjectIdentity(value);
                    }
                }

                id += Convert.ToString(value) + sep;
            }
            if (id.Length > sep.Length)
            {
                id = id.Substring(0, id.Length - sep.Length);
            }
            return(id);
        }
Ejemplo n.º 3
0
        public virtual void AbortInserted()
        {
            IObjectManager om = this.Context.ObjectManager;

            foreach (object obj in m_listInserted)
            {
                IClassMap classMap = this.Context.DomainMap.MustGetClassMap(obj.GetType());
                //we must roll back autoincreasers
                if (classMap.HasAssignedBySource())
                {
                    foreach (IPropertyMap propertyMap in classMap.GetAllPropertyMaps())
                    {
                        if (propertyMap.IsAssignedBySource)
                        {
                            string prevId = om.GetObjectIdentity(obj);
                            om.SetPropertyValue(obj, propertyMap.Name, 0);
                            this.Context.IdentityMap.UpdateIdentity(obj, prevId);
                        }
                    }
                }
                m_listCreated.Add(obj);
                om.SetObjectStatus(obj, ObjectStatus.UpForCreation);
            }
            m_listInserted.Clear();
        }
Ejemplo n.º 4
0
        public void TestRevertTemporaryIdentity()
        {
            DeleteTestCustomer("TESTX");

            string tmpProdId = "";

            using (IContext context = GetContext())
            {
                ITransaction tx = context.BeginTransaction();
                try
                {
                    Product  product  = (Product)context.CreateObject(typeof(Product));
                    Customer customer = (Customer)context.CreateObject("TESTX", typeof(Customer));

                    //customer.CompanyName = "TestCompany";
                    product.ProductName = "TestProduct";

                    context.ValidateBeforeCommit = false;

                    IObjectManager om = context.ObjectManager;

                    tmpProdId = om.GetObjectIdentity(product);

                    Assert.AreEqual(36, tmpProdId.Length);

                    try
                    {
                        context.Commit();

                        throw new Exception("We should not reach this place!");
                        //tx.Commit();
                    }
                    catch (Exception ex2)
                    {
                        Assert.AreEqual(tmpProdId, om.GetObjectIdentity(product));

                        tx.Rollback();
                    }
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    throw ex;
                }
            }
        }
        protected virtual string GetFileNamePerObject(object obj, IClassMap classMap)
        {
            IObjectManager om = this.Context.ObjectManager;

            string directory = GetDirectoryForClass(classMap);

            string fileName = directory + @"\" + classMap.GetFullName() + "." + om.GetObjectIdentity(obj) + ".xml";

            return(fileName);
        }
        public void TestGetAcquiredIdentityEventForDetail()
        {
            DeleteTestCustomer("TESTC");

            string tmpProdId = "";

            using (IContext context = GetContext())
            {
                hashAcquiredIdentities.Clear();
                context.AcquiredIdentity += new AcquiredIdentityEventHandler(Context_CountOnAcquiredIdentity);

                ITransaction tx = context.BeginTransaction();
                try
                {
                    Customer    customer    = (Customer)context.CreateObject("TESTC", typeof(Customer));
                    Order       order       = (Order)context.CreateObject(typeof(Order));
                    Product     product     = (Product)context.CreateObject(typeof(Product));
                    OrderDetail orderDetail = (OrderDetail)context.CreateObject(typeof(OrderDetail));
                    order.Customer      = customer;
                    orderDetail.Order   = order;
                    orderDetail.Product = product;

                    orderDetail.Discount  = 0;
                    orderDetail.Quantity  = 1;
                    orderDetail.UnitPrice = 10;

                    customer.CompanyName = "TestCompany";
                    product.ProductName  = "TestProduct";

                    context.ValidateBeforeCommit = false;

                    IObjectManager om = context.ObjectManager;

                    tmpProdId = om.GetObjectIdentity(product);

                    Assert.AreEqual(36, tmpProdId.Length);

                    Assert.AreEqual(0, hashAcquiredIdentities.Count);

                    context.Commit();

                    Assert.AreEqual(3, hashAcquiredIdentities.Count);
                    Assert.IsTrue(hashAcquiredIdentities.ContainsKey(product));
                    Assert.IsTrue(hashAcquiredIdentities.ContainsKey(order));
                    Assert.IsTrue(hashAcquiredIdentities.ContainsKey(orderDetail));

                    tx.Commit();
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    throw ex;
                }
            }
        }
Ejemplo n.º 7
0
        private object GetInsertedObjectWithTemporaryIdentity(string tempId)
        {
            IObjectManager om = Context.ObjectManager;

            foreach (object obj in listInsert)
            {
                if (om.GetObjectIdentity(obj) == tempId)
                {
                    return(obj);
                }
            }
            return(null);
        }
        protected virtual void SerializeInlineReferenceElement(object obj, XmlNode xmlElement, object value)
        {
            IObjectManager om        = this.Context.ObjectManager;
            IDomainMap     domainMap = this.Context.DomainMap;
            IClassMap      classMap  = domainMap.MustGetClassMap(value.GetType());

            SetAttributeValue(xmlElement, "id", om.GetObjectIdentity(value));
            SetAttributeValue(xmlElement, "class", classMap.Name);

            IPropertyMap parent = classMap.GetDocParentPropertyMap();

            if (parent != null)
            {
                object rootObject = GetRootObject(value, parent);

                if (rootObject == null)
                {
                    throw new NPersistException("Could not find root object!");                     // do not localize
                }
                SetAttributeValue(xmlElement, "root-id", om.GetObjectIdentity(rootObject));
                SetAttributeValue(xmlElement, "root-class", domainMap.MustGetClassMap(rootObject.GetType()).Name);
            }
        }
Ejemplo n.º 9
0
        public void TestGetAcquiredIdentityEvent()
        {
            string tmpProdId = "";

            using (IContext context = GetContext())
            {
                hashAcquiredIdentities.Clear();
                context.AcquiredIdentity += new AcquiredIdentityEventHandler(Context_CountOnAcquiredIdentity);

                ITransaction tx = context.BeginTransaction();
                try
                {
                    Product product = (Product)context.CreateObject(typeof(Product));

                    product.ProductName = "TestProduct";

                    context.ValidateBeforeCommit = false;

                    IObjectManager om = context.ObjectManager;

                    tmpProdId = om.GetObjectIdentity(product);

                    Assert.AreEqual(36, tmpProdId.Length);

                    Assert.AreEqual(0, hashAcquiredIdentities.Count);

                    context.Commit();

                    Assert.AreEqual(1, hashAcquiredIdentities.Count);
                    Assert.IsTrue(hashAcquiredIdentities.ContainsKey(product));

                    context.DeleteObject(product);

                    context.Commit();

                    tx.Commit();
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    throw ex;
                }
            }
        }
        private void MergeSingleRefProperty(IObjectManager om, object obj, IClassMap classMap, IPropertyMap propertyMap, object existing, bool forOrgValue, PropertyStatus propStatus, PropertyStatus extPropStatus, MergeBehaviorType mergeBehavior)
        {
            string extOrgObjId;
            string refObjId;
            object extRefObj;
            object refObj;
            object extOrgObj;
            if (forOrgValue)
            {
                refObj = om.GetOriginalPropertyValue(obj, propertyMap.Name);
                extOrgObj = om.GetOriginalPropertyValue(existing, propertyMap.Name);
            }
            else
            {
                refObj = om.GetPropertyValue(obj, propertyMap.Name);
                extOrgObj = om.GetPropertyValue(existing, propertyMap.Name);
            }
            if (refObj != null && DBNull.Value.Equals(refObj) != true)
            {
                //hmmmm won't this fail if we have two objects of different classes but with the same id?
                //probably the type should be included (and preferably change to KeyStruct comparisons...)
                refObjId = om.GetObjectIdentity(refObj);
                extOrgObjId = "";
                if (extOrgObj != null)
                    extOrgObjId = om.GetObjectIdentity(extOrgObj);

                if (!refObjId.Equals(extOrgObjId))
                {
                    bool keepExisting = KeepExistingValue(refObj, extOrgObj, mergeBehavior, classMap, propertyMap, existing, obj, propStatus, extPropStatus, forOrgValue);
                    if (keepExisting != true)
                    {
                        extRefObj = this.Context.GetObjectById(refObjId, refObj.GetType());

                        SetSingleRefPropetyValue(forOrgValue, om, existing, propertyMap, extRefObj, propStatus);
                    }
                }
            }
            else
            {
                if (extOrgObj != null)
                {
                    bool keepExisting = KeepExistingValue(refObj, extOrgObj, mergeBehavior, classMap, propertyMap, existing, obj, propStatus, extPropStatus, forOrgValue);
                    if (keepExisting)
                    {
                        SetSingleRefPropetyValue(forOrgValue, om, existing, propertyMap, null, propStatus);
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public void TestRevertTemporaryIdentityOnReference()
        {
            DeleteTestCustomer("TESTC");

            string tmpProdId   = "";
            string tmpOrderId  = "";
            string tmpDetailId = "";

            using (IContext context = GetContext())
            {
                ITransaction tx = context.BeginTransaction();
                try
                {
                    Customer    customer    = (Customer)context.CreateObject("TESTC", typeof(Customer));
                    Order       order       = (Order)context.CreateObject(typeof(Order));
                    Product     product     = (Product)context.CreateObject(typeof(Product));
                    OrderDetail orderDetail = (OrderDetail)context.CreateObject(typeof(OrderDetail));
                    order.Customer      = customer;
                    orderDetail.Order   = order;
                    orderDetail.Product = product;

                    orderDetail.Discount  = 0;
                    orderDetail.Quantity  = 1;
                    orderDetail.UnitPrice = 10;

                    customer.CompanyName = "TestCompany";
                    //product.ProductName = "TestProduct";

                    context.ValidateBeforeCommit = false;

                    IObjectManager om = context.ObjectManager;

                    tmpProdId   = om.GetObjectIdentity(product);
                    tmpOrderId  = om.GetObjectIdentity(order);
                    tmpDetailId = om.GetObjectIdentity(orderDetail);

                    Assert.AreEqual(36, tmpProdId.Length);

                    try
                    {
                        context.Commit();

                        throw new Exception("We should not reach this place!");
                        //tx.Commit();
                    }
                    catch (Exception ex2)
                    {
                        Assert.AreEqual(tmpProdId, om.GetObjectIdentity(product));
                        Assert.AreEqual(tmpOrderId, om.GetObjectIdentity(order));
                        Assert.AreEqual(tmpDetailId, om.GetObjectIdentity(orderDetail));

                        tx.Rollback();
                    }
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    throw ex;
                }
            }
        }
		private void LoadProperty(object obj, IPropertyMap propertyMap, IObjectManager om, object source, IPropertyMap sourcePropertyMap, IObjectManager sourceOm)
		{
			if (!Monitor.TryEnter(sourceContext, this.Context.Timeout))
				throw new NPersistTimeoutException("Could not aquire exclusive lock on root context before timeout: " + this.Context.Timeout.ToString() + " ms" );

			try
			{
				bool nullValueStatus;
				object value;
				if (propertyMap.ReferenceType == ReferenceType.None)
				{
					if (!(propertyMap.IsCollection))
					{
						value = sourceOm.GetPropertyValue(source, sourcePropertyMap.Name);
						nullValueStatus = sourceOm.GetNullValueStatus(source, sourcePropertyMap.Name);

						om.SetPropertyValue(obj, propertyMap.Name, value);
						if (nullValueStatus)
						{
							om.SetOriginalPropertyValue(obj, propertyMap.Name, DBNull.Value);								
						}
						else
						{
							om.SetOriginalPropertyValue(obj, propertyMap.Name, value);
						}
						om.SetNullValueStatus(obj, propertyMap.Name, nullValueStatus);								
					}				
					else
					{
						//Using CloneList will work when it is only primitive values 
						//(or immutable objects such as strings and dates) 
						//that can be copied between contexts
						IList list = (IList) sourceOm.GetPropertyValue(source, sourcePropertyMap.Name);
						IList listClone = this.Context.ListManager.CloneList(obj, propertyMap, list);
						IList listCloneOrg = this.Context.ListManager.CloneList(obj, propertyMap, list);
						om.SetPropertyValue(obj, propertyMap.Name, listClone);
						om.SetOriginalPropertyValue(obj, propertyMap.Name, listCloneOrg);
					}
				}									
				else
				{
					if (!(propertyMap.IsCollection))
					{
						object refObject = sourceOm.GetPropertyValue(source, sourcePropertyMap.Name);

						if (refObject == null)
						{
							om.SetPropertyValue(obj, propertyMap.Name, null);
							om.SetOriginalPropertyValue(obj, propertyMap.Name, null);

							om.SetNullValueStatus(obj, propertyMap.Name, true);								
						}
						else
						{
							string identity = sourceOm.GetObjectIdentity(refObject);

							Type refType = ToLeafType(refObject);

							//Impossible to solve for inheritance scenarios when mapping presentation model to domain model!!!!
							//We could try checking which presentation domain map which class map that maps to the 
							//domain class map, but that could be a many-one relationship (many presentation model classes
							//map to the same domain model class!)
							//								IClassMap sourceOrgClassMap = this.sourceContext.DomainMap.GetClassMap(orgObject.GetType() );
							//								IClassMap leafOrgClassMap = this.sourceContext.DomainMap.GetClassMap(sourceOrgClassMap.Name );
							//								IClassMap theClassMap = this.sourceContext.DomainMap.GetClassMap (sourceOrgClassMap.Name );																

							value = this.Context.GetObjectById(identity, refType, true);
							nullValueStatus = sourceOm.GetNullValueStatus(source, sourcePropertyMap.Name);								

							om.SetPropertyValue(obj, propertyMap.Name, value);
							om.SetOriginalPropertyValue(obj, propertyMap.Name, value);

							om.SetNullValueStatus(obj, propertyMap.Name, nullValueStatus);								
						}
					}				
					else
					{
						//Using CloneList will not work when there are reference values (to mutable objects) 
						//that can be copied between contexts
						IList orgList = (IList) sourceOm.GetPropertyValue(source, sourcePropertyMap.Name);
						IList list = (IList) om.GetPropertyValue(obj, sourcePropertyMap.Name);
						
						this.LoadReferenceList(list, orgList);

						//for the org-list we can use ListManager.CloneList and clone the list of leaf objects
						IList listOrg = this.Context.ListManager.CloneList(obj, propertyMap, list);
						om.SetPropertyValue(obj, propertyMap.Name, list);
						om.SetOriginalPropertyValue(obj, propertyMap.Name, listOrg);
							
					}							
				}
			}
			finally
			{
				Monitor.Exit(sourceContext);			
			}	
		}
Ejemplo n.º 13
0
		public virtual void UpdateAutoIncIdProperty(IObjectManager om, object obj, IClassMap classMap, object newId)
		{
			IContext ctx = m_SqlEngineManager.Context;
			string prevId;
			string autoPropName;
			IPropertyMap autoProp;
			object autoID = null;
			prevId = om.GetObjectIdentity(obj);
			autoProp = classMap.GetAutoIncreasingIdentityPropertyMap();
			autoPropName = autoProp.Name;					
			PropertyInfo propInfo = obj.GetType().GetProperty(autoProp.Name);
	
			if (propInfo.PropertyType == typeof(System.Int64))
			{
				autoID = Convert.ToInt64(newId);						
			}
			else if (propInfo.PropertyType == typeof(System.Int16))
			{
				autoID = Convert.ToInt16(newId);						
			}
			else if (propInfo.PropertyType == typeof(System.Double))
			{
				autoID = Convert.ToDouble(newId);						
			}
			else if (propInfo.PropertyType == typeof(System.Decimal))
			{
				autoID = Convert.ToDecimal(newId);						
			}
			else
			{
				autoID = Convert.ToInt32(newId);						
			}					
			om.SetPropertyValue(obj, autoPropName, autoID);
			//om.SetOriginalPropertyValue(obj, autoPropName, autoID);
			om.SetNullValueStatus(obj, autoPropName, false);
			ctx.IdentityMap.UpdateIdentity(obj, prevId);
		}
        public override void InsertObject(object obj, IList stillDirty)
        {
            IList        parameters    = new ArrayList();
            ArrayList    propertyNames = new ArrayList();
            IPropertyMap propertyMap;

            ArrayList             nonPrimaryPropertyMaps = new ArrayList();
            ArrayList             collectionPropertyMaps = new ArrayList();
            ArrayList             sqlStatements          = new ArrayList();
            int                   rowsAffected;
            object                autoID;
            IPropertyMap          autoProp;
            IColumnMap            autoPropCol;
            string                autoPropName;
            string                prevId;
            bool                  originalKeepOpen;
            IContext              ctx = SqlEngineManager.Context;
            ObjectCancelEventArgs e   = new ObjectCancelEventArgs(obj);

            ctx.EventManager.OnInsertingObject(this, e);
            if (e.Cancel)
            {
                return;
            }
            IObjectManager om        = ctx.ObjectManager;
            IListManager   lm        = ctx.ListManager;
            IClassMap      classMap  = ctx.DomainMap.MustGetClassMap(obj.GetType());
            string         sqlSelect = "";
            string         sql;

            if (classMap.HasSingleIdAutoIncreaser())
            {
                sql = GetInsertStatement(obj, propertyNames, stillDirty, nonPrimaryPropertyMaps, collectionPropertyMaps, ref sqlSelect, parameters);
            }
            else
            {
                sql = GetInsertStatement(obj, propertyNames, stillDirty, nonPrimaryPropertyMaps, collectionPropertyMaps, parameters);
            }
            IDataSource ds = ctx.DataSourceManager.GetDataSource(obj);

            if (classMap.HasSingleIdAutoIncreaser())
            {
                originalKeepOpen      = ds.KeepConnectionOpen;
                ds.KeepConnectionOpen = true;
                rowsAffected          = ctx.SqlExecutor.ExecuteNonQuery(sql, ds, parameters);
                if (!(rowsAffected == 1))
                {
                    ds.KeepConnectionOpen = originalKeepOpen;
                    throw new NPersistException("An exception occurred when inserting the row for a new object into the data source. Exactly one row should have been affected by the insert operation. Instead " + rowsAffected + " rows were affected!");                     // do not localize
                }
                object[,] result = (object[, ])ctx.SqlExecutor.ExecuteArray(sqlSelect, ds, parameters);
                if (Util.IsArray(result))
                {
                    prevId       = om.GetObjectIdentity(obj);
                    autoProp     = classMap.GetAutoIncreasingIdentityPropertyMap();
                    autoPropName = autoProp.Name;
                    autoPropCol  = autoProp.GetColumnMap();
                    if (autoPropCol.DataType == DbType.Int64)
                    {
                        autoID = Convert.ToInt64(result[0, 0]);
                    }
                    else if (autoPropCol.DataType == DbType.Int16)
                    {
                        autoID = Convert.ToInt16(result[0, 0]);
                    }
                    else
                    {
                        autoID = Convert.ToInt32(result[0, 0]);
                    }
                    om.SetPropertyValue(obj, autoPropName, autoID);
                    //om.SetOriginalPropertyValue(obj, autoPropName, autoID);
                    om.SetNullValueStatus(obj, autoPropName, false);
                    ctx.IdentityMap.UpdateIdentity(obj, prevId);
                }
                else
                {
                    ds.KeepConnectionOpen = originalKeepOpen;
                    throw new FailedFetchingDbGeneratedValueException("Could not find auto-increasing ID for new object!");                     // do not localize
                }
                ds.KeepConnectionOpen = originalKeepOpen;
            }
            else
            {
                rowsAffected = ctx.SqlExecutor.ExecuteNonQuery(sql, ds, parameters);
                if (!(rowsAffected == 1))
                {
                    throw new RowNotInsertedException("A new row was not inserted in the data source for a new object.");                     // do not localize
                }
            }
//			foreach (string propName in propertyNames)
//			{
//				om.SetOriginalPropertyValue(obj, propName, om.GetPropertyValue(obj, propName));
//			}
            InsertNonPrimaryProperties(obj, nonPrimaryPropertyMaps, stillDirty);
            foreach (IPropertyMap iPpropertyMap in collectionPropertyMaps)
            {
                propertyMap = iPpropertyMap;
                sqlStatements.Clear();
                GetInsertCollectionPropertyStatements(obj, propertyMap, sqlStatements, stillDirty);
                ds = ctx.DataSourceManager.GetDataSource(obj, propertyMap.Name);
                foreach (SqlStatementAndDbParameters sqlStatementAndDbParameters in sqlStatements)
                {
                    sql          = sqlStatementAndDbParameters.SqlStatement;
                    rowsAffected = ctx.SqlExecutor.ExecuteNonQuery(sql, ds, sqlStatementAndDbParameters.DbParameters);
                    if (!(rowsAffected == 1))
                    {
                        throw new RowNotInsertedException("A new row was not inserted in the data source for a collection property of a new object.");                         // do not localize
                    }
                }
            }
            ctx.InverseManager.NotifyCreate(obj);
            ObjectEventArgs e2 = new ObjectEventArgs(obj);

            ctx.EventManager.OnInsertedObject(this, e2);
        }
        private void LoadReferenceList(IList list, IList orgList, IObjectManager om, object obj, IPropertyMap propertyMap)
        {
            IList objectsToRemove = new ArrayList();
            IList objectsToAdd    = new ArrayList();

            foreach (object itemOrgObj in orgList)
            {
                string itemOrgObjId = om.GetObjectIdentity(itemOrgObj);
                bool   found        = false;
                foreach (object itemObj in list)
                {
                    string itemObjId = om.GetObjectIdentity(itemObj);
                    if (itemObjId == itemOrgObjId)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    objectsToRemove.Add(itemOrgObj);
                }
            }
            foreach (object itemObj in list)
            {
                string itemObjId = om.GetObjectIdentity(itemObj);
                bool   found     = false;
                foreach (object itemOrgObj in orgList)
                {
                    string itemOrgObjId = om.GetObjectIdentity(itemOrgObj);
                    if (itemObjId == itemOrgObjId)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    object itemOrgObj = this.Context.GetObjectById(itemObjId, itemObj.GetType(), true);
                    objectsToAdd.Add(itemOrgObj);
                }
            }

            if (objectsToRemove.Count > 0 || objectsToAdd.Count > 0)
            {
                bool stackMute           = false;
                IInterceptableList mList = orgList as IInterceptableList;
                if (mList != null)
                {
                    stackMute        = mList.MuteNotify;
                    mList.MuteNotify = true;
                }
                foreach (object itemOrgObj in objectsToRemove)
                {
                    orgList.Remove(itemOrgObj);
                }
                foreach (object itemOrgObj in objectsToAdd)
                {
                    orgList.Add(itemOrgObj);
                }

                if (mList != null)
                {
                    mList.MuteNotify = stackMute;
                }
            }

            bool iStackMute          = false;
            IInterceptableList iList = orgList as IInterceptableList;

            if (iList != null)
            {
                iStackMute       = iList.MuteNotify;
                iList.MuteNotify = true;
            }

            IList listClone = new ArrayList(orgList);

            if (iList != null)
            {
                iList.MuteNotify = iStackMute;
            }

            om.SetOriginalPropertyValue(obj, propertyMap.Name, listClone);
        }
Ejemplo n.º 16
0
		private void MergeSingleRefProperty(IObjectManager om, object obj, IClassMap classMap, IPropertyMap propertyMap, object existing, bool forOrgValue, PropertyStatus propStatus, PropertyStatus extPropStatus, MergeBehaviorType mergeBehavior)
		{
			string extOrgObjId;
			string refObjId;
			object extRefObj;
			object refObj;
			object extOrgObj;
			if (forOrgValue)
			{
				refObj = om.GetOriginalPropertyValue(obj, propertyMap.Name);
				extOrgObj = om.GetOriginalPropertyValue(existing, propertyMap.Name);				
			}
			else
			{
				refObj = om.GetPropertyValue(obj, propertyMap.Name);
				extOrgObj = om.GetPropertyValue(existing, propertyMap.Name);			
			}	
			if (refObj != null && DBNull.Value.Equals(refObj) != true)
			{
				refObjId = om.GetObjectIdentity(refObj);
				extOrgObjId = "";
				if (extOrgObj != null)
					extOrgObjId = om.GetObjectIdentity(extOrgObj);

				if (!refObjId.Equals(extOrgObjId))
				{
					bool keepExisting = KeepExistingValue(refObj, extOrgObj, mergeBehavior, classMap, propertyMap, existing, obj, propStatus, extPropStatus, forOrgValue);
					if (keepExisting != true)
					{
						extRefObj = this.Context.GetObjectById(refObjId, refObj.GetType());

						SetSingleRefPropetyValue(forOrgValue, om, existing, propertyMap, extRefObj, propStatus);
					}
				}
			}
			else
			{
				if (extOrgObj != null)
				{
					bool keepExisting = KeepExistingValue(refObj, extOrgObj, mergeBehavior, classMap, propertyMap, existing, obj, propStatus, extPropStatus, forOrgValue);
					if (keepExisting)
					{
						SetSingleRefPropetyValue(forOrgValue, om, existing, propertyMap, null, propStatus);
					}
				}
			}
		}
Ejemplo n.º 17
0
        //[DebuggerStepThrough()]
        protected virtual void DoNotifyPropertySet(object obj, string propertyName, ref object value, object oldValue, bool hasOldValue, ref bool cancel)
        {
            IContext                ctx = this.Context;
            IObjectManager          om  = ctx.ObjectManager;
            IPersistenceEngine      pe  = ctx.PersistenceEngine;
            PropertyCancelEventArgs e;

            if (hasOldValue)
            {
                e = new PropertyCancelEventArgs(obj, propertyName, value, oldValue, this.Context.ObjectManager.GetNullValueStatus(obj, propertyName));
            }
            else
            {
                e = new PropertyCancelEventArgs(obj, propertyName, value, this.Context.ObjectManager.GetPropertyValue(obj, propertyName), this.Context.ObjectManager.GetNullValueStatus(obj, propertyName));
            }
            this.Context.EventManager.OnWritingProperty(this, e);
            if (e.Cancel)
            {
                cancel = true;
                return;
            }
            value = e.NewValue;
            IClassMap    classMap = ctx.DomainMap.MustGetClassMap(obj.GetType());
            IPropertyMap propertyMap;
            string       prevId;
            string       newId;

            propertyMap = classMap.MustGetPropertyMap(propertyName);

            if (propertyMap.ReferenceType != ReferenceType.None && value != null)
            {
                if (propertyMap.ReferenceType == ReferenceType.OneToMany || propertyMap.ReferenceType == ReferenceType.OneToOne)
                {
                    //parent object
                    IInterceptable ivalue = value as IInterceptable;
                    if (ivalue == null)
                    {
                        throw new NPersistException(string.Format("Object is not a NPersist managed object, do not use 'new' on Entities. (Property='{0}', Owner={1})", propertyName, obj));
                    }
                    else
                    {
                        if (ivalue.GetInterceptor().Context != this.Context)
                        {
                            throw new NPersistException(string.Format("Object does not belong to the same context object as the property owner. (Property='{0}', Owner={1})", propertyName, obj));
                        }
                        ObjectStatus valueObjectStatus = om.GetObjectStatus(value);
                        if (valueObjectStatus == ObjectStatus.UpForDeletion || valueObjectStatus == ObjectStatus.Deleted)
                        {
                            throw new DeletedObjectException(string.Format("Object has been deleted. (Object={0})", value), value);
                        }
                    }
                }
                else if (propertyMap.ReferenceType == ReferenceType.ManyToOne || propertyMap.ReferenceType == ReferenceType.ManyToMany)
                {
                    IInterceptableList ivalue = value as IInterceptableList;
                    if (ivalue == null)
                    {
                        throw new NPersistException(string.Format("List is not a NPersist managed list, do not use 'new' to initialize lists, NPersist does this for you. (Property='{0}', Owner={1})", propertyName, obj));
                    }
                    else if (ivalue.Interceptable.GetInterceptor().Context != this.Context)
                    {
                        throw new NPersistException(string.Format("List does not belong to the same context object as the property owner. (Property='{0}', Owner={1})", propertyName, obj));
                    }
                }
            }

            if (propertyMap.IsReadOnly)
            {
                //Let read-only inverse properties through
                if (!(propertyMap.ReferenceType != ReferenceType.None && propertyMap.Inverse.Length > 0 && propertyMap.NoInverseManagement == false))
                {
                    //Special - if someone forgot to make their ManyOne read-only,
                    //why bug them about it? (so don't add an "else" with an exception...)
                    if (propertyMap.ReferenceType != ReferenceType.ManyToOne)
                    {
                        throw new ReadOnlyException("Property '" + classMap.Name + "." + propertyName + "' is read-only!");                         // do not localize
                    }
                }
            }
            PropertyStatus propStatus        = PropertyStatus.Clean;
            ObjectStatus   objStatus         = om.GetObjectStatus(obj);
            bool           hasPropertyStatus = false;

            if (objStatus == ObjectStatus.Deleted)
            {
                throw new DeletedObjectException("The object has been deleted!", obj, propertyName);                 // do not localize
            }
            else if (objStatus == ObjectStatus.UpForDeletion)
            {
                throw new DeletedObjectException("The object has been registered as up for deletion!", obj, propertyName);                 // do not localize
            }

            this.Context.ObjectCloner.EnsureIsClonedIfEditing(obj);

            if (objStatus == ObjectStatus.UpForCreation)
            {
            }
            else if (objStatus == ObjectStatus.Clean)
            {
                propStatus = om.GetPropertyStatus(obj, propertyName);
                if (propStatus == PropertyStatus.NotLoaded)
                {
                    pe.LoadProperty(obj, propertyName);
                }
                if (!(hasOldValue))
                {
                    if (!(om.ComparePropertyValues(obj, propertyName, value, om.GetPropertyValue(obj, propertyName))))
                    {
                        this.Context.UnitOfWork.RegisterDirty(obj);
                    }
                }
            }
            else if (objStatus == ObjectStatus.NotLoaded)
            {
                propertyMap = this.Context.DomainMap.MustGetClassMap(obj.GetType()).MustGetPropertyMap(propertyName);
                if (!(propertyMap.IsIdentity))
                {
                    propStatus        = this.Context.ObjectManager.GetPropertyStatus(obj, propertyName);
                    hasPropertyStatus = true;
                    //it would be sweet to be able to determine beforehand if this property would be part of the span
                    //that is loaded with LoadObject and only call LoadObject if that is the case....
                    if (propStatus == PropertyStatus.NotLoaded)
                    {
                        hasPropertyStatus = false;
                        //this.Context.PersistenceEngine.LoadObject(ref obj);
                        this.Context.IdentityMap.LoadObject(ref obj, true);
                        if (obj == null)
                        {
                            throw new ObjectNotFoundException("Object not found!");                             // do not localize
                        }
                    }
                    if (!hasPropertyStatus)
                    {
                        propStatus = om.GetPropertyStatus(obj, propertyName);
                    }

                    if (propStatus == PropertyStatus.NotLoaded)
                    {
                        pe.LoadProperty(obj, propertyName);
                    }
                }

                if (!(hasOldValue))
                {
                    if (!(om.ComparePropertyValues(obj, propertyName, value, om.GetPropertyValue(obj, propertyName))))
                    {
                        this.Context.UnitOfWork.RegisterDirty(obj);
                    }
                }
            }
            else if (objStatus == ObjectStatus.Dirty)
            {
                propStatus = om.GetPropertyStatus(obj, propertyName);
                if (propStatus == PropertyStatus.NotLoaded)
                {
                    pe.LoadProperty(obj, propertyName);
                }
            }
            if (propertyMap.IsIdentity)
            {
                prevId = om.GetObjectIdentity(obj);
                newId  = om.GetObjectIdentity(obj, propertyMap, value);
                if (prevId != newId)
                {
                    ctx.IdentityMap.UpdateIdentity(obj, prevId, newId);
                }
            }
            om.SetNullValueStatus(obj, propertyName, false);
            om.SetUpdatedStatus(obj, propertyName, true);
            if (hasOldValue)
            {
                ctx.InverseManager.NotifyPropertySet(obj, propertyName, value, oldValue);
                ctx.UnitOfWork.RegisterDirty(obj);
            }
            else
            {
                ctx.InverseManager.NotifyPropertySet(obj, propertyName, value);
            }
        }
        protected virtual void SerializeClone(object obj, ReadOnlyClone clone, string id, string key)
        {
            IObjectManager   om       = this.Context.ObjectManager;
            IDomainMap       dm       = this.Context.DomainMap;
            IAssemblyManager am       = this.Context.AssemblyManager;
            IClassMap        classMap = dm.MustGetClassMap(obj.GetType());
            IListManager     lm       = this.Context.ListManager;

            clone.Identity = id;
            clone.Key      = key;
            clone.Type     = classMap.GetFullName();
            foreach (IPropertyMap propertyMap in classMap.GetAllPropertyMaps())
            {
                if (propertyMap.ReferenceType == ReferenceType.None)
                {
                    if (propertyMap.IsCollection)
                    {
                        IList values = new ArrayList();
                        IList list   = (IList)om.GetPropertyValue(obj, propertyMap.Name);

                        foreach (object value in list)
                        {
                            values.Add(value);
                        }

                        clone.PropertyValues[propertyMap.Name]    = values;
                        clone.NullValueStatuses[propertyMap.Name] = false;
                    }
                    else
                    {
                        object value = om.GetPropertyValue(obj, propertyMap.Name);
                        clone.PropertyValues[propertyMap.Name]    = value;
                        clone.NullValueStatuses[propertyMap.Name] = om.GetNullValueStatus(obj, propertyMap.Name);
                    }
                }
                else
                {
                    IClassMap refClassMap = propertyMap.MustGetReferencedClassMap();
                    if (refClassMap.IsReadOnly)
                    {
                        if (propertyMap.IsCollection)
                        {
                            IList values = new ArrayList();
                            IList list   = (IList)om.GetPropertyValue(obj, propertyMap.Name);

                            foreach (object value in list)
                            {
                                if (value != null)
                                {
                                    refClassMap = dm.MustGetClassMap(value.GetType());
                                    string refIdentity        = om.GetObjectIdentity(value);
                                    SerializedReference refId = new SerializedReference(refIdentity, refClassMap.GetFullName());
                                    values.Add(refId);
                                }
                            }
                            clone.PropertyValues[propertyMap.Name]    = values;
                            clone.NullValueStatuses[propertyMap.Name] = false;
                        }
                        else
                        {
                            object value = om.GetPropertyValue(obj, propertyMap.Name);
                            if (value != null)
                            {
                                refClassMap = dm.MustGetClassMap(value.GetType());
                                string refIdentity        = om.GetObjectIdentity(value);
                                SerializedReference refId = new SerializedReference(refIdentity, refClassMap.GetFullName());
                                value = refId;
                            }
                            clone.PropertyValues[propertyMap.Name]    = value;
                            clone.NullValueStatuses[propertyMap.Name] = om.GetNullValueStatus(obj, propertyMap.Name);
                        }
                    }
                }
            }
        }
        private void LoadReferenceList(IList list, IList orgList, IObjectManager om, object obj, IPropertyMap propertyMap)
        {
            IList objectsToRemove = new ArrayList();
            IList objectsToAdd = new ArrayList();
            foreach (object itemOrgObj in orgList)
            {
                string itemOrgObjId = om.GetObjectIdentity(itemOrgObj);
                bool found = false;
                foreach (object itemObj in list)
                {
                    string itemObjId = om.GetObjectIdentity(itemObj);
                    if (itemObjId == itemOrgObjId)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                    objectsToRemove.Add(itemOrgObj);
            }
            foreach (object itemObj in list)
            {
                string itemObjId = om.GetObjectIdentity(itemObj);
                bool found = false;
                foreach (object itemOrgObj in orgList)
                {
                    string itemOrgObjId = om.GetObjectIdentity(itemOrgObj);
                    if (itemObjId == itemOrgObjId)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    object itemOrgObj = this.Context.GetObjectById(itemObjId, itemObj.GetType(), true);
                    objectsToAdd.Add(itemOrgObj);
                }
            }

            if (objectsToRemove.Count > 0 || objectsToAdd.Count > 0)
            {
                bool stackMute = false;
                IInterceptableList mList = orgList as IInterceptableList;
                if (mList != null)
                {
                    stackMute = mList.MuteNotify;
                    mList.MuteNotify = true;
                }
                foreach (object itemOrgObj in objectsToRemove)
                    orgList.Remove(itemOrgObj);
                foreach (object itemOrgObj in objectsToAdd)
                    orgList.Add(itemOrgObj);

                if (mList != null) { mList.MuteNotify = stackMute; }
            }

            bool iStackMute = false;
            IInterceptableList iList = orgList as IInterceptableList;
            if (iList != null)
            {
                iStackMute = iList.MuteNotify;
                iList.MuteNotify = true;
            }

            IList listClone = new ArrayList( orgList);

            if (iList != null) { iList.MuteNotify = iStackMute; }

            om.SetOriginalPropertyValue(obj, propertyMap.Name, listClone);
        }
Ejemplo n.º 20
0
		private void MergeReferenceLists(IList list, IList orgList, IObjectManager om, object obj, MergeBehaviorType mergeBehavior, IClassMap classMap, IPropertyMap propertyMap, object existing, PropertyStatus propStatus, PropertyStatus extPropStatus, bool forOrgValue)
		{
			IList objectsToRemove = new ArrayList(); 
			IList objectsToAdd = new ArrayList();
			IUnitOfWork uow = this.Context.UnitOfWork;
			foreach (object itemOrgObj in orgList)
			{
				string itemOrgObjId = om.GetObjectIdentity(itemOrgObj);
				bool found = false;
				foreach (object itemObj in list)
				{
					string itemObjId = om.GetObjectIdentity(itemObj);
					if (itemObjId == itemOrgObjId)
					{
						found = true;
						break;
					}								
				}
				if (!found)
					objectsToRemove.Add(itemOrgObj);
			}
			foreach (object itemObj in list)
			{
				string itemObjId = om.GetObjectIdentity(itemObj);
				bool found = false;
				foreach (object itemOrgObj in orgList)
				{
					string itemOrgObjId = om.GetObjectIdentity(itemOrgObj);
					if (itemObjId == itemOrgObjId)
					{
						found = true;
						break;
					}								
				}
				if (!found)
				{
					object itemOrgObj = this.Context.GetObjectById(itemObjId, obj.GetType());
					objectsToAdd.Add(itemOrgObj);
				}
			}
	
			if (objectsToRemove.Count > 0 || objectsToAdd.Count > 0)
			{
				bool keepExisting = KeepExistingValue(list, orgList, mergeBehavior, classMap, propertyMap, existing, obj, propStatus, extPropStatus, forOrgValue);
				if (!keepExisting)
				{
					bool stackMute = false;
					IInterceptableList mList = orgList as IInterceptableList;					
					if (mList != null)
					{
						stackMute = mList.MuteNotify;
						mList.MuteNotify = true;
					}
					foreach (object itemOrgObj in objectsToRemove)
						orgList.Remove(itemOrgObj);
					foreach (object itemOrgObj in objectsToAdd)
						orgList.Add(itemOrgObj);	

					if (mList != null) { mList.MuteNotify = stackMute; }
					
					if (propStatus == PropertyStatus.Dirty)
					{
						uow.RegisterDirty(existing);					
						om.SetUpdatedStatus(existing, propertyMap.Name, true);						
					}
				}								
			}
		}
        public void CheckPartiallyLoadedList(string propertyName, ITransaction transaction)
        {
            IList partialList = GetPartiallyLoadedList(propertyName, transaction);
            int   count       = GetCount(propertyName, transaction);

            if (count == partialList.Count)
            {
                IContext       context = ((IInterceptable)this.target).GetInterceptor().Context;
                IObjectManager om      = context.ObjectManager;

                IInterceptableList iList = om.GetPropertyValue(target, propertyName) as IInterceptableList;
                if (iList == null)
                {
                    throw new NPersistException(string.Format("Object of type {0} and identity {1} does not have an interceptable list injected in property {2}", target.GetType(), om.GetObjectIdentity(target), propertyName));
                }

                bool stackMute = iList.MuteNotify;
                iList.MuteNotify = true;

                if (iList.Count < 1)
                {
                    IList orgList = new ArrayList();
                    foreach (object refObj in partialList)
                    {
                        iList.Add(refObj);
                        orgList.Add(refObj);
                    }
                    iList.MuteNotify = stackMute;
                    om.SetPropertyValue(target, propertyName, iList);
                    om.SetOriginalPropertyValue(target, propertyName, orgList);
                    om.SetNullValueStatus(target, propertyName, false);
                    om.SetUpdatedStatus(target, propertyName, false);

                    context.InverseManager.NotifyPropertyGet(target, propertyName);
                }
                else
                {
                    iList.MuteNotify = stackMute;
                }
            }
        }