public ReplicateEvent(string entityName, object entity, ReplicationMode replicationMode, IEventSource source)
			: base(source)
		{
			if (entity == null)
				throw new ArgumentNullException("entity", "attempt to create replication strategy with null entity");

			if (replicationMode == null)
				throw new ArgumentNullException("replicationMode",
				                                "attempt to create replication strategy with null replication mode");

			this.entityName = entityName;
			this.entity = entity;
			this.replicationMode = replicationMode;
		}
Example #2
0
 /// <summary>
 /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
 /// /> and <see cref="ignoreCase" />
 /// </summary>
 /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
 /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
 /// <param name="formatProvider">not used by this TypeConverter.</param>
 /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
 /// <returns>
 /// an instance of <see cref="ReplicationMode" />, or <c>null</c> if there is no suitable conversion.
 /// </returns>
 public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ReplicationMode.CreateFrom(sourceValue);
		public void Replicate( object obj, ReplicationMode replicationMode )
		{
			CheckIsOpen();

			if( obj == null )
			{
				throw new ArgumentNullException( "obj", "attempt to replicate null" );
			}

			if( ReassociateIfUninitializedProxy( obj ) )
			{
				return;
			}

			object theObj = UnproxyAndReassociate( obj );

			if( IsEntryFor( theObj ) )
			{
				return;
			}

			IClassPersister persister = GetPersister( theObj );
			if( persister.IsUnsaved( theObj ) )
			{
				//TODO: generate a new id value for brand new objects
				throw new TransientObjectException( "unsaved object passed to Replicate()" );
			}

			object id = persister.GetIdentifier( theObj );
			object oldVersion;
			if( replicationMode == ReplicationMode.Exception )
			{
				//always do an INSERT, and let it fail by constraint violation
				oldVersion = null;
			}
			else
			{
				//what is the version on the database?
				oldVersion = persister.GetCurrentVersion( id, this );
			}

			if( oldVersion != null )
			{
				// existing row - do an update if appropriate
				if( replicationMode.ShouldOverwriteCurrentVersion( theObj, oldVersion, persister.GetVersion( obj ), persister.VersionType ) )
				{
					//will result in a SQL UPDATE:
					DoReplicate( theObj, id, oldVersion, replicationMode, persister );
				}
				//else do nothing (don't even reassociate object!)
				//TODO: would it be better to do a refresh from db?
			}
			else
			{
				// no existing row - do an insert
				if( log.IsDebugEnabled )
				{
					log.Debug( "replicating " + MessageHelper.InfoString( persister, id ) );
				}
				bool regenerate = persister.IsIdentifierAssignedByInsert; // prefer re-generation of identity!
				DoSave(
					theObj,
					regenerate ? null : new Key( id, persister ),
					persister,
					true, //!persister.isUnsaved(object), //TODO: Do an ordinary save in the case of an "unsaved" object
					// TODO: currently ignores interceptor definition of isUnsaved()
					regenerate,
					Cascades.CascadingAction.ActionReplicate, // not quite an ordinary save(), since we cascade back to replicate()
					replicationMode
					);
			}
		}
		private void PerformReplication(object entity, object id, object version, IEntityPersister persister, ReplicationMode replicationMode, IEventSource source)
		{
			if (log.IsDebugEnabled)
			{
				log.Debug("replicating changes to " + MessageHelper.InfoString(persister, id, source.Factory));
			}

			new OnReplicateVisitor(source, id, entity, true).Process(entity, persister);

			source.PersistenceContext.AddEntity(
				entity, 
				persister.IsMutable ? Status.Loaded : Status.ReadOnly,
				null,
				source.GenerateEntityKey(id, persister),
				version, 
				LockMode.None, 
				true, 
				persister,
				true, 
				false);

			CascadeAfterReplicate(entity, persister, replicationMode, source);
		}
		public ReplicateEvent(object entity, ReplicationMode replicationMode, IEventSource source)
			: this(null, entity, replicationMode, source)
		{}
Example #6
0
 public void Replicate(string entityName, object obj, ReplicationMode replicationMode)
 {
     _session.Replicate(entityName, obj, replicationMode);
 }
Example #7
0
 /// <summary>
 /// Persist the state of the given detached instance, reusing the current
 ///             identifier value.  This operation cascades to associated instances if
 ///             the association is mapped with <tt>cascade="replicate"</tt>.
 /// </summary>
 /// <param name="entityName"/><param name="obj">a detached instance of a persistent class </param><param name="replicationMode"/>
 public void Replicate(string entityName, object obj, ReplicationMode replicationMode)
 {
     throw new NotImplementedException();
 }
Example #8
0
 /// <summary>
 /// From NHibernate documentation:
 /// Persist all reachable transient objects, reusing the current identifier
 /// values. Note that this will not trigger the Interceptor of the Session.
 /// </summary>
 /// <param name="instance">The instance.</param>
 /// <param name="replicationMode">The replication mode.</param>
 public static void Replicate <T>(object instance, ReplicationMode replicationMode) where T : class
 {
     AR.CurrentScope().Replicate <T>(instance, replicationMode);
 }
Example #9
0
 private async Task CascadeAfterReplicateAsync(object entity, IEntityPersister persister, ReplicationMode replicationMode, IEventSource source, CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     source.PersistenceContext.IncrementCascadeLevel();
     try
     {
         await(new Cascade(CascadingAction.Replicate, CascadePoint.AfterUpdate, source).CascadeOnAsync(persister, entity, replicationMode, cancellationToken)).ConfigureAwait(false);
     }
     finally
     {
         source.PersistenceContext.DecrementCascadeLevel();
     }
 }
Example #10
0
        private async Task PerformReplicationAsync(object entity, object id, object version, IEntityPersister persister, ReplicationMode replicationMode, IEventSource source, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (log.IsDebugEnabled)
            {
                log.Debug("replicating changes to " + MessageHelper.InfoString(persister, id, source.Factory));
            }

            await(new OnReplicateVisitor(source, id, entity, true).ProcessAsync(entity, persister, cancellationToken)).ConfigureAwait(false);

            source.PersistenceContext.AddEntity(
                entity,
                persister.IsMutable ? Status.Loaded : Status.ReadOnly,
                null,
                source.GenerateEntityKey(id, persister),
                version,
                LockMode.None,
                true,
                persister,
                true,
                false);

            await(CascadeAfterReplicateAsync(entity, persister, replicationMode, source, cancellationToken)).ConfigureAwait(false);
        }
Example #11
0
 public Task ReplicateAsync(string entityName, object obj, ReplicationMode replicationMode,
                            CancellationToken cancellationToken = new CancellationToken())
 {
     return(_session.ReplicateAsync(entityName, obj, replicationMode, cancellationToken));
 }
 public void Replicate(object obj, ReplicationMode replicationMode)
 {
     throw new NotWrappedException();
 }
    void EditState(StateDefinition def)
    {
        DEditorGUI.WithLabel("Inheritance", () =>
        {
            def.IsAbstract = DEditorGUI.ToggleDropdown("Is Abstract", "Is Concrete", def.IsAbstract);
            def.ParentGuid = DEditorGUI.AssetPopup("Parent: ", Project.States.Cast <AssetDefinition>(), def.ParentGuid, Project.GetInheritanceTree(def));
        });

        EditorGUI.BeginDisabledGroup(def.IsAbstract);

        DEditorGUI.WithLabel("Bandwidth", () =>
        {
            GUILayout.BeginHorizontal();
            def.PacketMaxBits       = Mathf.Clamp(DEditorGUI.IntFieldOverlay(def.PacketMaxBits, "Bits/Packet"), 128, 4096);
            def.PacketMaxProperties = Mathf.Clamp(DEditorGUI.IntFieldOverlay(def.PacketMaxProperties, "Properties/Packet"), 1, 255);
            GUILayout.EndHorizontal();
        });

        EditorGUI.EndDisabledGroup();

        DEditorGUI.WithLabel("Import Mecanim Modes", () => {
            replicationMode  = (ReplicationMode)EditorGUILayout.EnumPopup("Replication Mode", replicationMode);
            mecanimDirection = (MecanimDirection)EditorGUILayout.EnumPopup("Mecanim Mode", mecanimDirection);
        });

        DEditorGUI.WithLabel("Import Mecanim Parameters", () =>
        {
            mecanimController = EditorGUILayout.ObjectField(mecanimController, typeof(RuntimeAnimatorController), true) as RuntimeAnimatorController;

            if (mecanimController)
            {
                if (GUILayout.Button("Import", EditorStyles.miniButton))
                {
                    try
                    {
                        AC ac = (AC)mecanimController;

#if UNITY_5
                        for (int i = 0; i < ac.parameters.Length; ++i)
                        {
                            ImportMecanimParameter(def, ac.parameters[i]);
                        }
#else
                        for (int i = 0; i < ac.parameterCount; ++i)
                        {
                            ImportMecanimParameter(def, ac.GetParameter(i));
                        }

                        for (int i = 0; i < ac.layerCount; ++i)
                        {
                            ImportMecanimLayer(def, ac, i);
                        }
#endif

                        Save();
                    }
                    finally
                    {
                        mecanimController = null;
                    }
                }
            }
        });

        var groups =
            def.Properties
            .Where(x => x.PropertyType.MecanimApplicable)
            .Where(x => x.StateAssetSettings.MecanimMode != MecanimMode.Disabled)
            .GroupBy(x => x.StateAssetSettings.MecanimDirection);

        if (groups.Count() == 1)
        {
            var currentDirection = groups.First().Key;

            DEditorGUI.WithLabel("Mecanim (State Wide)", () =>
            {
                var selectedDirection = (MecanimDirection)EditorGUILayout.EnumPopup(currentDirection);

                if (currentDirection != selectedDirection)
                {
                    foreach (var property in def.Properties.Where(x => x.PropertyType.MecanimApplicable))
                    {
                        property.StateAssetSettings.MecanimDirection = selectedDirection;
                    }

                    Save();
                }
            });
        }
        else if (groups.Count() > 1)
        {
            DEditorGUI.WithLabel("Mecanim (State Wide)", () =>
            {
                string[] options = new string[] { "Using Animator Methods", "Using Bolt Properties", "Mixed (WARNING)" };

                int index = EditorGUILayout.Popup(2, options);

                if (index != 2)
                {
                    foreach (var property in def.Properties.Where(x => x.PropertyType.MecanimApplicable))
                    {
                        property.StateAssetSettings.MecanimDirection = (MecanimDirection)index;
                    }

                    Save();
                }
            });
        }

        EditPropertyList(def, def.Properties);

        Guid guid = def.ParentGuid;

        while (guid != Guid.Empty)
        {
            var parent = Project.FindState(guid);
            GUILayout.Label(string.Format("Inherited from {0}", parent.Name), DEditorGUI.MiniLabelButtonStyle);

            EditorGUI.BeginDisabledGroup(true);
            EditPropertyList(parent, parent.Properties);
            EditorGUI.EndDisabledGroup();

            guid = parent.ParentGuid;
        }
    }
Example #14
0
 public void Replicate(object obj, ReplicationMode replicationMode)
 {
     _backingSession.Replicate(obj, replicationMode);
 }
Example #15
0
 public virtual void Replicate(object obj, ReplicationMode replicationMode)
 {
     throw new NotSupportedException();
 }
Example #16
0
 public virtual void Replicate(string entityName, object obj, ReplicationMode replicationMode)
 {
     throw new NotSupportedException();
 }
Example #17
0
 public ReplicateEvent(object entity, ReplicationMode replicationMode, IEventSource source)
     : this(null, entity, replicationMode, source)
 {
 }
Example #18
0
 /// <summary>
 /// Persist all reachable transient objects, reusing the current identifier
 ///             values. Note that this will not trigger the Interceptor of the Session.
 /// </summary>
 /// <param name="obj">a detached instance of a persistent class</param><param name="replicationMode"/>
 public void Replicate(object obj, ReplicationMode replicationMode)
 {
     throw new NotImplementedException();
 }
        public Partitioner(CancellationToken token, CloudIndex idx, INameService namesvc, ITaskQueue taskqueue, ReplicationMode replicationMode, int minimalRedundancy)
        {
            Log.WriteLine($"{nameof(Partitioner)}: Initializing. ReplicationMode={replicationMode}, MinimumReplica={minimalRedundancy}");

            m_cancel          = token;
            m_idx             = idx;
            m_namesvc         = namesvc;
            m_taskqueue       = taskqueue;
            m_repmode         = replicationMode;
            m_minreplicas     = minimalRedundancy;
            m_partitionerproc = Utils.Daemon(m_cancel, "PartitionerProc", 10000, PartitionerProc);
        }
Example #20
0
 public void Replicate(object obj, ReplicationMode replicationMode)
 {
     _session.Replicate(obj, replicationMode);
 }
Example #21
0
        internal static DistributedAvailabilityGroupData DeserializeDistributedAvailabilityGroupData(JsonElement element)
        {
            ResourceIdentifier         id             = default;
            string                     name           = default;
            ResourceType               type           = default;
            SystemData                 systemData     = default;
            Optional <string>          targetDatabase = default;
            Optional <string>          sourceEndpoint = default;
            Optional <string>          primaryAvailabilityGroupName   = default;
            Optional <string>          secondaryAvailabilityGroupName = default;
            Optional <ReplicationMode> replicationMode = default;
            Optional <Guid>            distributedAvailabilityGroupId = default;
            Optional <Guid>            sourceReplicaId = default;
            Optional <Guid>            targetReplicaId = default;
            Optional <string>          linkState       = default;
            Optional <string>          lastHardenedLsn = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("targetDatabase"))
                        {
                            targetDatabase = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("sourceEndpoint"))
                        {
                            sourceEndpoint = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("primaryAvailabilityGroupName"))
                        {
                            primaryAvailabilityGroupName = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("secondaryAvailabilityGroupName"))
                        {
                            secondaryAvailabilityGroupName = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("replicationMode"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            replicationMode = new ReplicationMode(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("distributedAvailabilityGroupId"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            distributedAvailabilityGroupId = property0.Value.GetGuid();
                            continue;
                        }
                        if (property0.NameEquals("sourceReplicaId"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            sourceReplicaId = property0.Value.GetGuid();
                            continue;
                        }
                        if (property0.NameEquals("targetReplicaId"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            targetReplicaId = property0.Value.GetGuid();
                            continue;
                        }
                        if (property0.NameEquals("linkState"))
                        {
                            linkState = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("lastHardenedLsn"))
                        {
                            lastHardenedLsn = property0.Value.GetString();
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new DistributedAvailabilityGroupData(id, name, type, systemData, targetDatabase.Value, sourceEndpoint.Value, primaryAvailabilityGroupName.Value, secondaryAvailabilityGroupName.Value, Optional.ToNullable(replicationMode), Optional.ToNullable(distributedAvailabilityGroupId), Optional.ToNullable(sourceReplicaId), Optional.ToNullable(targetReplicaId), linkState.Value, lastHardenedLsn.Value));
        }
Example #22
0
 /// <summary>
 /// From NHibernate documentation:
 /// Persist all reachable transient objects, reusing the current identifier
 /// values. Note that this will not trigger the Interceptor of the Session.
 /// </summary>
 /// <param name="instance">The instance.</param>
 /// <param name="replicationMode">The replication mode.</param>
 public static void Replicate(object instance, ReplicationMode replicationMode)
 {
     ActiveRecordBase.Replicate(instance, replicationMode);
 }
        private void PerformReplication(object entity, object id, object version, IEntityPersister persister, ReplicationMode replicationMode, IEventSource source)
        {
            if (log.IsDebugEnabled)
            {
                log.Debug("replicating changes to " + MessageHelper.InfoString(persister, id, source.Factory));
            }

            new OnReplicateVisitor(source, id, entity, true).Process(entity, persister);

            source.PersistenceContext.AddEntity(
                entity,
                persister.IsMutable ? Status.Loaded : Status.ReadOnly,
                null,
                source.GenerateEntityKey(id, persister),
                version,
                LockMode.None,
                true,
                persister,
                true,
                false);

            CascadeAfterReplicate(entity, persister, replicationMode, source);
        }
 private void CascadeAfterReplicate(object entity, IEntityPersister persister, ReplicationMode replicationMode, IEventSource source)
 {
     source.PersistenceContext.IncrementCascadeLevel();
     try
     {
         new Cascade(CascadingAction.Replicate, CascadePoint.AfterUpdate, source).CascadeOn(persister, entity, replicationMode);
     }
     finally
     {
         source.PersistenceContext.DecrementCascadeLevel();
     }
 }
        public virtual void OnReplicate(ReplicateEvent @event)
        {
            IEventSource source = @event.Session;

            if (source.PersistenceContext.ReassociateIfUninitializedProxy(@event.Entity))
            {
                log.Debug("uninitialized proxy passed to replicate()");
                return;
            }

            object entity = source.PersistenceContext.UnproxyAndReassociate(@event.Entity);

            if (source.PersistenceContext.IsEntryFor(entity))
            {
                log.Debug("ignoring persistent instance passed to replicate()");
                //hum ... should we cascade anyway? throw an exception? fine like it is?
                return;
            }

            IEntityPersister persister = source.GetEntityPersister(@event.EntityName, entity);

            // get the id from the object

            /*if ( persister.isUnsaved(entity, source) ) {
             * throw new TransientObjectException("transient instance passed to replicate()");
             * }*/
            object id = persister.GetIdentifier(entity);

            if (id == null)
            {
                throw new TransientObjectException("instance with null id passed to replicate()");
            }

            ReplicationMode replicationMode = @event.ReplicationMode;
            object          oldVersion;

            if (replicationMode == ReplicationMode.Exception)
            {
                //always do an INSERT, and let it fail by constraint violation
                oldVersion = null;
            }
            else
            {
                //what is the version on the database?
                oldVersion = persister.GetCurrentVersion(id, source);
            }

            if (oldVersion != null)
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug("found existing row for " + MessageHelper.InfoString(persister, id, source.Factory));
                }

                // HHH-2378
                object realOldVersion = persister.IsVersioned ? oldVersion : null;

                bool canReplicate =
                    replicationMode.ShouldOverwriteCurrentVersion(entity, realOldVersion,
                                                                  persister.GetVersion(entity),
                                                                  persister.VersionType);

                if (canReplicate)
                {
                    //will result in a SQL UPDATE:
                    PerformReplication(entity, id, realOldVersion, persister, replicationMode, source);
                }
                else
                {
                    //else do nothing (don't even reassociate object!)
                    log.Debug("no need to replicate");
                }

                //TODO: would it be better to do a refresh from db?
            }
            else
            {
                // no existing row - do an insert
                if (log.IsDebugEnabled)
                {
                    log.Debug("no existing row, replicating new instance " + MessageHelper.InfoString(persister, id, source.Factory));
                }

                bool      regenerate = persister.IsIdentifierAssignedByInsert;            // prefer re-generation of identity!
                EntityKey key        = regenerate ? null : source.GenerateEntityKey(id, persister);

                PerformSaveOrReplicate(entity, key, persister, regenerate, replicationMode, source, true);
            }
        }
		private void CascadeAfterReplicate(object entity, IEntityPersister persister, ReplicationMode replicationMode, IEventSource source)
		{
			source.PersistenceContext.IncrementCascadeLevel();
			try
			{
				new Cascade(CascadingAction.Replicate, CascadePoint.AfterUpdate, source).CascadeOn(persister, entity, replicationMode);
			}
			finally
			{
				source.PersistenceContext.DecrementCascadeLevel();
			}
		}
		/// <summary>
		/// Used only by Replicate
		/// </summary>
		/// <param name="obj"></param>
		/// <param name="id"></param>
		/// <param name="version"></param>
		/// <param name="replicationMode"></param>
		/// <param name="persister"></param>
		private void DoReplicate( object obj, object id, object version, ReplicationMode replicationMode, IClassPersister persister )
		{
			if( log.IsDebugEnabled )
			{
				log.Debug( "replicating changes to " + MessageHelper.InfoString( persister, id ) );
			}

			new OnReplicateVisitor( this, id ).Process( obj, persister );
			Key key = new Key( id, persister );
			AddEntity( key, obj );
			AddEntry( obj, Status.Loaded, null, id, version, LockMode.None, true, persister, true );

			cascading++;
			try
			{
				// do cascade
				Cascades.Cascade( this, persister, obj, Cascades.CascadingAction.ActionReplicate, CascadePoint.CascadeOnUpdate, replicationMode );
			}
			finally
			{
				cascading--;
			}
		}