Inheritance: MonoBehaviour
Example #1
0
        //-----------------------------------------------------------------------------
        // Ledge Passing
        //-----------------------------------------------------------------------------
        // Update ledge passing, handling changes in altitude.
        public void CheckLedges(Entity entity)
        {
            if (!entity.Physics.PassOverLedges)
                return;

            Point2I prevLocation = entity.RoomControl.GetTileLocation(entity.PreviousPosition + entity.Physics.CollisionBox.Center);
            Point2I location = entity.RoomControl.GetTileLocation(entity.Position + entity.Physics.CollisionBox.Center);

            // When moving over a new tile, check its ledge state.
            if (location != prevLocation) {
                entity.Physics.LedgeTileLocation = new Point2I(-1, -1);

                if (entity.RoomControl.IsTileInBounds(location)) {
                    Tile tile = entity.RoomControl.GetTopTile(location);

                    if (tile != null && tile.IsLedge) {
                        entity.Physics.LedgeTileLocation = location;
                        // Adjust ledge altitude.
                        if (IsMovingUpLedge(entity, tile))
                            entity.Physics.LedgeAltitude--;
                        else if (IsMovingDownLedge(entity, tile))
                            entity.Physics.LedgeAltitude++;
                    }
                }
            }
        }
        protected override void TickCore(Entity host, RealmTime time, ref object state)
        {
            int cool = (int) state;

            if (cool <= 0)
            {
                if (host.HasConditionEffect(ConditionEffectIndex.Stunned)) return;

                Position target = new Position
                {
                    X = host.X + (float) (range*Math.Cos(angle.Value)),
                    Y = host.Y + (float) (range*Math.Sin(angle.Value)),
                };
                host.Owner.Timers.Add(new WorldTimer(0, (world, t) =>
                {
                    Entity entity = Entity.Resolve(world.Manager, child);
                    entity.Move(target.X, target.Y);
                    (entity as Enemy).Terrain = (host as Enemy).Terrain;
                    world.EnterWorld(entity);
                }));
                cool = coolDown.Next(Random);
            }
            else
                cool -= time.thisTickTimes;

            state = cool;
        }
Example #3
0
        protected override void TickCore(Entity host, RealmTime time, ref object state)
        {
            WanderStorage storage;
            if (state == null) storage = new WanderStorage();
            else storage = (WanderStorage)state;

            Status = CycleStatus.NotStarted;

            if (host.HasConditionEffect(ConditionEffects.Paralyzed)) return;

            Status = CycleStatus.InProgress;
            if (storage.RemainingDistance <= 0)
            {
                storage.Direction = new Vector2(Random.Next(-1, 2), Random.Next(-1, 2));
                storage.Direction.Normalize();
                storage.RemainingDistance = period.Next(Random) / 1000f;
                Status = CycleStatus.Completed;
            }
            float dist = host.GetSpeed(speed) * (time.thisTickTimes / 1000f);
            host.ValidateAndMove(host.X + storage.Direction.X * dist, host.Y + storage.Direction.Y * dist);
            host.UpdateCount++;

            storage.RemainingDistance -= dist;

            state = storage;
        }
 public override void CollidedWith(Entity e)
 {
     base.CollidedWith (e);
     if (e is TerrainEntity && e.Collidable && !(e is PitEntity)) {
         alive = false;
     }
 }
    public override bool OnCollisionSolid(Entity other)
    {
        Debug.Log("In Collision");
        ChatController.Show ("Hello welcome to college, I will be you're advisor");

        return true;
    }
Example #6
0
        public void Insert_LowFare(Entity.LowFare o_LowFare)
        {
            if (o_LowFare == null)
                return;

            Entity.LowFare e_LowFare = new Entity.LowFare();
            e_LowFare.LowFare_ID = o_LowFare.LowFare_ID;
            e_LowFare.LowFare_Type = o_LowFare.LowFare_Type;
            e_LowFare.LowFare_Detail_ID = o_LowFare.LowFare_Detail_ID;
            e_LowFare.LowFare_Adults = o_LowFare.LowFare_Adults;
            e_LowFare.LowFare_Children = o_LowFare.LowFare_Children;
            e_LowFare.LowFare_Infants = o_LowFare.LowFare_Infants;
            e_LowFare.LowFare_Passengers = FilterUtility.FilterSQL(o_LowFare.LowFare_Passengers);
            e_LowFare.LowFare_Airline = FilterUtility.FilterSQL(o_LowFare.LowFare_Airline);
            e_LowFare.LowFare_Class = FilterUtility.FilterSQL(o_LowFare.LowFare_Class);
            e_LowFare.LowFare_Member_ID = o_LowFare.LowFare_Member_ID;
            e_LowFare.LowFare_AdminUser_ID = o_LowFare.LowFare_AdminUser_ID;
            e_LowFare.LowFare_Status = o_LowFare.LowFare_Status;
            e_LowFare.LowFare_AddTime = o_LowFare.LowFare_AddTime;
            e_LowFare.LowFare_SubmitTime = o_LowFare.LowFare_SubmitTime;

            BLL.LowFare_Detail b_LowFare_Detail = new LowFare_Detail();
            b_LowFare_Detail.Insert_LowFare_Detail(e_LowFare.LowFare_Detail_ID);

            d_LowFare.Insert_LowFare(e_LowFare);
        }
 /// <summary>
 /// Constructs a new constraint which allows relative angular motion around a hinge axis and a twist axis.
 /// </summary>
 /// <param name="connectionA">First connection of the pair.</param>
 /// <param name="connectionB">Second connection of the pair.</param>
 /// <param name="worldHingeAxis">Hinge axis attached to connectionA.
 /// The connected entities will be able to rotate around this axis relative to each other.</param>
 /// <param name="worldTwistAxis">Twist axis attached to connectionB.
 /// The connected entities will be able to rotate around this axis relative to each other.</param>
 public SwivelHingeAngularJoint(Entity connectionA, Entity connectionB, Vector3 worldHingeAxis, Vector3 worldTwistAxis)
 {
     ConnectionA = connectionA;
     ConnectionB = connectionB;
     WorldHingeAxis = worldHingeAxis;
     WorldTwistAxis = worldTwistAxis;
 }
Example #8
0
        public void SpawnEntity(World world, Entity entity)
        {
            entity.Id = nextEntityId++;
            world.Entities.Add(entity);
            // Get nearby clients in the same world
            var clients = GetClientsInWorld(world)
                .Where(c => !c.IsDisconnected && c.Entity.Position.DistanceTo(entity.Position) < (c.ViewDistance * Chunk.Width));
            entity.PropertyChanged += EntityOnPropertyChanged;

            if (clients.Count() != 0)
            {
                // Spawn entity on relevant clients
                if (entity is PlayerEntity)
                {
                    // Isolate the client being spawned
                    var client = clients.First(c => c.Entity == entity);
                    client.Entity.BedStateChanged += EntityOnUpdateBedState;
                    client.Entity.BedTimerExpired += EntityOnBedTimerExpired;
                    clients = clients.Where(c => c.Entity != entity);
                    clients.ToList().ForEach(c => {
                        c.SendPacket(new SpawnNamedEntityPacket(client));
                        c.KnownEntities.Add(client.Entity.Id);
                    });
                }
            }
            server.ProcessSendQueue();
        }
Example #9
0
        /// <summary>
        /// Constructs the query manager for a character.
        /// </summary>
        public QueryManager(Entity characterBody, CharacterContactCategorizer contactCategorizer)
        {
            this.characterBody = characterBody;
            this.contactCategorizer = contactCategorizer;

            SupportRayFilter = SupportRayFilterFunction;
        }
 public ProposeAttributeChangeEventArgs(Entity entity, string componentName, string attributeName, object value)
 {
     this.entity = entity;
     this.componentName = componentName;
     this.attributeName = attributeName;
     this.value = value;
 }
Example #11
0
        /// <summary>
        /// Splits a single compound collidable into two separate compound collidables and computes information needed by the simulation.
        /// </summary>
        /// <param name="childContributions">List of distribution information associated with each child shape of the whole compound shape used by the compound being split.</param>
        /// <param name="splitPredicate">Delegate which determines if a child in the original compound should be moved to the new compound.</param>
        /// <param name="a">Original compound to be split.  Children in this compound will be removed and added to the other compound.</param>
        /// <param name="b">Compound to receive children removed from the original compound.</param>
        /// <param name="distributionInfoA">Volume, volume distribution, and center information about the new form of the original compound collidable.</param>
        /// <param name="distributionInfoB">Volume, volume distribution, and center information about the new compound collidable.</param>
        /// <returns>Whether or not the predicate returned true for any element in the original compound and split the compound.</returns>
        public static bool SplitCompound(IList<ShapeDistributionInformation> childContributions, Func<CompoundChild, bool> splitPredicate,
                        Entity<CompoundCollidable> a, out Entity<CompoundCollidable> b,
                        out ShapeDistributionInformation distributionInfoA, out ShapeDistributionInformation distributionInfoB)
        {
            var bCollidable = new CompoundCollidable { Shape = a.CollisionInformation.Shape };
            b = null;


            float weightA, weightB;
            if (SplitCompound(childContributions, splitPredicate, a.CollisionInformation, bCollidable, out distributionInfoA, out distributionInfoB, out weightA, out weightB))
            {
                //Reconfigure the entities using the data computed in the split.
                float originalMass = a.mass;
                if (a.CollisionInformation.children.Count > 0)
                {
                    float newMassA = (weightA / (weightA + weightB)) * originalMass;
                    Matrix3x3.Multiply(ref distributionInfoA.VolumeDistribution, newMassA * InertiaHelper.InertiaTensorScale, out distributionInfoA.VolumeDistribution);
                    a.Initialize(a.CollisionInformation, newMassA, distributionInfoA.VolumeDistribution, distributionInfoA.Volume);
                }
                if (bCollidable.children.Count > 0)
                {
                    float newMassB = (weightB / (weightA + weightB)) * originalMass;
                    Matrix3x3.Multiply(ref distributionInfoB.VolumeDistribution, newMassB * InertiaHelper.InertiaTensorScale, out distributionInfoB.VolumeDistribution);
                    b = new Entity<CompoundCollidable>();
                    b.Initialize(bCollidable, newMassB, distributionInfoB.VolumeDistribution, distributionInfoB.Volume);
                }

                SplitReposition(a, b, ref distributionInfoA, ref distributionInfoB, weightA, weightB);
                return true;
            }
            else
                return false;
        }
 public void LoadScript(string scriptType, string scriptName, string script, Entity ent)
 {
     if(this.scriptEngines.ContainsKey(scriptType))
     {
         this.scriptEngines[scriptType].LoadScript(script, scriptName, ent.localid);
     }
 }
		public void Initialize()
		{
			_tokenizer = new Tokenizer();
			_tokenizedBufferEntity = new Entity<LinkedList<Token>>();
			_textBuffer = MockRepository.GenerateStub<ITextBufferAdapter>();
			_finder = new MatchingBraceFinder(_textBuffer, _tokenizedBufferEntity);
		}
Example #14
0
        public static bool insertPicture(Entity.Picture picture)
        {
            try
            {

                string sqlInsert = @"INSERT INTO Picture(Album_ID,Picture_Name,Picture_Detail,Picture_Path, Picture_Status, Create_date)
                                   VALUES(@albunID,@pictureName,@pictureDetail,@picturePath,'A',GetDate())";
                ConnectDB connpath = new ConnectDB();
                objConn = new SqlConnection();
                objConn.ConnectionString = connpath.connectPath();
                objConn.Open();
                objCmd = new SqlCommand(sqlInsert, objConn);
                objCmd.Parameters.Add("@albunID", SqlDbType.Int).Value = picture.Album_ID;
                objCmd.Parameters.Add("@pictureName", SqlDbType.NVarChar).Value = picture.Picture_Name.ToString();
                objCmd.Parameters.Add("@pictureDetail", SqlDbType.NVarChar).Value = picture.Picture_Detail.ToString();
                objCmd.Parameters.Add("@picturePath", SqlDbType.NVarChar).Value = picture.Picture_Path.ToString();

                objCmd.ExecuteNonQuery();
                objConn.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }


        }
 private WorkitemPropertyDescriptor(Entity entity, string name, string attribute, Attribute[] attrs, PropertyUpdateSource updateSource)
     : base(name, attrs) {
     this.entity = entity;
     this.attribute = attribute;
     this.updateSource = updateSource;
     readOnly = entity.IsPropertyDefinitionReadOnly(Attribute) || entity.IsPropertyReadOnly(Attribute);
 }
 public override void OnInteract(Entity e)
 {
     if (e is PlayerEntity)
     {
         if (!opened)
         {
             PlayerEntity p = e as PlayerEntity;
             if (this.level <= p.GetSecurityLevel())
             {
                 opened = true;
                 UserInterface.Message("Inside is a " + itemInside.Name + " (Interact again to take)", Color.SkyBlue);
             }
             else
             {
                 UserInterface.Message("You need to be atleast " + level.name + " to use this chest", Color.Red);
             }
         }
         else
         {
             if (itemInside != null)
             {
                 PlayerEntity p = e as PlayerEntity;
                 bool success = p.PickUpItem(itemInside);
                 if (success)
                 {
                     UserInterface.Message("Took " + itemInside.Name, Color.SkyBlue);
                     itemInside = null;
                 }
             }
             else UserInterface.Message("The chest is Empty!", Color.Red);
         }
     }
 }
Example #17
0
        protected override void TickCore(Entity host, RealmTime time, ref object state)
        {
            int cooldown;
            if (state == null) cooldown = 1000;
            else cooldown = (int)state;

            Status = CycleStatus.NotStarted;

            if (host.HasConditionEffect(ConditionEffects.Paralyzed)) return;

            var player = (Player)host.GetNearestEntity(distance, null);
            if (player != null)
            {
                Vector2 vect;
                vect = new Vector2(player.X - host.X, player.Y - host.Y);
                vect.Normalize();
                float dist = host.GetSpeed(speed) * (time.thisTickTimes / 1000f);
                host.ValidateAndMove(host.X + (-vect.X) * dist, host.Y + (-vect.Y) * dist);
                host.UpdateCount++;

                if (cooldown <= 0)
                {
                    Status = CycleStatus.Completed;
                    cooldown = 1000;
                }
                else
                {
                    Status = CycleStatus.InProgress;
                    cooldown -= time.thisTickTimes;
                }
            }

            state = cooldown;
        }
	static public void ShootCircleBullets(Pool pool, Entity e)
	{
		for(int i = 0; i < 12; ++i)
		{
			ShootCircleBullet(pool, e, i, 12);
		}
	}
	    public static bool npcAttack(Npc npc, Entity target) {
		    if (npcHasAttack(npc)) {
			    doNpcAttack(npc, target);
			    return true;
		    }
		    return false;
	    }
 public PhysicsSimulationComponent(Entity parent)
     : base(parent, "PhysicsSimulationComponent")
 {
     space = new Space();
     space.ForceUpdater.Gravity = GRAVITY;
     space.TimeStepSettings.TimeStepDuration = TIME_STEP_DURATION;
 }
Example #21
0
        internal void AddEntity(Entity mEntity)
        {
            OrderedEntities.Add(mEntity);
            OrderedEntities.Sort((a, b) => a.Layer.CompareTo(b.Layer));

            Repository.AddEntity(mEntity);
        }
Example #22
0
 public override void onCollide(Entity entity, Game1 game)
 {
     if (entity is Enemy)
     {
         health--;
     }
 }
 public override void Process(Entity e)
 {
     Health health = healthMapper.Get(e);
     Transform transform = transformMapper.Get(e);
     Vector2 textPosition = new Vector2((float)transform.X + 20, (float)transform.Y - 30);
     spriteBatch.DrawString(font,health.HealthPercentage + "%",textPosition,Color.White);
 }
 public void Before() {
     var pool = Helper.CreatePool();
     _e = pool.CreateEntity();
     _e.AddComponent(CP.ComponentA, new ComponentA());
     _e.AddComponent(CP.ComponentB, new ComponentB());
     _e.AddComponent(CP.ComponentC, new ComponentC());
 }
Example #25
0
        public override bool OnBulletHitCallback(UpdateContext updateContext, CBullet bullet, Entity entityHit)
        {
            EntityWorld entityWorld = bullet.Entity.EntityWorld;
            IZombieSpatialMap zombieSpatialMap = entityWorld.Services.Get<IZombieSpatialMap>();

            // if the message has not listeners, then there's no point in doing in broadcasting it.
            RocketExplodedMessage explodedMessage = entityWorld.HasListeners<RocketExplodedMessage>() ? entityWorld.FetchMessage<RocketExplodedMessage>() : null; // AAWFFUUULL!!
            foreach (Entity zombie in zombieSpatialMap.GetAllIntersecting(bullet.Entity.Transform, RocketLauncher.ExplosionRange))
            {
                if (zombie.Get<CHealth>().IsAlive && ZombieHelper.TakeDamage(zombie, 25, Vector2.Zero))
                {
                    // if the message has not listeners, then there's no point in doing in broadcasting it.
                    if (explodedMessage != null)
                    {
                        explodedMessage.Add(zombie);
                    }
                }
            }

            // if the message has not listeners, then there's no point in doing in broadcasting it.
            if (explodedMessage != null)
            {
                entityWorld.BroadcastMessage(explodedMessage);
            }

            IParticleEngine particleEngine = entityWorld.Services.Get<IParticleEngine>();
            particleEngine[ParticleEffectID.RocketExplosion].Trigger(bullet.Entity.Transform);

            bullet.Entity.Delete();
            return true;
        }
Example #26
0
 public void Add(Entity e, int distance) {
     var v = new Vertebra();
     v.SetEntity(e);
     v.Distance = distance;
     v.Snake = this;
     Add(v);
 }
        public RecordsSource_EnumEntityFilters()
        {
            DB.EntityChanges.Insert(new
            {
                EntityName = "Entity",
                EntityKey = "1",
                ChangedOn = DateTime.Now,
                ChangeType = EntityChangeType.Insert
            });
            DB.EntityChanges.Insert(new
            {
                EntityName = "Entity",
                EntityKey = "1",
                ChangedOn = DateTime.Now,
                ChangeType = EntityChangeType.Update
            });
            DB.EntityChanges.Insert(new
            {
                EntityName = "Entity",
                EntityKey = "1",
                ChangedOn = DateTime.Now,
                ChangeType = EntityChangeType.Delete
            });

            _source = new RecordsSource(new Notificator());
            Admin.AddEntity<EntityChange>();
            Admin.SetForeignKeysReferences();
            Admin.ConnectionStringName = ConnectionStringName;
            _entity = Admin.ChangeEntity;
            _property = _entity["ChangeType"];
        }
Example #28
0
 private static void MapAllColumns(MappingSet set, ITable table, Entity entity)
 {
     for(int i = 0; i < table.Columns.Count; i++)
     {
         set.ChangeMappedColumnFor(entity.ConcreteProperties[i]).To(table.Columns[i]);
     }
 }
Example #29
0
        public override bool intersect(Entity e)
        {
            if (base.intersect(e))
            {
                if (e is Player)
                    ((Player)e).die();
                else if (e is Explosion)
                    die();

                return true;
            }

            bool intersect = false;

            for(int a = 0; a < 10; a++)
            {
                if (neck[a] != null)
                {
                    if (neck[a].intersect(e))
                    {
                        neck[a] = null;
                        intersect = true;
                    }
                }
            }

            return intersect;
        }
 public override void OnCollideWith(Entity e)
 {
     if (e is PlayerEntity)
     {
         UserInterface.Message("Present Clearance Level (Press E to interact)", Color.Red);
     }
 }
Example #31
0
 public PresentationOwnerData(int variation)
 {
     this.variation         = variation;
     currentVariation       = -1;
     currentVariationEntity = Entity.Null;
 }
        public void ReplicateProspectInfoUnitTest()
        {
            #region 1. Setup / Arrange
            var orgServiceMock = new Mock<IOrganizationService>();
            var orgService = orgServiceMock.Object;
            var orgTracingMock = new Mock<ITracingService>();
            var orgTracing = orgTracingMock.Object;

            #region Prospect EntityCollection
            var ProspectCollection = new EntityCollection
            {
                EntityName = "gsc_sls_prospect",
                Entities =
                {
                    new Entity
                    {
                        Id = Guid.NewGuid(),
                        LogicalName = "gsc_sls_prospect",
                        EntityState = EntityState.Changed,
                        Attributes = new AttributeCollection
                        {
                            {"gsc_firstname", "Mark"},
                            {"gsc_middlename", ""},
                            {"gsc_lastname", "Opaco"},
                            {"gsc_mobileno", "09123456789"},
                            {"gsc_emailaddress", "*****@*****.**"},
                            {"gsc_street", "Antipolo St."},
                            {"gsc_cityid",new EntityReference("gsc_syscity", Guid.NewGuid())
                            { Name = "Manila"}},
                            {"gsc_provinceid",new EntityReference("gsc_sysregion", Guid.NewGuid())
                            { Name = "Manila"}},
                            {"gsc_countryid", new EntityReference("gsc_syscountry", Guid.NewGuid()) {Name = "Philippines"}},
                        }
                    }
                }
            };
            #endregion

            #region ProspectInquiry EntityCollection
            var ProspectInquiryCollection = new EntityCollection
            {
                EntityName = "Prospect Inquiry",
                Entities =
                {
                    new Entity
                    {
                        Id = Guid.NewGuid(),
                        LogicalName = "lead",
                        EntityState = EntityState.Created,
                        Attributes = new AttributeCollection
                        {
                            {"firstname", ""},
                            {"middlename", ""},
                            {"lastname", ""},
                            {"fullname", ""},
                            {"mobilephone", ""},
                            {"emailaddress1", ""},
                            {"address1_line1", ""},
                            {"address1_city", ""},
                            {"address1_stateorprovince",""},
                            {"address1_country", ""},
                            {"gsc_prospectid", new EntityReference("gsc_sls_prospect", ProspectCollection.Entities[0].Id)},
                        }
                    }
                }
            };
            #endregion

            orgServiceMock.Setup((service => service.RetrieveMultiple(
                It.Is<QueryExpression>(expression => expression.EntityName == ProspectCollection.EntityName)
                ))).Returns(ProspectCollection);

            #endregion

            #region 2. Call/Action

            var ProspectInquiryHandler = new ProspectInquiryHandler(orgService, orgTracing);
            Entity prospectInquiry = ProspectInquiryHandler.ReplicateProspectInfo(ProspectInquiryCollection.Entities[0]);
            #endregion

            #region 3. Verify
            var fullname = ProspectCollection.Entities[0]["gsc_firstname"] + " " + ProspectCollection.Entities[0]["gsc_lastname"];
            Assert.AreEqual(ProspectCollection.Entities[0]["gsc_firstname"], prospectInquiry["firstname"]);
            Assert.AreEqual(ProspectCollection.Entities[0]["gsc_middlename"], prospectInquiry["middlename"]);
            Assert.AreEqual(ProspectCollection.Entities[0]["gsc_lastname"], prospectInquiry["lastname"]);
            Assert.AreEqual(fullname, prospectInquiry["fullname"]);
            Assert.AreEqual(ProspectCollection.Entities[0]["gsc_mobileno"], prospectInquiry["mobilephone"]);
            Assert.AreEqual(ProspectCollection.Entities[0]["gsc_emailaddress"], prospectInquiry["emailaddress1"]);
            Assert.AreEqual(ProspectCollection.Entities[0]["gsc_street"], prospectInquiry["address1_line1"]);
            Assert.AreEqual(ProspectCollection.Entities[0].GetAttributeValue<EntityReference>("gsc_cityid").Name, prospectInquiry["address1_city"]);
            Assert.AreEqual(ProspectCollection.Entities[0].GetAttributeValue<EntityReference>("gsc_provinceid").Name, prospectInquiry["address1_stateorprovince"]);
            Assert.AreEqual(ProspectCollection.Entities[0].GetAttributeValue<EntityReference>("gsc_countryid").Name, prospectInquiry["address1_country"]);
            #endregion
        }
Example #33
0
 /// <summary>
 /// Returns all visible creatures in range of entity, excluding itself.
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="range"></param>
 /// <returns></returns>
 public ICollection <Creature> GetVisibleCreaturesInRange(Entity entity, int range = VisibleRange)
 {
     return(this.GetCreatures(a => a != entity && a.GetPosition().InRange(entity.GetPosition(), range) && !a.Conditions.Has(ConditionsA.Invisible)));
 }
Example #34
0
 public override void Broadcast(Packet packet, Entity source, bool sendToSource = true, int range = -1)
 {
     Log.Warning("Broadcast in Limbo from source.");
     Log.Debug(Environment.StackTrace);
 }
Example #35
0
 /// <summary>Initializes a new instance of the <see cref="T:Microsoft.Crm.Sdk.Messages.GenerateSocialProfileRequest"></see> class.</summary>
 public GenerateSocialProfileRequest()
 {
   this.RequestName = "GenerateSocialProfile";
   this.Entity = (Entity) null;
 }
Example #36
0
 public IdleState(Entity entity, FiniteStateMachine stateMachine, string animBoolName, D_IdleState stateData) : base(entity, stateMachine, animBoolName)
 {
     this.stateData = stateData;
 }
        /// <summary>
        /// Constructs a new demo.
        /// </summary>
        /// <param name="game">Game owning this demo.</param>
        public EntityConstructionDemo(DemosGame game)
            : base(game)
        {
            //An entity is the basic physical simulation object in BEPUphysics.  It represents a rigid body which can be dynamic or kinematic.
            //Dynamic objects can bounce around and respond to collisions using forces.  Kinematic entities can move using velocity,
            //but effectively have infinite inertia and do not respond to collisions or forces.

            //For each of the below constructors, there are multiple overloads.  Half have a mass parameter, half do not.  If a mass parameter is specified,
            //the object is created as a dynamic object.  If a mass parameter is not specified, it is created as a kinematic object.  This state can be changed later
            //by using the BecomeDynamic/BecomeKinematic methods.


            //************************
            //There are a variety of ways to construct entities depending on your needs.
            //The most common approach is to use the 'prefab' types, like the Box, Sphere, ConvexHull, Cylinder, and so on (BEPUphysics.Entities.Prefabs namespace).
            //These provide a short cut to constructing the objects and generally provide convenience accessors to shape properties.

            //We'll start with such an entity for the kinematic ground.  Notice how it allows the definition of position and shape data all in the constructor.
            //It has other overloads that allow you to specify a mass (for a dynamic object) or a full MotionState instead of just a position.
            Box ground = new Box(new Vector3(0, -.5f, 0), 50, 1, 50);
            Space.Add(ground);

            //If you examine the ground's CollisionInformation property, you'll find that it is a generic method which returns a ConvexCollidable<BoxShape>.
            //So, in addition to having convenience properties, it also lets you go deeper into the object's data by knowing what the types are.


            //************************
            //Let's go one level up the hierarchy to Entity<T>.  This is the superclass of all prefab types.
            //The generic parameter is the type of the Collidable that the entity uses as its collision proxy.
            //It is also what allows prefab types' CollisionInformation property to return that type rather than EntityCollidable.

            Space.Add(new Entity<ConvexCollidable<SphereShape>>(new ConvexCollidable<SphereShape>(new SphereShape(1)), 1)
                          {
                              Position = new Vector3(-10, 1, 0)
                          });

            //That's a bit unwieldy<<>><>, but it works.  Directly constructing entities in this manner isn't common or generally necessary.
            //If you want to have a CollisionInformation property that returns a specific type but don't want to use a specific prefab type, this is the way to go.

            //Note that the constructor itself does not include any position/motion state parameters nor does it include any direct shape data.  The position and other auxiliary
            //properties can be set after it's been constructed.  In this case, object initializer syntax is used to set the Position.
            //The shape data is included within the first EntityCollidable parameter which defines the entity's collision proxy.
            //The prefab types discussed previously all create such EntityCollidables internally using the data passed into the constructor.


            //************************
            //So let's move onto something a little more convenient.  Entity<T> has a non-generic parent Entity.  It still has a CollisionInformation property,
            //but it returns an EntityCollidable rather than a specific type.

            Space.Add(new Entity(new BoxShape(2, 2, 2), 1)
                {
                    Position = new Vector3(10, 1, 0)
                });

            //Much better! No more ugly generic type syntax pollution.  Notice that there are quite a few overloads in the Entity.
            //In addition to overloads that accept EntityCollidable instances (as used in the generic entity above), Entity provides constructors that
            //take shapes directly.  Internally, the entity can create its own EntityCollidable instance based on the shape.  This further simplifies the construction process.

            //An object initializer is once again used to set the position, since the constructors do not have all the convenience constructor frills of the prefab types.


            //************************
            //All of the above entity types have read-only CollisionInformation properties.  Once an entity of those types is created, it cannot change its fundamental shape.
            //A sphere may get bigger or smaller, but a sphere entity couldn't become a box entity.

            //That's where the MorphableEntity comes in.  

            var morphable = new MorphableEntity(new CylinderShape(2, 1), 1)
            {
                Position = new Vector3(10, 3, 0)
            };
            Space.Add(morphable);

            //It is constructed identically to its parent Entity class, but after being created, the EntityCollidable it uses can change!
            morphable.CollisionInformation = new ConvexCollidable<ConeShape>(new ConeShape(2, 1));

            //That's neat, but that collidable constructor with generic type is a bit ugly.  We don't care about doing any type-specific configuration
            //on the EntityCollidable itself, so we can just tell the shape to make us an EntityCollidable instance.  This is what the Entity/MorphableEntity constructors
            //do internally when given an EntityShape instead of an EntityCollidable (which in turn contains an EntityShape).
            morphable.CollisionInformation = new ConeShape(2, 1).GetCollidableInstance();

            //While this is arguably a bit prettier, its major benefit comes from the fact that you don't need to know the type of the shape to call GetCollidableInstance.
            //If it's an EntityShape, it can create an EntityCollidable for itself.



            //************************
            //That's it for the different types of entities.  Another very useful technique is to share shapes and initialization between entities.
            //Re-using convex hulls is a common use case.  They have a fairly expensive initialization, and they tend to be some of the larger shapes memory-wise.
            //Rather than having a thousand redundant copies of identical geometry, one shape can be made and reused for subsequent entities.

            //First, create the pointset that composes the convex hull.
            var vertices = new[] 
            {
                new Vector3(-1,0,-1),
                new Vector3(-1,0,1),
                new Vector3(1,0,-1),
                new Vector3(1,0,1),
                new Vector3(0,2,0)             
            };
            //Construct the shape itself.
            var convexHullShape = new ConvexHullShape(vertices);

            //Create an entity using the shape.
            var convexHull = new Entity(convexHullShape, 2) { Position = new Vector3(0, 1, 0) };
            Space.Add(convexHull);
            //Create a bunch of other shapes using that first shape's properties.  
            //Instead of using a first entity's data, this could also be pulled in from some external source (deserialized save data or something).
            for (int i = 1; i <= 10; i++)
            {
                Space.Add(new Entity(convexHullShape, convexHull.Mass, convexHull.LocalInertiaTensor) { Position = new Vector3(0, 1 + i * 3, 0) });
            }

            //In older versions, initializing the entity was a little expensive if the inertia tensor and some other data wasn't provided.
            //These days, the cost is done once in the shape and the entity initialization is pretty much always super cheap.
            //So, you don't need to share inertia tensors for performance reasons.

            //************************
            //All convex shapes are centered on their local origin.  If you create a box entity and assign its position to (0,1,0), the box shape's center will end up at (0,1,0).
            //For simple shapes like the box, that's always the case without doing any work just based on the definition of the shape.

            //More complicated shapes, like the ConvexHullShape, can be constructed from data which is not initially centered around the origin.  For example, consider these vertices:
            vertices = new[] 
            {
                new Vector3(-5,15,-1),
                new Vector3(-5,15,1),
                new Vector3(-3,15,-1),
                new Vector3(-3,15,1),
                new Vector3(-4,17,0),    
                new Vector3(-4,13,0)             
            };
            //The center of those points is obviously going to be very far from the origin.
            //When we construct a ConvexHullShape, the points get 'recentered.'
            convexHullShape = new ConvexHullShape(vertices);

            //If you look at the convexHullShape.Vertices list, you'll see that the points are relative to a local origin now.
            //So now it's centered on the local origin, as was needed.  But there's a problem- what if you wanted your convex hull entity to end up at the original vertex positions?
            //To get it there, we need to know the offset from the original vertices to the local vertices.
            //Fortunately, there is a constructor overload which provides it!
            Vector3 center;
            convexHullShape = new ConvexHullShape(vertices, out center);

            //Now, when the entity is created, we can position it at the original point's center.  The shape still contains local data, but the entity's location ends up putting the shape in the right spot.
            convexHull = new Entity(convexHullShape, 2) { Position = center };
            Space.Add(convexHull);


            //************************
            //Compound bodies are unique in that they allow you to specify groups of shapes to create a concave shape.
            //Here's the common simple approach to making a compound body, using a prefab type for now.
            CompoundBody body = new CompoundBody(new List<CompoundShapeEntry>
            {
                new CompoundShapeEntry(new BoxShape(1, 1, 1), new Vector3(-7, 3, 8), 1),
                new CompoundShapeEntry(new BoxShape(1, 3, 1), new Vector3(-8, 2, 8), 5),
                new CompoundShapeEntry(new BoxShape(1, 1, 1), new Vector3(-9, 1, 8), 1)
            }, 10);
            Space.Add(body);
            //Each entry has a shape, a rigid transform (orientation and/or translation), and a weight.
            //The rigid transform defines the position of the shape in world space.  They will be recentered into local space within the CompoundShape itself (see previous convex hull example).
            //The 'weight' parameter does not correspond directly to mass, but rather to the contribution of that shape to the whole relative to other shapes.
            //It used to compute the center position of the shape.  When used by a dynamic entity, it is also used to compute a proper inertia tensor.  The resulting inertia tensor is scaled by the entity's actual mass.


            //************************
            //Just like shapes can be shared between entities, you can re-use a shape for multiple entries within a compound body.
            var compoundShape = new CompoundShape(new List<CompoundShapeEntry>
            {
                new CompoundShapeEntry(convexHullShape, new Vector3(7, 3, 8), 1),
                new CompoundShapeEntry(convexHullShape, new RigidTransform(new Vector3(8, 2, 8), Quaternion.CreateFromAxisAngle(Vector3.Forward, MathHelper.PiOver2)), 5),
                new CompoundShapeEntry(convexHullShape, new Vector3(9, 1, 8), 1)
            });

            //And just like normal convex shapes can be shared, so can compound shapes!
            for (int i = 0; i < 3; i++)
                Space.Add(new Entity(compoundShape, 10) { Position = new Vector3(8, 10 + i * 4, 8) });

            //************************
            //You can also use compound shapes as subshapes, creating nested compounds.
            Space.Add(new Entity(new CompoundShape(new List<CompoundShapeEntry>
            {
                new CompoundShapeEntry(compoundShape, new Vector3(7, 5, 8), 1),
                new CompoundShapeEntry(compoundShape, new Vector3(9, 1, 8), 1)
            }), 10) { Position = new Vector3(8, 25, 8) });


            //************************
            //Sometimes, it's nice to be able to change how subshapes behave.
            //This example will use a prefab CompoundBody type, but note that there exists a CompoundCollidable that can be constructed independently as well.
            //Just like a list of CompoundShapeEntry objects can be used to construct a compound object, a list of CompoundChildData objects can too.
            //CompoundChildData objects contain CompoundShapeEntry objects as well as other data to be used by a Collidable instance.
            //That extra data includes material, events, and collision rules.

            var compoundBody = new CompoundBody(new List<CompoundChildData>
            {
                new CompoundChildData { Entry = new CompoundShapeEntry(new CylinderShape(1, 1), new Vector3(0, 2, 8)), CollisionRules = new CollisionRules { Personal = CollisionRule.NoBroadPhase } },
                new CompoundChildData { Entry = new CompoundShapeEntry(new BoxShape(3, 1, 3), new Vector3(0, 1, 8)), Material = new Material(3, 3, 0) }
            }, 10);
            Space.Add(compoundBody);

            //In this example, one of the two blocks doesn't collide with anything.  The other does collide, and has a very high friction material.

            //************************
            //While sharing shapes can help reduce load times, sometimes it's useful to eliminate the shape's initialization cost too.
            //For this purpose, all shapes have a constructor which takes a bunch of data that fully defines the shape.
            //The constructor assumes that all of it is correct; it won't catch any errors or do any additional preprocessing.

            //For example, let's construct a ConvexHullShape from the our earlier ConvexHullShape.
            //We'll need a ConvexShapeDescription that defines the data common to all convex shapes.
            var shapeDescription = new ConvexShapeDescription
                {
                    CollisionMargin = convexHullShape.CollisionMargin,
                    MinimumRadius = convexHullShape.MinimumRadius,
                    MaximumRadius = convexHullShape.MaximumRadius,
                    EntityShapeVolume = new EntityShapeVolumeDescription
                    {
                        Volume = convexHullShape.Volume,
                        VolumeDistribution = convexHullShape.VolumeDistribution
                    }
                };

            //Now, along with the surface vertices from the previous shape, the new shape can be created:
            var shapeFromCachedData = new ConvexHullShape(convexHullShape.Vertices, shapeDescription);

            //Usually, the data for these constructors will come from some cache or storage. For example,
            //a game could store out the above information to disk from a content development tool.
            //At load time, the matching shape can be created at virtually no cost.

            //Stuff the shape into the world!
            Space.Add(new Entity(shapeFromCachedData, 10)
                {
                    Position = new Vector3(-10, 5, -5)
                });

            Game.Camera.Position = new Vector3(0, 3, 25);
        }
Example #38
0
 public LightningAnnihilator(Entity owner, Vector2 relativePosition, float rotation = 0, float[] savedPositions = null) : base(owner, relativePosition, rotation, savedPositions)
 {
     texture = Miasma.EntityExtras[27];
     origin = new Vector2(0, 19);
     turretLength = 46;
 }
Example #39
0
 public CenterDoor(Entity owner, Vector2 relativePosition, float rotation = 0, float[] savedPositions = null) : base(owner, relativePosition, rotation, savedPositions)
 {
     texture = Miasma.EntityExtras[20];
     origin = new Vector2(34.5f, 69.5f);
 }
        public ActionResult AddPortalComment(string regardingEntityLogicalName, string regardingEntityId, string text,
                                             HttpPostedFileBase file = null, string attachmentSettings = null)
        {
            if (string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(StringHelper.StripHtml(text)))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.ExpectationFailed, ResourceManager.GetString("Required_Field_Error").FormatWith(ResourceManager.GetString("Comment_DefaultText"))));
            }

            Guid regardingId;

            Guid.TryParse(regardingEntityId, out regardingId);
            var regarding = new EntityReference(regardingEntityLogicalName, regardingId);

            var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext);
            var serviceContext          = dataAdapterDependencies.GetServiceContext();

            var dataAdapter = new ActivityDataAdapter(dataAdapterDependencies);
            var settings    = EntityNotesController.GetAnnotationSettings(serviceContext, attachmentSettings);
            var crmUser     = dataAdapter.GetCRMUserActivityParty(regarding, "ownerid");
            var portalUser  = new Entity("activityparty");

            portalUser["partyid"] = dataAdapterDependencies.GetPortalUser();

            var portalComment = new PortalComment
            {
                Description        = text,
                From               = portalUser,
                To                 = crmUser,
                Regarding          = regarding,
                AttachmentSettings = settings,
                StateCode          = StateCode.Completed,
                StatusCode         = StatusCode.Received,
                DirectionCode      = PortalCommentDirectionCode.Incoming
            };

            if (file != null && file.ContentLength > 0)
            {
                // Soon we will change the UI/controller to accept multiple attachments during the create dialog, so the data adapter takes in a list of attachments
                portalComment.FileAttachments = new IAnnotationFile[]
                { AnnotationDataAdapter.CreateFileAttachment(file, settings.StorageLocation) };
            }

            var result = dataAdapter.CreatePortalComment(portalComment);

            if (!result.PermissionsExist)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden,
                                                ResourceManager.GetString("Entity_Permissions_Have_Not_Been_Defined_Message")));
            }

            if (!result.CanCreate)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden,
                                                ResourceManager.GetString("No_Permissions_To_Create_Notes")));
            }

            if (!result.CanAppendTo)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden,
                                                ResourceManager.GetString("No_Permissions_To_Append_Record")));
            }

            if (!result.CanAppend)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden,
                                                ResourceManager.GetString("No_Permissions_To_Append_Notes")));
            }

            if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
            {
                PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Comments, this.HttpContext, "create_comment_" + regardingEntityLogicalName, 1, regarding, "create");
            }

            return(new HttpStatusCodeResult(HttpStatusCode.Created));
        }
Example #41
0
        protected override void TickCore(Entity host, RealmTime time, ref object state)
        {
            SwirlState s = (SwirlState)state;

            Status = CycleStatus.NotStarted;

            if (host.HasConditionEffect(ConditionEffects.Paralyzed))
            {
                return;
            }

            var period = (int)(1000 * radius / host.GetSpeed(speed) * (2 * Math.PI));

            if (!s.Acquired &&
                s.RemainingTime <= 0 &&
                targeted)
            {
                var entity = host.GetNearestEntity(acquireRange, null);
                if (entity != null && entity.X != host.X && entity.Y != host.Y)
                {
                    //find circle which pass through host and player pos
                    var l  = entity.Dist(host);
                    var hx = (host.X + entity.X) / 2;
                    var hy = (host.Y + entity.Y) / 2;
                    var c  = Math.Sqrt(Math.Abs(radius * radius - l * l) / 4);
                    s.Center = new Vector2(
                        (float)(hx + c * (host.Y - entity.Y) / l),
                        (float)(hy + c * (entity.X - host.X) / l));

                    s.RemainingTime = period;
                    s.Acquired      = true;
                }
                else
                {
                    s.Acquired = false;
                }
            }
            else if (s.RemainingTime <= 0 || (s.RemainingTime - period > 200 && host.GetNearestEntity(2, null) != null))
            {
                if (targeted)
                {
                    s.Acquired = false;
                    var entity = host.GetNearestEntity(acquireRange, null);
                    if (entity != null)
                    {
                        s.RemainingTime = 0;
                    }
                    else
                    {
                        s.RemainingTime = 5000;
                    }
                }
                else
                {
                    s.RemainingTime = 5000;
                }
            }
            else
            {
                s.RemainingTime -= time.thisTickTimes;
            }

            double angle;

            if (host.Y == s.Center.Y && host.X == s.Center.X)//small offset
            {
                angle = Math.Atan2(host.Y - s.Center.Y + (Random.NextDouble() * 2 - 1), host.X - s.Center.X + (Random.NextDouble() * 2 - 1));
            }
            else
            {
                angle = Math.Atan2(host.Y - s.Center.Y, host.X - s.Center.X);
            }

            var spd        = host.GetSpeed(speed) * (s.Acquired ? 1 : 0.2);
            var angularSpd = spd / radius;

            angle += angularSpd * (time.thisTickTimes / 1000f);

            double  x    = s.Center.X + Math.Cos(angle) * radius;
            double  y    = s.Center.Y + Math.Sin(angle) * radius;
            Vector2 vect = new Vector2((float)x, (float)y) - new Vector2(host.X, host.Y);

            vect.Normalize();
            vect *= (float)spd * (time.thisTickTimes / 1000f);

            host.ValidateAndMove(host.X + vect.X, host.Y + vect.Y);
            host.UpdateCount++;

            Status = CycleStatus.InProgress;

            state = s;
        }
Example #42
0
 public ArmsCore(Entity owner, Vector2 relativePosition, float rotation = 0, float[] savedPositions = null) : base(owner, relativePosition, rotation, savedPositions)
 {
     texture = Miasma.EntityExtras[22];
     origin = new Vector2(9.5f, 9.5f);
 }
Example #43
0
 public GainBlockAction(Entity entityToModify) : base(entityToModify)
 {
 }
    public void UpdatePath()
    {
        if (HasPath)
        {
            if (waypoint.Count > 0)
            {
                if (Time.time - PathEventTime > Global.instance.RepathInterval)
                {
                    PathEventTime = Time.time;
                    SetPath(DestinationPosition, OnPathEnd);
                }
                // follow path if waypoints exist
                Vector3 waypointFlat = waypointEnu.Current;
                waypointFlat.z = 0;
                if (Vector3.SqrMagnitude(transform.position - waypointFlat) > WaypointRadii * WaypointRadii)
                {
                    MoveDirection = (Vector2)waypointEnu.Current - (Vector2)transform.position;
                }
                else
                if (waypointEnu.MoveNext())
                {
                    MoveDirection = (Vector2)waypointEnu.Current - (Vector2)transform.position;
                }
                else
                {
                    // destination reached
                    // clear the waypoints before calling the callback because it may set another path and you do not want them to accumulate
                    waypoint.Clear();
#if UNITY_EDITOR
                    debugPath.Clear();
#endif
                    HasPath             = false;
                    DestinationPosition = transform.position;
                    // do this to allow OnPathEnd to become null because the callback may set another path without a callback.
                    System.Action temp = OnPathEnd;
                    OnPathEnd = null;
                    if (temp != null)
                    {
                        temp.Invoke();
                    }
                }

                //velocity = MoveDirection.normalized * speed;
            }

#if UNITY_EDITOR
            // draw path
            if (debugPath.Count > 0)
            {
                Color pathColor = Color.white;
                if (nvp.status == NavMeshPathStatus.PathInvalid)
                {
                    pathColor = Color.red;
                }
                if (nvp.status == NavMeshPathStatus.PathPartial)
                {
                    pathColor = Color.gray;
                }
                foreach (var ls in debugPath)
                {
                    Debug.DrawLine(ls.a, ls.b, pathColor);
                }
            }
#endif
        }
        else
        {
            // no path
            MoveDirection = Vector2.zero;
        }

        if (Global.instance.GlobalSidestepping && SidestepAvoidance)
        {
            if (Time.time - SidestepLast > Global.instance.SidestepInterval)
            {
                Sidestep     = Vector3.zero;
                SidestepLast = Time.time;
                if (MoveDirection.magnitude > 0.001f)
                {
                    float distanceToWaypoint = Vector3.Distance(waypointEnu.Current, transform.position);
                    if (distanceToWaypoint > Global.instance.SidestepIgnoreWithinDistanceToGoal)
                    {
                        float raycastDistance = Mathf.Min(distanceToWaypoint, Global.instance.SidestepRaycastDistance);
                        int   count           = Physics2D.CircleCastNonAlloc(transform.position, 0.5f /*box.edgeRadius*/, MoveDirection.normalized, RaycastHits, raycastDistance, Global.CharacterSidestepLayers);
                        for (int i = 0; i < count; i++)
                        {
                            Entity other = RaycastHits[i].transform.root.GetComponent <Entity>();
                            if (other != null && other != Client)
                            {
                                Vector3 delta = other.transform.position - transform.position;
                                Sidestep = ((transform.position + Vector3.Project(delta, MoveDirection.normalized)) - other.transform.position).normalized * Global.instance.SidestepDistance;
                                break;
                            }
                        }
                    }
                }
            }
            MoveDirection += Sidestep;
        }

#if UNITY_EDITOR
        Debug.DrawLine(transform.position, (Vector2)transform.position + MoveDirection.normalized * 0.5f, Color.magenta);
        //Debug.DrawLine( transform.position, transform.position + FaceDirection.normalized, Color.red );
#endif
    }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create an observation.
        /// </summary>

        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    Entity observation = new Entity("msemr_observation");

                    observation["msemr_identifier"]  = "OBS-123";
                    observation["msemr_comment"]     = "following Schedule";
                    observation["msemr_description"] = "Recovery is good";
                    observation["msemr_status"]      = new OptionSetValue(935000000);

                    //Setting Context Type as Encounter
                    observation["msemr_contexttype"] = new OptionSetValue(935000001); //Encounter
                    Guid EncounterId = Encounter.GetEncounterId(_serviceProxy, "E23556");
                    if (EncounterId != Guid.Empty)
                    {
                        observation["msemr_conexttypeencounter"] = new EntityReference("msemr_encounter", EncounterId);
                    }

                    //Setting Device Type as Device Metric
                    observation["msemr_devicetype"] = new OptionSetValue(935000001);
                    Guid DeviceMetricId = SDKFunctions.GetDeviceMetricId(_serviceProxy, "Device Metric");
                    if (DeviceMetricId != Guid.Empty)
                    {
                        observation["msemr_devicetypedevicemetric"] = new EntityReference("msemr_device", DeviceMetricId);
                    }

                    //Setting Effictive as DateTime
                    observation["msemr_effectivetype"]         = new OptionSetValue(935000000); //DateTime
                    observation["msemr_effectivetypedatetime"] = DateTime.Now;

                    //Setting Subject Type as Device
                    observation["msemr_subjecttype"] = new OptionSetValue(935000002);//Device
                    Guid SubjectTypeDevice = Device.GetDeviceId(_serviceProxy, "Pacemaker");
                    if (SubjectTypeDevice != Guid.Empty)
                    {
                        observation["msemr_subjecttypedevice"] = new EntityReference("msemr_device", SubjectTypeDevice);
                    }


                    //Setting Value Type as Range
                    observation["msemr_valuetype"]           = new OptionSetValue(935000004); //Range
                    observation["msemr_valuerangehighlimit"] = 10;
                    observation["msemr_valuerangelowlimit"]  = 1;


                    Guid BodySite = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Body Site", 100000000);
                    if (BodySite != Guid.Empty)
                    {
                        observation["msemr_bodysite"] = new EntityReference("msemr_codeableconcept", BodySite);
                    }
                    Guid Code = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Observation Name", 935000073);
                    if (Code != Guid.Empty)
                    {
                        observation["msemr_code"] = new EntityReference("msemr_codeableconcept", Code);
                    }

                    Guid EpisodeOfCareId = EpisodeOfCare.GetEpisodeOfCareId(_serviceProxy, "EPC-153");
                    if (EpisodeOfCareId != Guid.Empty)
                    {
                        observation["msemr_episodeofcare"] = new EntityReference("msemr_episodeofcare", EpisodeOfCareId);
                    }
                    Guid DataAbsentReason = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Absent Reason", 935000090);
                    if (DataAbsentReason != Guid.Empty)
                    {
                        observation["msemr_dataabsentreason"] = new EntityReference("msemr_codeableconcept", DataAbsentReason);
                    }
                    Guid DeviceId = Device.GetDeviceId(_serviceProxy, "MAGNETOM Sola");
                    if (DeviceId != Guid.Empty)
                    {
                        observation["msemr_device"] = new EntityReference("msemr_device", DeviceId);
                    }
                    Guid Interpretation = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Interpretation Code", 935000085);
                    if (Interpretation != Guid.Empty)
                    {
                        observation["msemr_interpretation"] = new EntityReference("msemr_codeableconcept", Interpretation);
                    }
                    observation["msemr_issueddate"] = DateTime.Now;
                    Guid Method = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Interpretation Code", 935000086);
                    if (Method != Guid.Empty)
                    {
                        observation["msemr_method"] = new EntityReference("msemr_codeableconcept", Method);
                    }
                    observation["msemr_observationnumber"] = "OBS-123";
                    Guid SpecimenId = SDKFunctions.GetSpecimenId(_serviceProxy, "SP-1234");
                    if (SpecimenId != Guid.Empty)
                    {
                        observation["msemr_specimen"] = new EntityReference("msemr_specimen", SpecimenId);
                    }


                    Guid ObservationId = _serviceProxy.Create(observation);

                    // Verify that the record has been created.
                    if (ObservationId != Guid.Empty)
                    {
                        Console.WriteLine("Succesfully created {0}.", ObservationId);
                    }
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Example #46
0
 public override RuneAction Clone(Entity otherEntity)
 {
     return(new GainBlockAction(otherEntity));
 }
Example #47
0
        //Created By: Leslie Baliguat, Created On: 7/7/2016
        /*Purpose: Replicate Disocunt Information to Quote Discount Form.
         * Registration Details:
         * Event/Message: 
         *      Create: 
         * Primary Entity: Quote Discount
         */
        public void ReplicateDiscountInformation(Entity quoteDiscountEntity, String message)
        {
            if (quoteDiscountEntity.GetAttributeValue<EntityReference>("gsc_pricelistid") != null)
            {
                _tracingService.Trace("Started ReplicateDiscountInformation method..");

                var quoteId = quoteDiscountEntity.GetAttributeValue<EntityReference>("gsc_quoteid")!= null
                    ? quoteDiscountEntity.GetAttributeValue<EntityReference>("gsc_quoteid").Id
                    : Guid.Empty;
                var discountId = quoteDiscountEntity.GetAttributeValue<EntityReference>("gsc_pricelistid") != null
                    ? quoteDiscountEntity.GetAttributeValue<EntityReference>("gsc_pricelistid").Id
                    : Guid.Empty;
                var product = new EntityReference();

                //Retrieve Porduct Associated in Quote 
                EntityCollection quoteRecords = CommonHandler.RetrieveRecordsByOneValue("quote", "quoteid", quoteId, _organizationService, null, OrderType.Ascending,
                new[] { "gsc_productid" });

                if (quoteRecords != null && quoteRecords.Entities.Count > 0)
                {
                    _tracingService.Trace("Retrieve Product Id..");

                    product = quoteRecords.Entities[0].GetAttributeValue<EntityReference>("gsc_productid");
                }

                //Check if Quote Record has Product associated in it. If none, throw an error.
                if (product == null)
                    throw new InvalidPluginExecutionException("Cannot associate discount. Vehicle is missing in Quotation Record.");

                //Retrieve Price List Selected
                EntityCollection priceListRecords = CommonHandler.RetrieveRecordsByOneValue("pricelevel", "pricelevelid", discountId, _organizationService, null, OrderType.Ascending,
                new[] { "description" });

                if (priceListRecords != null && priceListRecords.Entities.Count > 0)
                {
                    _tracingService.Trace("Retrieve Price List Details..");

                    var priceListEntity = priceListRecords.Entities[0];

                    var description = priceListEntity.Contains("description")
                        ? priceListEntity.GetAttributeValue<String>("description")
                        : String.Empty;

                    //Check if price list is applicable to Product, if not, throw an error.
                    var priceListItemConditionList = new List<ConditionExpression>
                            {
                                new ConditionExpression("pricelevelid", ConditionOperator.Equal, priceListEntity.Id),
                                new ConditionExpression("productid", ConditionOperator.Equal, product.Id)
                            };

                    EntityCollection priceListItemRecords = CommonHandler.RetrieveRecordsByConditions("productpricelevel", priceListItemConditionList, _organizationService,
                         null, OrderType.Ascending, new[] { "productid", "amount"});

                    if (priceListItemRecords != null && priceListItemRecords.Entities.Count > 0)
                    {
                        _tracingService.Trace("Retrieve Price List Item Details..");

                        var priceListItemEntity = priceListItemRecords.Entities[0];

                        var discount = priceListItemEntity.Contains("amount")
                                ? priceListItemEntity.GetAttributeValue<Money>("amount")
                                : new Money(0);

                        quoteDiscountEntity["gsc_discountamount"] = discount;
                        quoteDiscountEntity["gsc_description"] = description;

                        if (message.Equals("Update"))
                        {
                            Entity quoteDiscountToUpdate = _organizationService.Retrieve(quoteDiscountEntity.LogicalName, quoteDiscountEntity.Id,
                                new ColumnSet("gsc_discountamount", "gsc_description", "gsc_quotediscountpn"));
                            quoteDiscountToUpdate["gsc_discountamount"] = discount;
                            quoteDiscountToUpdate["gsc_description"] = description;
                            _organizationService.Update(quoteDiscountToUpdate);
                        }

                        _tracingService.Trace("Quote Information Updated..");

                    }
                    else
                    {
                        throw new InvalidPluginExecutionException("The promo selected is not applicable for the vehicle of this quote.");
                    }

                }

                _tracingService.Trace("Ended ReplicateDiscountInformation method..");
            }
        }
Example #48
0
        private static string WriteTestFileText(string solutionDirectory, ClassPath classPath, Entity entity, string projectBaseName)
        {
            var featureName               = Utilities.UpdateEntityFeatureClassName(entity.Name);
            var testFixtureName           = Utilities.GetIntegrationTestFixtureName();
            var commandName               = Utilities.CommandUpdateName(entity.Name);
            var fakeEntity                = Utilities.FakerName(entity.Name);
            var fakeUpdateDto             = Utilities.FakerName(Utilities.GetDtoName(entity.Name, Dto.Update));
            var updateDto                 = Utilities.GetDtoName(entity.Name, Dto.Update);
            var fakeEntityVariableName    = $"fake{entity.Name}One";
            var lowercaseEntityName       = entity.Name.LowercaseFirstLetter();
            var lowercaseEntityPluralName = entity.Plural.LowercaseFirstLetter();
            var pkName            = Entity.PrimaryKeyProperty.Name;
            var lowercaseEntityPk = pkName.LowercaseFirstLetter();

            var testUtilClassPath = ClassPathHelper.IntegrationTestUtilitiesClassPath(solutionDirectory, projectBaseName, "");
            var fakerClassPath    = ClassPathHelper.TestFakesClassPath(solutionDirectory, "", entity.Name, projectBaseName);
            var dtoClassPath      = ClassPathHelper.DtoClassPath(solutionDirectory, "", entity.Name, projectBaseName);
            var featuresClassPath = ClassPathHelper.FeaturesClassPath(solutionDirectory, featureName, entity.Plural, projectBaseName);

            var myProp    = entity.Properties.Where(e => e.Type == "string" && e.CanManipulate).FirstOrDefault();
            var lookupVal = $@"""Easily Identified Value For Test""";

            // if no string properties, do one with an int
            if (myProp == null)
            {
                myProp    = entity.Properties.Where(e => e.Type.Contains("int") && e.CanManipulate).FirstOrDefault();
                lookupVal = "999999";
            }

            return(@$ "namespace {classPath.ClassNamespace};

using {fakerClassPath.ClassNamespace};
using {testUtilClassPath.ClassNamespace};
using {dtoClassPath.ClassNamespace};
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using System.Threading.Tasks;
using Microsoft.AspNetCore.JsonPatch;
using {featuresClassPath.ClassNamespace};
using static {testFixtureName};
Example #49
0
        public static void HandleMessage(Entity parent, string text, string name, ushort hue, MessageType type, byte font, TEXT_TYPE text_type, bool unicode = false, string lang = null)
        {
            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            if (ProfileManager.Current != null && ProfileManager.Current.OverrideAllFonts)
            {
                font    = ProfileManager.Current.ChatFont;
                unicode = ProfileManager.Current.OverrideAllFontsIsUnicode;
            }

            switch (type)
            {
            case MessageType.Spell:

            {
                //server hue color per default
                if (!string.IsNullOrEmpty(text) && SpellDefinition.WordToTargettype.TryGetValue(text, out SpellDefinition spell))
                {
                    if (ProfileManager.Current != null && ProfileManager.Current.EnabledSpellFormat && !string.IsNullOrWhiteSpace(ProfileManager.Current.SpellDisplayFormat))
                    {
                        StringBuilder sb = new StringBuilder(ProfileManager.Current.SpellDisplayFormat);
                        sb.Replace("{power}", spell.PowerWords);
                        sb.Replace("{spell}", spell.Name);
                        text = sb.ToString().Trim();
                    }

                    //server hue color per default if not enabled
                    if (ProfileManager.Current != null && ProfileManager.Current.EnabledSpellHue)
                    {
                        if (spell.TargetType == TargetType.Beneficial)
                        {
                            hue = ProfileManager.Current.BeneficHue;
                        }
                        else if (spell.TargetType == TargetType.Harmful)
                        {
                            hue = ProfileManager.Current.HarmfulHue;
                        }
                        else
                        {
                            hue = ProfileManager.Current.NeutralHue;
                        }
                    }
                }

                goto case MessageType.Label;
            }

            case MessageType.Focus:
            case MessageType.Whisper:
            case MessageType.Yell:
            case MessageType.Regular:
            case MessageType.Label:
            case MessageType.Limit3Spell:

                if (parent == null)
                {
                    break;
                }

                TextObject msg = CreateMessage(text, hue, font, unicode, type);
                msg.Owner = parent;

                if (parent is Item it && !it.OnGround)
                {
                    msg.X          = DelayedObjectClickManager.X;
                    msg.Y          = DelayedObjectClickManager.Y;
                    msg.IsTextGump = true;
                    bool found = false;

                    for (var gump = UIManager.Gumps.Last; gump != null; gump = gump.Previous)
                    {
                        var g = gump.Value;

                        if (!g.IsDisposed)
                        {
                            switch (g)
                            {
                            case PaperDollGump paperDoll when g.LocalSerial == it.Container:
                                paperDoll.AddText(msg);
                                found = true;
                                break;

                            case ContainerGump container when g.LocalSerial == it.Container:
                                container.AddText(msg);
                                found = true;
                                break;

                            case TradingGump trade when g.LocalSerial == it.Container || trade.ID1 == it.Container || trade.ID2 == it.Container:
                                trade.AddText(msg);
                                found = true;
                                break;
                            }
                        }

                        if (found)
                        {
                            break;
                        }
                    }
                }

                parent.AddMessage(msg);

                break;


            case MessageType.Command:
            case MessageType.Encoded:
            case MessageType.System:
            case MessageType.Party:
            case MessageType.Guild:
            case MessageType.Alliance:

                break;

            default:
                if (parent == null)
                {
                    break;
                }

                parent.AddMessage(type, text, font, hue, unicode);

                break;
            }

            MessageReceived.Raise(new UOMessageEventArgs(parent, text, name, hue, type, font, text_type, unicode, lang), parent);
        }
Example #50
0
        public static async ETTask Transfer(Unit unit, long sceneInstanceId, string sceneName)
        {
            // 通知客户端开始切场景
            M2C_StartSceneChange m2CStartSceneChange = new M2C_StartSceneChange()
            {
                SceneInstanceId = sceneInstanceId, SceneName = sceneName
            };

            MessageHelper.SendToClient(unit, m2CStartSceneChange);

            M2M_UnitTransferRequest request = new M2M_UnitTransferRequest();
            ListComponent <int>     Stack   = ListComponent <int> .Create();

            request.Unit = unit;
            Entity curEntity = unit;

            Stack.Add(-1);
            while (Stack.Count > 0)
            {
                var index = Stack[Stack.Count - 1];
                if (index != -1)
                {
                    curEntity = request.Entitys[index];
                }
                Stack.RemoveAt(Stack.Count - 1);
                foreach (Entity entity in curEntity.Components.Values)
                {
                    if (entity is ITransfer)
                    {
                        var childIndex = request.Entitys.Count;
                        request.Entitys.Add(entity);
                        Stack.Add(childIndex);
                        request.Map.Add(new RecursiveEntitys
                        {
                            ChildIndex  = childIndex,
                            ParentIndex = index,
                            IsChild     = 0
                        });
                    }
                }
                foreach (Entity entity in curEntity.Children.Values)
                {
                    if (entity is ITransfer)
                    {
                        var childIndex = request.Entitys.Count;
                        request.Entitys.Add(entity);
                        Stack.Add(childIndex);
                        request.Map.Add(new RecursiveEntitys
                        {
                            ChildIndex  = childIndex,
                            ParentIndex = index,
                            IsChild     = 1
                        });
                    }
                }
            }
            Stack.Dispose();
            // 删除Mailbox,让发给Unit的ActorLocation消息重发
            unit.RemoveComponent <MailBoxComponent>();

            // location加锁
            long oldInstanceId = unit.InstanceId;
            await LocationProxyComponent.Instance.Lock(unit.Id, unit.InstanceId);

            M2M_UnitTransferResponse response = await ActorMessageSenderComponent.Instance.Call(sceneInstanceId, request) as M2M_UnitTransferResponse;

            await LocationProxyComponent.Instance.UnLock(unit.Id, oldInstanceId, response.NewInstanceId);

            unit.Dispose();
        }
 public object FirstNotNull(string attributeName, Entity entity, Entity image)
 {
     return(entity != null && entity.Contains(attributeName) ? entity[attributeName] : image != null && image.Contains(attributeName) ? image[attributeName] : null);
 }
Example #52
0
        //Created By : Jerome Anthony Gerero, Created On : 3/11/2016
        public Entity SetQuoteTotalDiscountAmount(Entity quoteDiscountEntity, String message)
        {
            _tracingService.Trace("Started SetQuoteTotalDiscountAmount method..");

            Decimal totalDiscountAmount = 0;
            Decimal totalDPAmount = 0;
            Decimal totalAFAmount = 0;
            Decimal totalUPAmount = 0;

            var quoteId = quoteDiscountEntity.GetAttributeValue<EntityReference>("gsc_quoteid") != null
                ? quoteDiscountEntity.GetAttributeValue<EntityReference>("gsc_quoteid").Id
                : Guid.Empty;

            //Retrieve Applied Price List records with the same Quote
            EntityCollection quoteDiscountRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_cmn_quotediscount", "gsc_quoteid", quoteId, _organizationService, null, 
                OrderType.Ascending, new[] { "gsc_discountamount", "gsc_applypercentagetodp", "gsc_applyamounttodp", "gsc_applypercentagetoaf", "gsc_applyamounttoaf", "gsc_applypercentagetoup", "gsc_applyamounttoup" });

            _tracingService.Trace("Quote Discount Records Retrieved: " + quoteDiscountRecords.Entities.Count);

            if (quoteDiscountRecords != null && quoteDiscountRecords.Entities.Count > 0)
            {

                //Compute for Total Discount Amount from all retrieved Quote records
                foreach (var appliedPriceList in quoteDiscountRecords.Entities)
                {
                    _tracingService.Trace("Add Created/Updated Discount Amount in Quote..");

                    totalDiscountAmount += appliedPriceList.Contains("gsc_discountamount")
                        ? appliedPriceList.GetAttributeValue<Money>("gsc_discountamount").Value
                        : Decimal.Zero;

                    totalDPAmount += appliedPriceList.Contains("gsc_applyamounttodp")
                        ? appliedPriceList.GetAttributeValue<Money>("gsc_applyamounttodp").Value
                        : Decimal.Zero;

                    totalAFAmount += appliedPriceList.Contains("gsc_applyamounttoaf")
                        ? appliedPriceList.GetAttributeValue<Money>("gsc_applyamounttoaf").Value
                        : Decimal.Zero;

                    totalUPAmount += appliedPriceList.Contains("gsc_applyamounttoup")
                        ? appliedPriceList.GetAttributeValue<Money>("gsc_applyamounttoup").Value
                        : Decimal.Zero;
                }

                if (quoteDiscountEntity.Contains("gsc_discountamount") && message.Equals("Delete"))
                {
                    _tracingService.Trace("Subtract Deleted Discount from Total Discount...");

                    totalDiscountAmount = totalDiscountAmount - (Decimal)quoteDiscountEntity.GetAttributeValue<Money>("gsc_discountamount").Value;

                    totalDPAmount = totalDPAmount - (quoteDiscountEntity.Contains("gsc_applyamounttodp") 
                    ? quoteDiscountEntity.GetAttributeValue<Money>("gsc_applyamounttodp").Value
                    : 0);

                    totalAFAmount = totalAFAmount -  (quoteDiscountEntity.Contains("gsc_applyamounttoaf") 
                    ? quoteDiscountEntity.GetAttributeValue<Money>("gsc_applyamounttoaf").Value
                    : 0);

                    totalUPAmount = totalUPAmount - (quoteDiscountEntity.Contains("gsc_applyamounttoaf") 
                    ? quoteDiscountEntity.GetAttributeValue<Money>("gsc_applyamounttoup").Value
                    : 0);
                }
            }


            //Retrieve Quote record from Quote field value
            EntityCollection quoteRecords = CommonHandler.RetrieveRecordsByOneValue("quote", "quoteid", quoteId, _organizationService, null, OrderType.Ascending,
                new[] { "totaldiscountamount", "gsc_applytodppercentage", "gsc_applytodpamount", "gsc_applytoafpercentage", "gsc_applytoafamount", 
                    "gsc_applytouppercentage", "gsc_applytoupamount", "statecode" });

            if (quoteRecords != null && quoteRecords.Entities.Count > 0 && quoteRecords.Entities[0].GetAttributeValue<OptionSetValue>("statecode").Value == 0)
            {
                _tracingService.Trace("Setting Up Quote to be Updated . . . ");

                Entity quotetoUpdate = quoteRecords.Entities[0];

                quotetoUpdate["totaldiscountamount"] = new Money(totalDiscountAmount);
                quotetoUpdate["gsc_applytodpamount"] = new Money(totalDPAmount);
                quotetoUpdate["gsc_applytoafamount"] = new Money(totalAFAmount);
                quotetoUpdate["gsc_applytoupamount"] = new Money(totalUPAmount);
                quotetoUpdate["gsc_applytodppercentage"] = ComputePercentage(totalDPAmount, totalDiscountAmount);
                quotetoUpdate["gsc_applytoafpercentage"] = ComputePercentage(totalAFAmount, totalDiscountAmount);
                quotetoUpdate["gsc_applytouppercentage"] = ComputePercentage(totalUPAmount, totalDiscountAmount);

                _organizationService.Update(quotetoUpdate);

                _tracingService.Trace("Updated Discounts Amount in Quote..");
                return quotetoUpdate;
            }

            _tracingService.Trace("Ended SetQuoteTotalDiscountAmount method..");

            return quoteDiscountEntity;
        }
 public virtual void PreWinOpportunity(Entity opportunity, ConnectionHelper helper)
 {
 }
Example #54
0
 public static void OnLocalizedMessage(Entity entity, UOMessageEventArgs args)
 {
     LocalizedMessageReceived.Raise(args, entity);
 }
 public virtual void PostCreate(Entity entity, ConnectionHelper helper)
 {
 }
 public virtual void PostLoseOpportunity(Entity opportunity, ConnectionHelper helper)
 {
 }
 public virtual void PrevalidateUpdate(Entity entity, ConnectionHelper ch)
 {
 }
 public virtual void PreUpdate(Entity entity, ConnectionHelper helper)
 {
 }
        public void Execute(IServiceProvider serviceProvider)
        {
            ConnectionHelper ch = new ConnectionHelper(serviceProvider);

            ch.Messages = new List <string>();

            try
            {
                #region EntityMessage

                Entity entity;

                if (ch.PluginExecutionContext.InputParameters.Contains("Target") &&
                    ch.PluginExecutionContext.InputParameters["Target"] is Entity)
                {
                    entity = ch.PluginExecutionContext.InputParameters["Target"] as Entity;
                    if (ch.PluginExecutionContext.Stage == 10 && ch.PluginExecutionContext.MessageName == "Create")
                    {
                        PrevalidateCreate(entity, ch);
                    }
                    if (ch.PluginExecutionContext.Stage == 40 && ch.PluginExecutionContext.MessageName == "Create")
                    {
                        PostCreate(entity, ch);
                    }
                    if (ch.PluginExecutionContext.Stage == 40 && ch.PluginExecutionContext.MessageName == "Update")
                    {
                        PostUpdate(entity, ch);
                    }
                    if (ch.PluginExecutionContext.Stage == 20 && ch.PluginExecutionContext.MessageName == "Create")
                    {
                        PreCreate(entity, ch);
                    }
                    if (ch.PluginExecutionContext.Stage == 20 && ch.PluginExecutionContext.MessageName == "Update")
                    {
                        PreUpdate(entity, ch);
                    }
                    if (ch.PluginExecutionContext.Stage == 10 && ch.PluginExecutionContext.MessageName == "Update")
                    {
                        PrevalidateUpdate(entity, ch);
                    }
                }

                if (ch.PluginExecutionContext.InputParameters.Contains("Target") &&
                    ch.PluginExecutionContext.InputParameters["Target"] is EntityReference)
                {
                    EntityReference target = ch.PluginExecutionContext.InputParameters["Target"] as EntityReference;
                    ;
                    if (ch.PluginExecutionContext.Stage > 30 && ch.PluginExecutionContext.MessageName == "Delete")
                    {
                        PostDelete(target, ch);
                    }
                    if (ch.PluginExecutionContext.Stage < 30 && ch.PluginExecutionContext.MessageName == "Delete")
                    {
                        PreDelete(target, ch);
                    }
                }

                if (ch.PluginExecutionContext.Stage < 30 && ch.PluginExecutionContext.MessageName == "RetrieveMultiple")
                {
                    PreRetrieveMultiple();
                }
                if (ch.PluginExecutionContext.Stage > 30 && ch.PluginExecutionContext.MessageName == "RetrieveMultiple")
                {
                    PostRetrieveMultiple();
                }

                #endregion

                #region EntityReferenceMessage

                EntityReference moniker;
                if (ch.PluginExecutionContext.InputParameters.Contains("EntityMoniker") &&
                    ch.PluginExecutionContext.InputParameters["EntityMoniker"] is EntityReference)
                {
                    moniker = ch.PluginExecutionContext.InputParameters["EntityMoniker"] as EntityReference;

                    if (ch.PluginExecutionContext.Stage > 30 && (ch.PluginExecutionContext.MessageName == "SetState" || ch.PluginExecutionContext.MessageName == "SetStateDynamicEntity"))
                    {
                        PostSetSate(moniker, ch);
                    }
                    if (ch.PluginExecutionContext.Stage > 30 && ch.PluginExecutionContext.MessageName == "Assign")
                    {
                        PostAssign(moniker, ch);
                    }
                    if (ch.PluginExecutionContext.Stage < 30 && (ch.PluginExecutionContext.MessageName == "SetState" || ch.PluginExecutionContext.MessageName == "SetStateDynamicEntity"))
                    {
                        PreSetState(moniker, ch);
                    }
                    if (ch.PluginExecutionContext.Stage < 30 && ch.PluginExecutionContext.MessageName == "Assign")
                    {
                        PreAssign(moniker, ch);
                    }
                }

                if (ch.PluginExecutionContext.InputParameters.Contains("RelatedEntities") &&
                    ch.PluginExecutionContext.InputParameters["RelatedEntities"] is EntityReferenceCollection &&
                    ch.PluginExecutionContext.InputParameters.Contains("Target") &&
                    ch.PluginExecutionContext.InputParameters["Target"] is EntityReference)
                {
                    EntityReferenceCollection relatedEntities = (EntityReferenceCollection)ch.PluginExecutionContext.InputParameters["RelatedEntities"];
                    moniker = (EntityReference)ch.PluginExecutionContext.InputParameters["Target"];

                    if (ch.PluginExecutionContext.Stage > 30 && (ch.PluginExecutionContext.MessageName == "Associate"))
                    {
                        PostAssociate(relatedEntities, moniker, ch);
                    }
                    if (ch.PluginExecutionContext.Stage > 30 && (ch.PluginExecutionContext.MessageName == "Disassociate"))
                    {
                        PostDisassociate(relatedEntities, moniker, ch);
                    }
                }

                #endregion

                #region OpportunityMessages

                if (ch.PluginExecutionContext.InputParameters.Contains("OpportunityClose") &&
                    ch.PluginExecutionContext.InputParameters["OpportunityClose"] is Entity)
                {
                    Entity target = ch.PluginExecutionContext.InputParameters["OpportunityClose"] as Entity;
                    if (ch.PluginExecutionContext.Stage > 30 && ch.PluginExecutionContext.MessageName == "Lose")
                    {
                        PostLoseOpportunity(target, ch);
                    }
                    if (ch.PluginExecutionContext.Stage < 30 && ch.PluginExecutionContext.MessageName == "Lose")
                    {
                        PreLoseOpportunity(target, ch);
                    }
                    if (ch.PluginExecutionContext.Stage > 30 && ch.PluginExecutionContext.MessageName == "Win")
                    {
                        PostWinOpportunity(target, ch);
                    }
                    if (ch.PluginExecutionContext.Stage < 30 && ch.PluginExecutionContext.MessageName == "Win")
                    {
                        PreWinOpportunity(target, ch);
                    }
                }

                #endregion

                #region MarketingListMessages
                if (ch.PluginExecutionContext.InputParameters.Contains("ListId") &&
                    ch.PluginExecutionContext.InputParameters["ListId"] is Guid &&
                    ch.PluginExecutionContext.InputParameters.Contains("EntityId") &&
                    ch.PluginExecutionContext.InputParameters["EntityId"] is Guid)
                {
                    var mkList = (Guid)ch.PluginExecutionContext.InputParameters["ListId"];
                    var member = (Guid)ch.PluginExecutionContext.InputParameters["EntityId"];

                    if (ch.PluginExecutionContext.Stage > 30 && (ch.PluginExecutionContext.MessageName == "AddMember"))
                    {
                        PostAddMember(mkList, member, ch);
                    }
                    if (ch.PluginExecutionContext.Stage > 30 && (ch.PluginExecutionContext.MessageName == "RemoveMember"))
                    {
                        PostRemoveMember(mkList, member, ch);
                    }
                }

                if (ch.PluginExecutionContext.MessageName == "AddListMembers" &&
                    ch.PluginExecutionContext.InputParameters.Contains("ListId") &&
                    ch.PluginExecutionContext.InputParameters.Contains("MemberIds"))
                {
                    var mkList  = (Guid)ch.PluginExecutionContext.InputParameters["ListId"];
                    var members = (Guid[])ch.PluginExecutionContext.InputParameters["MemberIds"];

                    if (ch.PluginExecutionContext.Stage > 30)
                    {
                        PostAddListMembers(mkList, members, ch);
                    }
                }
                else if (ch.PluginExecutionContext.MessageName == "Update" && ch.PluginExecutionContext.ParentContext != null &&
                         ch.PluginExecutionContext.ParentContext.MessageName == "AddListMembers" &&
                         ch.PluginExecutionContext.ParentContext.InputParameters.Contains("ListId") &&
                         ch.PluginExecutionContext.ParentContext.InputParameters.Contains("MemberIds"))
                {
                    var mkList  = (Guid)ch.PluginExecutionContext.ParentContext.InputParameters["ListId"];
                    var members = (Guid[])ch.PluginExecutionContext.ParentContext.InputParameters["MemberIds"];

                    if (ch.PluginExecutionContext.ParentContext.Stage > 30)
                    {
                        PostAddListMembers(mkList, members, ch);
                    }
                    if (ch.PluginExecutionContext.ParentContext.Stage < 30)
                    {
                        PreAddListMembers(mkList, members, ch);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                #region Exception handling
                string errorMessage = ex.Message;
                string traceText    = string.Empty;
                ch.TracingService.Trace("Context Depth: " + ch.PluginExecutionContext.Depth);
                if (!ch.ThrowError)
                {
                    ch.Messages.Add("CatchBase");
                    ch.Messages.Add("BaseException: " + ex.Message);
                }

                IEnumerator enumer = ch.Messages.GetEnumerator();
                while (enumer.MoveNext())
                {
                    string value = enumer.Current.ToString();
                    traceText += Environment.NewLine + "-" + value;
                    ch.TracingService.Trace(value);
                }

                if (!ch.ThrowError)
                {
                    ch.TracingService.Trace(ex.Message);
                    ch.TracingService.Trace(ex.StackTrace);
                    throw new Exception("An exception has occured. Please see the trace log for further information.",
                                        ex);
                }
                else
                {
                    ch.TracingService.Trace(ex.Message);
                    ch.TracingService.Trace(ex.StackTrace);
                    ch.TracingService.Trace(traceText);

                    throw new InvalidPluginExecutionException(ex.Message);
                }
                #endregion
            }
        }
 public virtual void PrevalidateCreate(Entity entity, ConnectionHelper helper)
 {
 }