コード例 #1
0
        private IfRangeHeader(EntityTag entityTag, DateTime? httpDate)
        {
            if (entityTag == null && httpDate == null)
            {
                throw new ArgumentException("ETag and http-date cannot both be null.");
            }

            _entityTag = entityTag;
            _httpDate = httpDate;
        }
コード例 #2
0
        public async Task PreconditionIfRangeIgnoreEtagEmptyTest()
        {
            // Arrange
            Client.DefaultRequestHeaders.Add("Range", "bytes=1-1");
            Client.DefaultRequestHeaders.Add("If-Range", EntityTag.ToString());

            // Act
            HttpResponseMessage response = await Client.GetAsync("/file/physical/true/false");

            response.EnsureSuccessStatusCode();

            string responseString = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
            Assert.Equal("1", responseString);
            Assert.Equal("bytes", response.Headers.AcceptRanges.ToString());
            Assert.Null(response.Headers.ETag);
        }
コード例 #3
0
 public ResourceResult <TResource> GetResource(
     TKey key,
     EntityTag requestETag   = null,
     string requestUri       = null,
     WebContentFormat format = WebContentFormat.Xml,
     bool trailingSlash      = false
     )
 {
     return(SendRequest(
                "GET",
                new Uri((requestUri ?? ServiceUri) + key.ToString() + (trailingSlash ? "/" : string.Empty)),
                format,
                beforeRequest: (request) =>
     {
         if (requestETag != null)
         {
             request.Headers.IfNoneMatch.Add(requestETag);
         }
     }));
 }
コード例 #4
0
        public async Task PreconditionIfMatchSuccessTest()
        {
            // Arrange
            Client.DefaultRequestHeaders.Add("If-Match", EntityTag.ToString());

            // Act
            HttpResponseMessage response = await Client.GetAsync("/file/physical/true/true");

            response.EnsureSuccessStatusCode();

            string responseString = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("0123456789abcdefghijklmnopgrstuvwxyzABCDEFGHIJKLMNOPGRSTUVWXYZ", responseString);
            Assert.Equal("bytes", response.Headers.AcceptRanges.ToString());
            Assert.Equal(EntityTag, response.Headers.ETag);
            Assert.Null(response.Content.Headers.ContentRange);
            Assert.Equal("attachment", response.Content.Headers.ContentDisposition.DispositionType);
        }
コード例 #5
0
        public async Task PreconditionIfMatchFailWeakTest()
        {
            // Arrange
            string entityTag       = EntityTag.ToString();
            var    tmpNewEntityTag = new EntityTagHeaderValue(entityTag, true);

            Client.DefaultRequestHeaders.Add("If-Match", tmpNewEntityTag.ToString());

            // Act
            HttpResponseMessage response = await Client.GetAsync("/file/physical/true/true");

            string responseString = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.PreconditionFailed, response.StatusCode);
            Assert.Equal(string.Empty, responseString);
            Assert.NotEqual("bytes", response.Headers.AcceptRanges.ToString());
            Assert.Equal(EntityTag, response.Headers.ETag);
            Assert.Null(response.Content.Headers.ContentRange);
        }
コード例 #6
0
        /// <summary>
        /// Creates a new collection
        /// </summary>
        /// <param name="name">The name of the collection to create</param>
        /// <returns>The created collection</returns>
        /// <exception cref="UnauthorizedAccessException">The file system is read-only</exception>
        /// <exception cref="IOException">Document or collection with the same name already exists</exception>
        public BinsyncDirectory CreateCollection(string name)
        {
            if (BinsyncFS.IsReadOnly)
            {
                throw new UnauthorizedAccessException("Failed to modify a read-only file system");
            }

            checkName(name);

            ETag = new EntityTag(false);

            var engine = Program.BinsyncEngine;
            var next   = _isRoot ? "" : System.Net.WebUtility.UrlDecode(this.Path.ToString());

            if (next.Length > 0 && next.Substring(next.Length - 1, 1) == "/")
            {
                next = next.Substring(0, next.Length - 1);
            }
            next = next + "/" + name;
            if (next.Length > 0 && next.Substring(next.Length - 1, 1) == "/")
            {
                next = next.Substring(0, next.Length - 1);
            }
            next = "/" + next;

            engine.NewDirectory(next).Wait();
            return(new BinsyncDirectory(BinsyncFS, this, Path.AppendDirectory(name), name));

            //throw new NotImplementedException();

            /*
             * if (BinsyncFS.IsReadOnly)
             *      throw new UnauthorizedAccessException("Failed to modify a read-only file system");
             * if (_children.ContainsKey(name))
             *      throw new IOException("Document or collection with the same name already exists");
             * var newItem = new BinsyncDirectory(BinsyncFS, this, Path.AppendDirectory(name), name);
             * _children.Add(newItem.Name, newItem);
             * ETag = new EntityTag(false);
             * return newItem;
             */
        }
コード例 #7
0
        /// <inheritdoc />
        protected override Task <EntityTag> UpdateDeadETagAsync(IEntry entry, CancellationToken cancellationToken)
        {
            var       storeData = Load(entry, false, cancellationToken);
            var       entryKey  = GetEntryKey(entry);
            EntryInfo info;

            if (!storeData.Entries.TryGetValue(entryKey, out info))
            {
                info = new EntryInfo();
                storeData.Entries.Add(entryKey, info);
            }

            var etag        = new EntityTag(false);
            var etagElement = etag.ToXml();

            info.Attributes[_etagKey] = etagElement;

            Save(entry, storeData, cancellationToken);

            return(Task.FromResult(etag));
        }
コード例 #8
0
        public async Task PreconditionIfRangeIgnoreWeakEtagTest()
        {
            // Arrange
            var tmpNewEntityTag = new EntityTagHeaderValue(EntityTag.ToString(), true);

            Client.DefaultRequestHeaders.Add("Range", "bytes=1-1");
            Client.DefaultRequestHeaders.Add("If-Range", tmpNewEntityTag.ToString());

            // Act
            HttpResponseMessage response = await Client.GetAsync("/file/physical/true/true");

            response.EnsureSuccessStatusCode();

            string responseString = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("0123456789abcdefghijklmnopgrstuvwxyzABCDEFGHIJKLMNOPGRSTUVWXYZ", responseString);
            Assert.Equal("bytes", response.Headers.AcceptRanges.ToString());
            Assert.Equal(EntityTag, response.Headers.ETag);
            Assert.Null(response.Content.Headers.ContentRange);
        }
コード例 #9
0
        /// <inheritdoc />
        protected override Task <EntityTag> UpdateDeadETagAsync(IEntry entry, CancellationToken cancellationToken)
        {
            var etag        = EntityTag.FromXml(null);
            var etagElement = etag.ToXml();
            var key         = etagElement.Name;

            IDictionary <XName, XElement> properties;

            if (!_properties.TryGetValue(entry.Path, out properties))
            {
                _properties.Add(entry.Path, new Dictionary <XName, XElement>()
                {
                    [key] = etagElement,
                });
            }
            else
            {
                properties[key] = etagElement;
            }

            return(Task.FromResult(etag));
        }
コード例 #10
0
        /// <summary>
        /// Creates a document
        /// </summary>
        /// <param name="name">The name of the document to create</param>
        /// <returns>The created document</returns>
        /// <exception cref="UnauthorizedAccessException">The file system is read-only</exception>
        /// <exception cref="IOException">Document or collection with the same name already exists</exception>
        public BinsyncFile CreateDocument(string name)
        {
            if (BinsyncFS.IsReadOnly)
            {
                throw new UnauthorizedAccessException("Failed to modify a read-only file system");
            }

            checkName(name);

            ETag = new EntityTag(false);
            return(new BinsyncFile(BinsyncFS, this, Path.Append(name, false), name));



            //throw new NotImplementedException();

            /*if (_children.ContainsKey(name))
             * throw new IOException("Document or collection with the same name already exists");
             * var newItem = new BinsyncFile(BinsyncFS, this, Path.Append(name, false), name);
             * _children.Add(newItem.Name, newItem);
             * ETag = new EntityTag(false);
             * return newItem;*/
        }
コード例 #11
0
 public void StartPolling(Uri uri, EntityTag etag, DateTime?lastModifiedTime)
 {
     if (this.HttpClient == null)
     {
         throw new InvalidOperationException("The http client to use for polling is not specified.");
     }
     lock (thisLock)
     {
         if (this.isBusy)
         {
             throw new InvalidOperationException("Polling has already started");
         }
         this.isBusy = true;
     }
     this.uri              = uri ?? this.HttpClient.BaseAddress;
     this.etag             = etag;
     this.lastModifiedTime = lastModifiedTime;
     this.timer            = new Timer(this.PollingInterval.TotalMilliseconds);
     this.timer.AutoReset  = true;
     this.syncContext      = SynchronizationContext.Current;
     this.timer.Elapsed   += this.TimerElapsed;
     this.timer.Enabled    = true;
     this.timer.Start();
 }
コード例 #12
0
        /// <summary>
        /// The check conditional update.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="resource">
        /// The resource.
        /// </param>
        /// <exception cref="HttpResponseException">
        /// The precondition failed
        /// </exception>
        private static void CheckIfMatch(HttpRequestMessage request, Sample resource)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (resource == null)
            {
                throw new ArgumentNullException("resource");
            }

            // No etags
            if (request.Headers.IfMatch.Count == 0)
            {
                return;
            }

            // If there is no matching etag, the pre-condition fails
            if (!request.Headers.IfMatch.Any(etag => EntityTag.IsMatchingTag(resource.Tag, etag.Tag)))
            {
                throw new HttpResponseException(HttpStatusCode.PreconditionFailed);
            }
        }
コード例 #13
0
ファイル: EntityTag.Facts.cs プロジェクト: KarlDirck/cavity
        public void prop_Null()
        {
            var expected = new EntityTag();
            var actual = EntityTag.Null;

            Assert.Equal(expected, actual);
        }
コード例 #14
0
ファイル: EntityTag.Facts.cs プロジェクト: KarlDirck/cavity
        public void op_ToString()
        {
            const string expected = _jigsawEtag;
            var actual = new EntityTag(_jigsawEtag).ToString();

            Assert.Equal(expected, actual);
        }
コード例 #15
0
ファイル: EntityTag.Facts.cs プロジェクト: KarlDirck/cavity
        public void op_GetHashCode()
        {
            var expected = _jigsawEtag.GetHashCode();
            var actual = new EntityTag(_jigsawEtag).GetHashCode();

            Assert.Equal(expected, actual);
        }
コード例 #16
0
ファイル: EntityTag.Facts.cs プロジェクト: KarlDirck/cavity
        public void opEquality_EntityTag_EntityTag()
        {
            var obj = new EntityTag();
            var comparand = new EntityTag();

            Assert.True(obj == comparand);
        }
コード例 #17
0
        public override GameObject GetGameObject()
        {
            GameObject prefab = GameObject.Instantiate(this.GameObject);

            prefab.name = this.ClassID;

            // Translate
            foreach (Transform tr in prefab.transform)
            {
                tr.localPosition = new Vector3(tr.localPosition.x, tr.localPosition.y + 0.25f, tr.localPosition.z);
            }

            // Update TechTag
            var techTag = prefab.GetComponent <TechTag>();

            if (techTag == null)
            {
                if ((techTag = prefab.GetComponentInChildren <TechTag>()) == null)
                {
                    techTag = prefab.AddComponent <TechTag>();
                }
            }
            techTag.type = this.TechType;

            // Remove unwanted components
            EntityTag entityTag = prefab.GetComponent <EntityTag>();

            if (entityTag != null)
            {
                GameObject.DestroyImmediate(entityTag);
            }
            EcoTarget ecoTarget = prefab.GetComponent <EcoTarget>();

            if (ecoTarget != null)
            {
                GameObject.DestroyImmediate(ecoTarget);
            }
            ResourceTracker resourceTracker = prefab.GetComponent <ResourceTracker>();

            if (resourceTracker != null)
            {
                GameObject.DestroyImmediate(resourceTracker);
            }
            WorldForces worldForces = prefab.GetComponent <WorldForces>();

            if (worldForces != null)
            {
                GameObject.DestroyImmediate(worldForces);
            }

            // Update prefab ID
            var prefabId = prefab.GetComponent <PrefabIdentifier>();

            if (prefabId == null)
            {
                if ((prefabId = prefab.GetComponentInChildren <PrefabIdentifier>()) == null)
                {
                    prefabId = prefab.AddComponent <PrefabIdentifier>();
                }
            }
            prefabId.ClassId = this.ClassID;

            // Remove Cube object to prevent physics
            GameObject cube = prefab.FindChild("Cube");

            if (cube != null)
            {
                GameObject.DestroyImmediate(cube);
            }

            // Remove rigid body to prevent physics bugs
            var rb = prefab.GetComponent <Rigidbody>();

            if (rb != null)
            {
                GameObject.DestroyImmediate(rb);
            }

            // Add box collider
            var collider = prefab.GetComponent <BoxCollider>();

            if (collider == null)
            {
                Collider[] colliders = prefab.GetComponentsInChildren <Collider>();
                if (colliders != null)
                {
                    foreach (Collider c in colliders)
                    {
                        GameObject.DestroyImmediate(c);
                    }
                }
                collider = prefab.AddComponent <BoxCollider>();
            }
            collider.size      = new Vector3(0.7f, 0.7f, 0.7f);
            collider.center    = new Vector3(collider.center.x - 0.15f, collider.center.y + 1.0f, collider.center.z - 1.0f);
            collider.isTrigger = true;

            // We can pick this item
            var pickupable = prefab.GetComponent <Pickupable>();

            if (pickupable == null)
            {
                pickupable = prefab.AddComponent <Pickupable>();
            }
            pickupable.isPickupable = true;
            pickupable.randomizeRotationWhenDropped = true;

            // We can place this item
            prefab.AddComponent <CustomPlaceToolController>();
            var placeTool = prefab.GetComponent <PlaceTool>();

            if (placeTool != null)
            {
                GameObject.DestroyImmediate(placeTool);
            }
            placeTool = prefab.AddComponent <GenericPlaceTool>();
            placeTool.allowedInBase          = true;
            placeTool.allowedOnBase          = true;
            placeTool.allowedOnCeiling       = false;
            placeTool.allowedOnConstructable = true;
            placeTool.allowedOnGround        = true;
            placeTool.allowedOnRigidBody     = true;
            placeTool.allowedOnWalls         = true;
            placeTool.allowedOutside         = ConfigSwitcher.AllowPlaceOutside;
            placeTool.rotationEnabled        = true;
            placeTool.enabled              = true;
            placeTool.hasAnimations        = false;
            placeTool.hasBashAnimation     = false;
            placeTool.hasFirstUseAnimation = false;
            placeTool.mainCollider         = collider;
            placeTool.pickupable           = pickupable;

            // Update sky applier
            PrefabsHelper.ReplaceSkyApplier(prefab, true);

            // Add fabricating animation
            var fabricating = prefab.AddComponent <VFXFabricating>();

            fabricating.localMinY   = -0.2f;
            fabricating.localMaxY   = 0.6f;
            fabricating.posOffset   = new Vector3(0.1f, 0.141f, 0.3f);
            fabricating.eulerOffset = new Vector3(0f, 0f, 0f);
            fabricating.scaleFactor = 0.2f;

            return(prefab);
        }
コード例 #18
0
 public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
 {
     try
     {
         IntegerTag num = IntegerTag.TryFor(entry.GetArgumentObject(queue, 1));
         if (num.Internal < 0)
         {
             queue.HandleError(entry, "Must provide a non-negative number!");
             return;
         }
         EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));
         if (entity == null)
         {
             queue.HandleError(entry, "Invalid entity!");
             return;
         }
         EPlayerKill kill; // for use with "out EPlayerKill" parameters
         PlayerTag   player;
         if (entity.TryGetPlayer(out player))
         {
             PlayerLife          life             = player.Internal.player.life;
             UFMHealthController healthController = player.Internal.player.GetComponent <UFMHealthController>();
             uint health = healthController != null ? healthController.health : life.health;
             if (num.Internal >= health)
             {
                 uint amount = (uint)num.Internal;
                 if (healthController != null)
                 {
                     healthController.health = 0;
                 }
                 if (amount >= byte.MaxValue) // TODO: better handling
                 {
                     life._health = 0;
                     amount       = 1;
                 }
                 life.askDamage((byte)amount, Vector3.zero, EDeathCause.KILL, ELimb.SPINE, CSteamID.Nil, out kill, null);
             }
             else
             {
                 uint amount = (uint)num.Internal;
                 if (healthController != null)
                 {
                     healthController.Damage((uint)num.Internal);
                 }
                 life._health = healthController.Translate();
                 life.channel.send("tellHealth", ESteamCall.OWNER, ESteamPacket.UPDATE_RELIABLE_BUFFER, new object[]
                 {
                     life.health
                 });
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a player by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         ZombieTag zombie;
         if (entity.TryGetZombie(out zombie))
         {
             uint xp;
             zombie.Internal.askDamage((byte)num.Internal, Vector3.zero, out kill, out xp);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a zombie by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         AnimalTag animal;
         if (entity.TryGetAnimal(out animal))
         {
             uint xp;
             animal.Internal.askDamage((byte)num.Internal, Vector3.zero, out kill, out xp);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged an animal by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         BarricadeTag barricade;
         if (entity.TryGetBarricade(out barricade))
         {
             // TODO: Use BarricadeManager?
             barricade.InternalData.barricade.askDamage((ushort)num.Internal);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a barricade by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         ResourceTag resource;
         if (entity.TryGetResource(out resource))
         {
             // TODO: Use ResourceManager?
             resource.Internal.askDamage((ushort)num.Internal);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a resource by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         StructureTag structure;
         if (entity.TryGetStructure(out structure))
         {
             // TODO: Use StructureManager?
             structure.InternalData.structure.askDamage((ushort)num.Internal);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a structure by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         VehicleTag vehicle;
         if (entity.TryGetVehicle(out vehicle))
         {
             vehicle.Internal.askDamage((ushort)num.Internal, false);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a vehicle by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         queue.HandleError(entry, "That entity can't be damaged!");
     }
     catch (Exception ex) // TODO: Necessity?
     {
         queue.HandleError(entry, "Failed to damage entity: " + ex.ToString());
     }
 }
コード例 #19
0
        public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
        {
            EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));

            if (entity == null)
            {
                queue.HandleError(entry, "Invalid entity!");
                return;
            }
            EPlayerKill kill; // for use with "out EPlayerKill" parameters
            PlayerTag   player;

            if (entity.TryGetPlayer(out player))
            {
                PlayerLife life = player.Internal.player.life;
                life.askDamage(life.health, Vector3.zero, EDeathCause.KILL, ELimb.SPINE, CSteamID.Nil, out kill, null);
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully killed a player!");
                }
                return;
            }
            ZombieTag zombie;

            if (entity.TryGetZombie(out zombie))
            {
                while (!zombie.Internal.isDead)
                {
                    uint xp;
                    zombie.Internal.askDamage((byte)zombie.Internal.health, Vector3.zero, out kill, out xp);
                }
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully killed a zombie!");
                }
                return;
            }
            AnimalTag animal;

            if (entity.TryGetAnimal(out animal))
            {
                while (!animal.Internal.isDead)
                {
                    uint xp;
                    animal.Internal.askDamage((byte)animal.Internal.health, Vector3.zero, out kill, out xp);
                }
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully killed an animal!");
                }
                return;
            }
            BarricadeTag barricade;

            if (entity.TryGetBarricade(out barricade))
            {
                // TODO: Use BarricadeManager?
                barricade.InternalData.barricade.askDamage(barricade.InternalData.barricade.health);
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully destroyed a barricade!");
                }
                return;
            }
            ResourceTag resource;

            if (entity.TryGetResource(out resource))
            {
                // TODO: Use ResourceManager?
                resource.Internal.askDamage(resource.Internal.health);
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully destroyed a resource!");
                }
                return;
            }
            StructureTag structure;

            if (entity.TryGetStructure(out structure))
            {
                // TODO: Use StructureManager?
                structure.InternalData.structure.askDamage(structure.InternalData.structure.health);
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully destroyed a structure!");
                }
                return;
            }
            VehicleTag vehicle;

            if (entity.TryGetVehicle(out vehicle))
            {
                vehicle.Internal.askDamage(vehicle.Internal.health, false);
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully destroyed a vehicle!");
                }
                return;
            }
            queue.HandleError(entry, "That entity can't be damaged!");
        }
コード例 #20
0
 public EntityType(string type, EntityTag tag, UID128 targetUID)
 {
     Type = type; Tag = tag; Metadata = null; TargetUID = targetUID;
 }
コード例 #21
0
        public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
        {
            EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));

            if (entity == null)
            {
                queue.HandleError(entry, "Invalid entity!");
                return;
            }
            PlayerTag player;

            if (entity.TryGetPlayer(out player)) // TODO: Kick?
            {
                Provider.kick(player.Internal.playerID.steamID, "Removed forcibly.");
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully removed a player!");
                }
                return;
            }
            ZombieTag zombie;

            if (entity.TryGetZombie(out zombie)) // TODO: Remove!
            {
                zombie.Internal.health = 0;
                ZombieManager.sendZombieDead(zombie.Internal, new Vector3(9999, 9999, -9999));
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully removed a zombie!");
                }
                return;
            }
            AnimalTag animal;

            if (entity.TryGetAnimal(out animal))
            {
                animal.Internal.health = 0;
                AnimalManager.sendAnimalDead(animal.Internal, new Vector3(9999, 9999, -9999));
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully removed an animal!");
                }
                return;
            }
            BarricadeTag barricade;

            if (entity.TryGetBarricade(out barricade))
            {
                // TODO: Use BarricadeManager magic to remove properly?
                barricade.InternalData.barricade.askDamage(barricade.InternalData.barricade.health);
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully destroyed a barricade!");
                }
                return;
            }
            ResourceTag resource;

            if (entity.TryGetResource(out resource)) // TODO: Remove!
            {
                // TODO: Use ResourceManager magic to remove properly?
                resource.Internal.askDamage(resource.Internal.health);
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully destroyed a resource!");
                }
                return;
            }
            StructureTag structure;

            if (entity.TryGetStructure(out structure)) // TODO: Remove!
            {
                // TODO: Use StructureManager magic to remove properly?
                structure.InternalData.structure.askDamage(structure.InternalData.structure.health);
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully destroyed a structure!");
                }
                return;
            }
            VehicleTag vehicle;

            if (entity.TryGetVehicle(out vehicle)) // TODO: Remove!
            {
                vehicle.Internal.health = 0;
                VehicleManager.sendVehicleExploded(vehicle.Internal);
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully removed a vehicle!");
                }
                return;
            }
            queue.HandleError(entry, "That entity can't be damaged!");
        }
コード例 #22
0
        /// <summary>
        /// Constructs a new physics actor.
        /// </summary>
        /// <param name="desc">Descriptor for the actor.</param>
        public StaticBEPUActor(ActorDesc desc) : base(desc)
        {
            // Build all shapes that make up the actor.
            for (int i = 0; i < desc.Shapes.Count; ++i)
            {
                ShapeDesc shapeDesc = desc.Shapes[i];

                var tag = new EntityTag(this.ownerEntityID);

                if (shapeDesc is BoxShapeDesc)
                {
                    var boxDesc = shapeDesc as BoxShapeDesc;
                    this.body.PhysicsEntity = new Box(desc.Position, boxDesc.Extents.X, boxDesc.Extents.Y, boxDesc.Extents.Z);
                }
                else if (shapeDesc is SphereShapeDesc)
                {
                    var sphereDesc = shapeDesc as SphereShapeDesc;
                    this.body.PhysicsEntity = new Sphere(desc.Position, sphereDesc.Radius);
                }
                else if (shapeDesc is CapsuleShapeDesc)
                {
                    var capDesc = shapeDesc as CapsuleShapeDesc;
                    this.body.PhysicsEntity = new Capsule(desc.Position, capDesc.Length, capDesc.Radius);
                }
                else if (shapeDesc is CylinderShapeDesc)
                {
                    var cylDesc = shapeDesc as CylinderShapeDesc;
                    this.body.PhysicsEntity = new Cylinder(desc.Position, cylDesc.Height, cylDesc.Radius);
                }
                else if (shapeDesc is TriangleMeshShapeDesc)
                {
                    var triDesc = shapeDesc as TriangleMeshShapeDesc;

                    this.collidable = new StaticMesh(triDesc.Vertices.ToArray(),
                                                     triDesc.Indices.ToArray(),
                                                     new AffineTransform(Quaternion.CreateFromRotationMatrix(desc.Orientation), desc.Position));

                    this.collidable.Tag = tag;
                    this.spaceObject    = this.collidable;
                }
                else if (shapeDesc is HeightFieldShapeDesc)
                {
                    throw new Exception("To load terrain physics you must use a TerrainBEPUActor.");
                }
                else
                {
                    throw new Exception("Bad shape.");
                }

                if (null != this.body.PhysicsEntity)
                {
                    SetMovable(false);
                    this.body.PhysicsEntity.Tag = tag;
                    this.body.PhysicsEntity.CollisionInformation.Tag = tag;
                    this.spaceObject = this.body.PhysicsEntity;
                }
            }

            if (this.body.PhysicsEntity != null)
            {
                this.spaceObject = this.body.PhysicsEntity;
                this.body.PhysicsEntity.BecomeKinematic();
                this.body.PhysicsEntity.IsAffectedByGravity = desc.Dynamic;
            }

            Debug.Assert(this.spaceObject != null, "A physics entity was not properly created.");
        }
コード例 #23
0
        private static IEnumerable <IDocument> ReadFile(string fn)
        {
            var MapTypes = new Dictionary <string, string>()
            {
                ["I-ORG"]  = "Organization",
                ["I-PER"]  = "Person",
                ["I-MISC"] = AveragePerceptronEntityRecognizer.TagOutside.ToString(),
                ["I-LOC"]  = "Location",
                ["O"]      = AveragePerceptronEntityRecognizer.TagOutside.ToString(),
            };

            var sb           = new StringBuilder();
            var tagHashToTag = new Dictionary <uint, string>();

            using (var stream = File.OpenRead(fn))
            {
                Stream decompressedStream = stream;
                if (fn.EndsWith("bz2"))
                {
                    decompressedStream = new BZip2InputStream(stream);
                }
                using (var reader = new StreamReader(decompressedStream))
                {
                    //Original tags are following the Inside Outside model
                    string line;

                    while ((line = reader.ReadLine()) is object)
                    {
                        if (!string.IsNullOrWhiteSpace(line))
                        {
                            var lineSpan = line.AsSpan();
                            int pos      = 0;

                            //First assemble the document text
                            sb.Clear();

                            while (true)
                            {
                                var space = lineSpan.Slice(pos).IndexOf(' ');

                                if (space < 0)
                                {
                                    break;
                                }
                                var token = lineSpan.Slice(pos, space - 1);
                                var sep   = token.IndexOf('|');
                                var word  = token.Slice(0, sep);
                                sb.Append(word).Append(' ');
                                pos += space + 1;
                            }

                            var text = sb.ToString();

                            var doc = new Document(text);
                            if (doc.Value.Length != text.Length)
                            {
                                continue;//There were control characters in the text, we just ignore it here...
                            }
                            var span = doc.AddSpan(0, text.Length - 1);


                            pos = 0;
                            int curPos  = 0;
                            var prevTag = "O";
                            var nextTag = "O";

                            //Now add the tags
                            while (true)
                            {
                                var space = lineSpan.Slice(pos).IndexOf(' ');

                                if (space < 0)
                                {
                                    break;
                                }

                                var nextSpace = lineSpan.Slice(pos + space + 1).IndexOf(' ');

                                if (nextSpace > 0)
                                {
                                    var nextToken = lineSpan.Slice(pos + space + 1, nextSpace);
                                    var nextSep   = nextToken.LastIndexOf('|');
                                    nextTag = nextToken.Slice(nextSep + 1).ToString();
                                }
                                else
                                {
                                    nextTag = "O";
                                }

                                var token   = lineSpan.Slice(pos, space);
                                var sep     = token.IndexOf('|');
                                var lastSep = token.LastIndexOf('|');
                                var word    = token.Slice(0, sep);
                                var rawtag  = token.Slice(lastSep + 1);

                                string tag;

                                if (rawtag.StartsWith("B-"))
                                {
                                    var h = rawtag.Hash32();

                                    if (!tagHashToTag.TryGetValue(h, out tag))
                                    {
                                        tag             = "I-" + rawtag.Slice(2).ToString();
                                        tagHashToTag[h] = tag;
                                    }
                                    //Replace with "I-"
                                }
                                else if (rawtag.EndsWith("MISC"))
                                {
                                    //Treat as "O";
                                    tag = "O";
                                }
                                else
                                {
                                    var h = rawtag.Hash32();

                                    if (!tagHashToTag.TryGetValue(h, out tag))
                                    {
                                        tag             = rawtag.ToString();
                                        tagHashToTag[h] = tag;
                                    }
                                }

                                int begin = curPos - span.Begin;
                                int end   = begin + word.Length - 1;
                                curPos += word.Length + 1;
                                EntityTag extra = EntityTag.Outside;

                                bool hasTag = tag != "O";

                                if (hasTag)
                                {
                                    bool equalBefore = tag == prevTag;
                                    bool equalNext   = tag == nextTag;

                                    if (!(equalBefore || equalNext))
                                    {
                                        extra = EntityTag.Single;
                                    }
                                    if (equalBefore && equalNext)
                                    {
                                        extra = EntityTag.Inside;
                                    }
                                    if (equalBefore && !equalNext)
                                    {
                                        extra = EntityTag.End;
                                    }
                                    if (!equalBefore && equalNext)
                                    {
                                        extra = EntityTag.Begin;
                                    }
                                }

                                var newToken = span.AddToken(begin, end);

                                if (!MapTypes.ContainsKey(tag))
                                {
                                    Logger.LogError("Missing tag: {TAG}", tag);
                                    throw new Exception($"Missing tag: {tag}");
                                }

                                newToken.AddEntityType(new EntityType(MapTypes[tag], extra));
                                prevTag = tag;
                                pos    += space + 1;
                            }

                            doc.TrimTokens();
                            yield return(doc);
                        }
                    }
                }
            }
        }
コード例 #24
0
 public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
 {
     try
     {
         IntegerTag num = IntegerTag.TryFor(entry.GetArgumentObject(queue, 1));
         if (num.Internal < 0)
         {
             queue.HandleError(entry, "Must provide a non-negative number!");
             return;
         }
         EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));
         if (entity == null)
         {
             queue.HandleError(entry, "Invalid entity!");
             return;
         }
         PlayerTag player;
         if (entity.TryGetPlayer(out player))
         {
             UFMHealthController healthController = player.Internal.player.gameObject.GetComponent <UFMHealthController>();
             uint amount = (uint)num.Internal;
             if (healthController != null)
             {
                 healthController.Heal(amount);
                 amount = (uint)(((double)amount / healthController.maxHealth) * 100.0);
             }
             PlayerLife life = player.Internal.player.life;
             life._health = healthController.Translate();
             life.channel.send("tellHealth", ESteamCall.OWNER, ESteamPacket.UPDATE_RELIABLE_BUFFER, new object[]
             {
                 life.health
             });
             if (entry.ShouldShowGood(queue))
             {
                 uint finalHealth = healthController != null ? healthController.health : life.health;
                 entry.Good(queue, "Successfully healed a player to a new health value of " + finalHealth + "!");
             }
             return;
         }
         ZombieTag zombie;
         if (entity.TryGetZombie(out zombie))
         {
             Zombie inZomb = zombie.Internal;
             inZomb.health += (ushort)num.Internal;
             if (inZomb.health > inZomb.maxHealth)
             {
                 inZomb.health = inZomb.maxHealth;
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed a zombie to a new health value of " + inZomb.health + "!");
             }
             return;
         }
         AnimalTag animal;
         if (entity.TryGetAnimal(out animal))
         {
             Animal inAnimal = animal.Internal;
             inAnimal.health += (ushort)num.Internal;
             if (inAnimal.health > inAnimal.asset.health)
             {
                 inAnimal.health = inAnimal.asset.health;
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed an animal to a new health value of " + inAnimal.health + "!");
             }
             return;
         }
         BarricadeTag barricade;
         if (entity.TryGetBarricade(out barricade))
         {
             Barricade inBarricade = barricade.InternalData.barricade;
             inBarricade.health += (ushort)num.Internal;
             ushort max = ((ItemBarricadeAsset)Assets.find(EAssetType.ITEM, inBarricade.id)).health;
             if (inBarricade.health > max)
             {
                 inBarricade.health = max;
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed a barricade to a new health value of " + inBarricade.health + "!");
             }
             return;
         }
         ResourceTag resource;
         if (entity.TryGetResource(out resource))
         {
             ResourceSpawnpoint inResource = resource.Internal;
             inResource.health += (ushort)num.Internal;
             ushort max = ((ResourceAsset)Assets.find(EAssetType.RESOURCE, inResource.id)).health;
             if (inResource.health > max)
             {
                 inResource.health = max;
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed a resource to a new health value of " + inResource.health + "!");
             }
             return;
         }
         StructureTag structure;
         if (entity.TryGetStructure(out structure))
         {
             Structure inStructure = structure.InternalData.structure;
             inStructure.health += (ushort)num.Internal;
             ushort max = ((ItemStructureAsset)Assets.find(EAssetType.ITEM, inStructure.id)).health;
             if (inStructure.health > max)
             {
                 inStructure.health = max;
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed a structure to a new health value of " + inStructure.health + "!");
             }
             return;
         }
         VehicleTag vehicle;
         if (entity.TryGetVehicle(out vehicle))
         {
             vehicle.Internal.askRepair((ushort)num.Internal);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed a vehicle to a new health value of " + vehicle.Internal.health + "!");
             }
             return;
         }
         queue.HandleError(entry, "That entity can't be healed!");
     }
     catch (Exception ex) // TODO: Necessity?
     {
         queue.HandleError(entry, ("Failed to heal entity: " + ex.ToString()));
     }
 }
コード例 #25
0
 public bool Match(AbsoluteUri urn,
                   EntityTag etag)
 {
     throw new NotImplementedException();
 }
コード例 #26
0
 public EntityType(string type, EntityTag tag)
 {
     Type = type; Tag = tag; Metadata = null; TargetUID = default(UID128);
 }
コード例 #27
0
        public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
        {
            string    animation = entry.GetArgument(queue, 1).ToUpperInvariant();
            EntityTag entity    = EntityTag.For(entry.GetArgumentObject(queue, 0));

            if (entity == null)
            {
                queue.HandleError(entry, "Invalid entity!");
                return;
            }
            PlayerTag player;

            if (entity.TryGetPlayer(out player))
            {
                try
                {
                    player.Internal.player.animator.sendGesture((EPlayerGesture)Enum.Parse(typeof(EPlayerGesture), animation), true);
                    //player.Internal.player.animator.askGesture(player.Internal.playerID.steamID, (byte)((EPlayerGesture)Enum.Parse(typeof(EPlayerGesture), animation)));
                }
                catch (ArgumentException)
                {
                    queue.HandleError(entry, "Invalid animation specified!");
                    return;
                }
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Animated a player!");
                }
                return;
            }
            ZombieTag zombie;

            if (entity.TryGetZombie(out zombie))
            {
                int    ind   = animation.IndexOf('_');
                string after = animation.Substring(ind + 1);
                animation = animation.Substring(0, ind);
                if (animation == "STARTLE")
                {
                    ZombieManager.sendZombieStartle(zombie.Internal, (byte)IntegerTag.TryFor(after).Internal);
                }
                else if (animation == "STUN")
                {
                    ZombieManager.sendZombieStun(zombie.Internal, (byte)IntegerTag.TryFor(after).Internal);
                }
                else if (animation == "ATTACK")
                {
                    ZombieManager.sendZombieAttack(zombie.Internal, (byte)IntegerTag.TryFor(after).Internal);
                }
                else
                {
                    queue.HandleError(entry, "Invalid animation specified!");
                    return;
                }
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Animated an animal!");
                }
                return;
            }
            AnimalTag animal;

            if (entity.TryGetAnimal(out animal))
            {
                if (animation == "STARTLE")
                {
                    AnimalManager.sendAnimalStartle(animal.Internal);
                }
                else if (animation == "PANIC")
                {
                    AnimalManager.sendAnimalPanic(animal.Internal);
                }
                else if (animation == "ATTACK")
                {
                    AnimalManager.sendAnimalAttack(animal.Internal);
                }
                else
                {
                    queue.HandleError(entry, "Invalid animation specified!");
                    return;
                }
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Animated an animal!");
                }
                return;
            }
            queue.HandleError(entry, "That entity can't be animated!");
        }
コード例 #28
0
        public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
        {
            try
            {
                LocationTag loc = LocationTag.For(entry.GetArgument(queue, 1));
                if (loc == null)
                {
                    queue.HandleError(entry, "Invalid location!");
                    return;
                }
                EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));
                if (entity == null)
                {
                    queue.HandleError(entry, "Invalid entity!");
                    return;
                }
                PlayerTag player;
                if (entity.TryGetPlayer(out player))
                {
                    player.Internal.player.sendTeleport(loc.ToVector3(), 0);
                    if (entry.ShouldShowGood(queue))
                    {
                        entry.Good(queue, "Successfully teleported a player to " + TagParser.Escape(loc.ToString()) + "!");
                    }
                    return;
                }
                ZombieTag zombie;
                if (entity.TryGetZombie(out zombie))
                {
                    zombie.Internal.transform.position = loc.ToVector3();
                    if (entry.ShouldShowGood(queue))
                    {
                        entry.Good(queue, "Successfully teleported a zombie to " + TagParser.Escape(loc.ToString()) + "!");
                    }
                    return;
                }
                AnimalTag animal;
                if (entity.TryGetAnimal(out animal))
                {
                    animal.Internal.transform.position = loc.ToVector3();
                    if (entry.ShouldShowGood(queue))
                    {
                        entry.Good(queue, "Successfully teleported an animal to " + TagParser.Escape(loc.ToString()) + "!");
                    }
                    return;
                }
                ItemEntityTag item;
                if (entity.TryGetItem(out item))
                {
                    // TODO: Find some way to teleport items, barricades, etc without voiding the InstanceID?

                    /*
                     * Transform transform = item.Internal.transform.parent;
                     * byte x;
                     * byte y;
                     * if (Regions.tryGetCoordinate(transform.position, out x, out y))
                     * {
                     *  ItemRegion region = ItemManager.regions[x, y];
                     *  for (byte i = 0; i < region.models.Count; i+)
                     *  {
                     *      if (region.models[i] == transform)
                     *      {
                     *          ItemManager.regions[x, y].items.RemoveAt(i);
                     *          ItemModelTracker.Untrack(x, y, i);
                     *          ItemManager.manager.channel.send("tellTakeItem", ESteamCall.CLIENTS, x, y, ItemManager.ITEM_REGIONS, ESteamPacket.UPDATE_RELIABLE_BUFFER, new object[]
                     *          {
                     *              x,
                     *              y,
                     *              loc.ToVector3()
                     *          });
                     *          // Then respawn item at new location
                     *          break;
                     *      }
                     *  }
                     * }
                     */
                }
                queue.HandleError(entry, "That entity can't be teleported!");
            }
            catch (Exception ex) // TODO: Necessity of this?
            {
                queue.HandleError(entry, "Failed to teleport entity: " + ex.ToString());
            }
        }
コード例 #29
0
ファイル: EntityTag.Facts.cs プロジェクト: KarlDirck/cavity
        public void opInequality_EntityTag_EntityTag()
        {
            var obj = new EntityTag();
            var comparand = new EntityTag();

            Assert.False(obj != comparand);
        }
コード例 #30
0
ファイル: Selector.cs プロジェクト: Vilder50/SharpCraft
 /// <summary>
 /// Creates a new selecter of the given type
 /// </summary>
 /// <param name="SelectWay">the type of selector</param>
 /// <param name="HasTag">a tag the selected entity must have. Note that this can be overwritten by <see cref="Tags"/></param>
 public Selector(ID.Selector SelectWay, Tag? HasTag = null)
 {
     SelectorType = SelectWay;
     if (HasTag != null) { Tags = new EntityTag[] { new EntityTag(HasTag) }; }
 }
コード例 #31
0
ファイル: EntityTag.Facts.cs プロジェクト: KarlDirck/cavity
        public void op_GetHashCode_whenDefault()
        {
            const int expected = 0;
            var actual = new EntityTag().GetHashCode();

            Assert.Equal(expected, actual);
        }
コード例 #32
0
 public bool Match(AlphaDecimal key,
                   EntityTag etag)
 {
     throw new NotImplementedException();
 }
コード例 #33
0
ファイル: EntityTag.Facts.cs プロジェクト: KarlDirck/cavity
        public void op_ToString_whenDefault()
        {
            const string expected = _nullEtag;
            var actual = new EntityTag().ToString();

            Assert.Equal(expected, actual);
        }
コード例 #34
0
        private IfMatchHeader(EntityTag entityTag)
        {
            entityTag.ThrowIfNull("entityTag");

            _entityTag = entityTag;
        }
コード例 #35
0
 public static string GetEntityTag(this MappedResourceInfo @this, CompressionMethod compressionMethod)
 => EntityTag.Compute(@this.LastModifiedUtc, @this.Length, compressionMethod);
コード例 #36
0
        void TimerElapsed(object sender, ElapsedEventArgs e)
        {
            if (!this.isBusy)
            {
                return;
            }
            if (!this.IgnoreExpiresHeader)
            {
                // Since Expires is a static guess by the server, use Expires only when the server did
                // not send back any Etag or LastModifiedTime, which makes conditional GET impossible
                if (this.etag == null && this.lastModifiedTime == null && this.expires != null && (DateTime.UtcNow < this.expires.Value.ToUniversalTime()))
                {
                    return;
                }
            }
            this.expires = null;
            HttpRequestMessage request = new HttpRequestMessage("GET", this.uri);

            if (this.etag != null)
            {
                var ifNoneMatch = new HeaderValues <EntityTag>();
                ifNoneMatch.Add(this.etag);
                request.Headers.IfNoneMatch = ifNoneMatch;
            }
            request.Headers.IfModifiedSince = this.lastModifiedTime;
            bool stopTimer = false;

            try
            {
                HttpResponseMessage response = null;

                try
                {
                    response = this.HttpClient.Send(request);
                }
                catch (Exception ex)
                {
                    if (!this.IgnoreSendErrors)
                    {
                        stopTimer = InvokeHandler(ex);
                    }
                    if (response != null)
                    {
                        response.Dispose();
                    }
                    return;
                }

                using (response)
                {
                    switch (response.StatusCode)
                    {
                    case HttpStatusCode.NotModified:
                        // the resource has not been modified
                        response.Dispose();
                        break;

                    case HttpStatusCode.OK:
                        // the resource has been modified. Fire the event, along with the response message
                        this.etag             = response.Headers.ETag;
                        this.expires          = response.Headers.Expires;
                        this.lastModifiedTime = response.Headers.LastModified;
                        try
                        {
                            stopTimer = InvokeHandler(response);
                        }
                        finally
                        {
                            response.Dispose();
                        }
                        break;

                    default:
                        // this is an unexpected error. Fire the event, if errors are not to be suppressed
                        try
                        {
                            if (!this.IgnoreNonOKStatusCodes)
                            {
                                stopTimer = InvokeHandler(response);
                            }
                        }
                        finally
                        {
                            response.Dispose();
                        }
                        break;
                    }
                }
            }
            finally
            {
                if (stopTimer)
                {
                    StopPolling();
                }
            }
        }