Exemplo n.º 1
0
		public Blob(IBlob blob)
			: this(blob.Md5, Guid.NewGuid().ToString())
		{
			Metdata = new List<KeyValuePair<string, string>>(blob.Metdata);
			Content = blob.Content;
			ContentType = blob.ContentType;
		}
Exemplo n.º 2
0
 public void Behave(IBlob blob)
 {
     if (blob.Damage - 5 >= this.initialDamage)
     {
         blob.Damage -= 5;
     }
 }
Exemplo n.º 3
0
 public override void ToggledEffect(IBlob blob)
 {
     if (this.HasTriggered)
     {
         blob.Health -= 10;
     }
 }
Exemplo n.º 4
0
 /// <summary>
 /// Testing constructor Only
 /// </summary>
 /// <param name="parent"></param>
 /// <param name="inPipe"></param>
 /// <param name="dataObj"></param>
 /// <param name="isValid"></param>
 public DummyOutputNeutralPort(IElement parent, INeutralPipe inPipe, IBlob dataObj, bool isValid)
 {
     _parent = parent;
     _inPipe = inPipe;
     _dataObj = dataObj;
     _IsValid = isValid;
 }
 public override void ApplyBehaviorTurn(IBlob blob)
 {
     if (blob.InitialDamage <= blob.Damage - DefaultAggressiveBehaviorDamageTurnSubtraction)
     {
         blob.Damage -= DefaultAggressiveBehaviorDamageTurnSubtraction;
     }
 }
Exemplo n.º 6
0
        internal Blob(IBlob blob)
        {
            if(blob.Id != Guid.Empty)
                Id = blob.Id;

            OwnerUserId = blob.OwnerUserId;
        }
Exemplo n.º 7
0
        public List<IBlob> Attack(List<IBlob> blobs, string attacker, string defender)
        {
            int attackerIndex = 0;
            int defenderIndex = 0;
            for (int i = 0; i < blobs.Count; i++)
            {
                if (blobs[i].Name == attacker)
                {
                    attackerIndex = i;
                }
                if (blobs[i].Name == defender)
                {
                    defenderIndex = i;
                }
            }

            if (blobs[attackerIndex].Attack == "PutridFart")
            {
                blobs[defenderIndex] = attaks.PutridFart(blobs[attackerIndex], blobs[defenderIndex]);
            }
            else if (blobs[attackerIndex].Attack == "Blobplode")
            {
                IBlob[] blobArray = new IBlob[2];
                blobArray = attaks.Blobplode(blobs[attackerIndex], blobs[defenderIndex]);
                blobs[attackerIndex] = blobArray[0];
                blobs[defenderIndex] = blobArray[1];
            }

            return blobs;
        }
Exemplo n.º 8
0
 public static void ValidateHelth(IBlob blob)
 {
     if (blob.Health < 0)
     {
         blob.Health = 0;
     }
 }
Exemplo n.º 9
0
 protected void FireEvent(IBlob parent)
 {
     if (this.HasTriggered != null)
     {
         this.HasTriggered(parent);
     }
 }
Exemplo n.º 10
0
 public override void Trigger(IBlob blob)
 {
     if (!this.HasTriggered)
     {
         this.HasTriggered = true;
         blob.Health += 50;
     }
 }
 public void AddBlobs(IBlob blob)
 {
     if (blob == null)
     {
         throw new ArgumentException(nameof(blob));
     }
     this.blobs.Add(blob);
 }
Exemplo n.º 12
0
 public Engine(IBlob blob, Data data, IInputReader reader, IBlobFactory blobFactory, IOutputWriter writer)
 {
     this.blob = blob;
     this.data = data;
     this.reader = reader;
     this.blobFactory = blobFactory;
     this.writer = writer;
 }
Exemplo n.º 13
0
 public void AddBlob(IBlob blob)
 {
     if (blob==null)
     {
         throw new NullReferenceException(Messeges.NullBlobReference);
     }
     this.blobs.Add(blob);
 }
Exemplo n.º 14
0
 /// <summary>
 /// Adding a Blob to the data.
 /// </summary>
 /// <param name="blob"></param>
 public void AddBlob(IBlob blob)
 {
     if (blob == null)
     {
         throw new ArgumentException("Blob cannot be created without the foll");
     }
     this.blops.Add(blob);
 }
Exemplo n.º 15
0
 public void AddInflatedBlobs(IBlob inflatedBlob)
 {
     if (inflatedBlob == null)
     {
         throw new ArgumentNullException(nameof(inflatedBlob));
     }
     this.inflatedBlobs.Add(inflatedBlob);
 }
Exemplo n.º 16
0
 public void AddAggresiveBlobs(IBlob aggressiveBlob)
 {
     if (aggressiveBlob == null)
     {
         throw new ArgumentNullException(nameof(aggressiveBlob));
     }
     this.aggresiveBlobs.Add(aggressiveBlob);
 }
Exemplo n.º 17
0
        public async Task InsertAsync(IBlob t)
        {
            var blobReference = _container.GetBlockBlobReference(t.Id);
            if(await blobReference.ExistsAsync())
                throw new InvalidOperationException("Key already exists: " + t.Id);

            await UpsertAsync(t);
        }
Exemplo n.º 18
0
 /// <summary>
 /// Initializes the base for the merged blob.
 /// </summary>
 /// <param name="baseBlob">The blob object to inherit properties from.</param>
 public MergedBlob(IBlob baseBlob)
 {
     Dimension = baseBlob.Dimension;
     Position = baseBlob.Position;
     Size = baseBlob.Size;
     Center = baseBlob.Center;
     Color = baseBlob.Color;
 }
 protected override void ApplyHealthEffect(IBlob blob)
 {
     if (blob.Health/2 >= 1)
     {
         blob.Health /= 2;
     }
     else blob.Health = 1;
 }
Exemplo n.º 20
0
 public override void Trigger(IBlob blob)
 {
     if (!this.HasTriggered)
     {
         this.HasTriggered = true;
         blob.Damage *= 2;
     }
 }
Exemplo n.º 21
0
        public virtual void SetOwner(IBlob newOwner)
        {
            if (this.Owner != default(IBlob))
            {
                throw new InvalidOperationException(ErrorMessages.OwnerAlreadySet);
            }

            this.Owner = newOwner;
        }
Exemplo n.º 22
0
 public void Blobplode(IBlob blobToAttack)
 {
     Health /= 2;
     if (Health < 1)
     {
         Health = 1;
     }
     blobToAttack.Health -= AttackDamage*2;
 }
        public void AddBlob(IBlob blob)
        {
            if (blob == null)
            {
                throw new ArgumentNullException("Blob cannot be null");
            }

            this.Blobs.Add(blob);
        }
Exemplo n.º 24
0
        public void CreateBlob(IBlob blob)
        {
            if (blob == null)
            {
                throw new ArgumentNullException(nameof(blob));
            }

            this.blobs.Add(blob);
        }
Exemplo n.º 25
0
        public static ManifestEntry FromBlob(IBlob blob)
        {
            var hash = Hash.Compute(HashType.SHA256, blob.Open(), leaveOpen: false);

            return new ManifestEntry(
                name     : blob.Name,
                modified : blob.Modified,
                hash     : hash
            );
        }
Exemplo n.º 26
0
		public Uri Put(IBlob blob)
		{
			Assert.NotNull(blob);
			Assert.NotNull(blob.Content);

			var uri = _blobStorage.Put(blob, "test");

			Assert.NotNull(uri);

			return uri;
		}
Exemplo n.º 27
0
        public override int SpellAttack(IBlob attackingBlob)
        {
            attackingBlob.Health -= attackingBlob.Health / 2;
            if (attackingBlob.Health == 0)
            {
                attackingBlob.Health = 1;
            }

            int attackPower = attackingBlob.Damage * 2;
            return attackPower;
        }
Exemplo n.º 28
0
        public override void ApplyBehavior(IBlob currentBlob)
        {
            if (EffectAlreadyApplied)
               {
               throw new InvalidOperationException(ExceptionMessage);
               }

               EffectAlreadyApplied = true;
               EffectApplied = true;
               currentBlob.Health += healthGain;
        }
        public override void Trigger(IBlob blob)
        {
            if (this.AlreadyTriggered)
            {
                throw new InvalidOperationException(ExceptionMessage);
            }

            this.IsTriggered = true;
            this.AlreadyTriggered = true;
            blob.Health += HealthBonus;
        }
 public override void PerformNegativeEffects(IBlob blob)
 {
     if (this.ShouldDelayBeforeExecution)
     {
         this.ShouldDelayBeforeExecution = false;
     }
     else
     {
         blob.Health -= HealthLostValue;
     }
 }
        private string ExecuteCreateCommand(ICommand command)
        {
            string name       = command.Parameters[0];
            int    health     = int.Parse(command.Parameters[1]);
            int    damage     = int.Parse(command.Parameters[2]);
            string behavior   = command.Parameters[3];
            string attackType = command.Parameters[4];


            IBlob blob = this.blobFactory.ProduceBlob(name, health, damage, behavior, attackType);

            this.database.Blobs.Add(blob);

            return(null);
        }
Exemplo n.º 32
0
        public PushBlobStep(
            BuildConfiguration buildConfiguration,
            ProgressEventDispatcher.Factory progressEventDipatcherFactory,
            AuthenticatePushStep authenticatePushStep,
            BlobDescriptor blobDescriptor,
            IBlob blob)
        {
            this.buildConfiguration            = buildConfiguration;
            this.progressEventDipatcherFactory = progressEventDipatcherFactory;
            this.authenticatePushStep          = authenticatePushStep;
            this.blobDescriptor = blobDescriptor;
            this.blob           = blob;

            listenableFuture = CallAsync();
        }
Exemplo n.º 33
0
        public void Truncate()
        {
            IBlob testSubject = NewTestSubject();

            if (testSubject.CanWrite)
            {
                long len = testSubject.Length;

                for (int i = (int)len; i >= 0; i--)
                {
                    testSubject.Truncate(i);

                    Assert.AreEqual(i, testSubject.Length);
                }
            }

            testSubject = NewTestSubject();

            try
            {
                testSubject.Truncate(-1);

                Assert.Fail("successful invocation of Truncate(len) with len < 0");
            }
            catch (AssertionException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(typeof(HsqlDataSourceException), ex);
            }

            try
            {
                testSubject.Truncate(testSubject.Length + 1);

                Assert.Fail("successful invocation of Truncate(len) with len > testSubject.Length");
            }
            catch (AssertionException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(typeof(HsqlDataSourceException), ex);
            }
        }
Exemplo n.º 34
0
        public override void ApplyRecurrentEffect(IBlob source)
        {
            if (this.ToDelayRecurrentEffect)
            {
                this.ToDelayRecurrentEffect = false;
            }
            else
            {
                source.Damage -= AggressiveDamageDecrementer;

                if (source.Damage <= this.sourceInitialDamage)
                {
                    source.Damage = this.sourceInitialDamage;
                }
            }
        }
Exemplo n.º 35
0
 public Functions(
     IOptions <Secrets.ConnectionStrings> connStr,
     IOptions <Secrets.Config> config,
     IInfo info,
     IMyPdf myPdf,
     IBlob blob,
     IMyEmail myEmail
     )
 {
     _connStr = connStr;
     _config  = config;
     _info    = info;
     _pdf     = myPdf;
     _blob    = blob;
     _email   = myEmail;
 }
Exemplo n.º 36
0
        public void Store(string relativePath, IBlob blob, BlobStoreOptions options = BlobStoreOptions.None)
        {
            var containerClient = GetContainerClient();

            var blobClient = containerClient.GetBlobClient(relativePath);

            if (options != BlobStoreOptions.Overwrite && blobClient.Exists())
            {
                throw new IOException("Blob already exists");
            }

            using (var inputStream = blob.OpenRead())
            {
                blobClient.Upload(inputStream);
            }
        }
Exemplo n.º 37
0
    public IAttack CreateAttack(string attackType, IBlob blob)
    {
        Type type = Assembly
                    .GetExecutingAssembly()
                    .GetTypes()
                    .FirstOrDefault(t => t.Name == attackType);

        if (type == null)
        {
            throw new ArgumentException("Unknown attack type.");
        }

        IAttack attack = (IAttack)Activator.CreateInstance(type, blob);

        return(attack);
    }
Exemplo n.º 38
0
        public async Task TestPushAsync()
        {
            localRegistry.PullAndPushToLocal("busybox", "busybox");
            IBlob testBlob = Blobs.From("crepecake");
            // Known digest for 'crepecake'
            DescriptorDigest testBlobDigest =
                DescriptorDigest.FromHash(
                    "52a9e4d4ba4333ce593707f98564fee1e6d898db0d3602408c0b2a6a424d357c");

            RegistryClient registryClient =
                RegistryClient.CreateFactory(EventHandlers.NONE, "localhost:5000", "testimage")
                .SetAllowInsecureRegistries(true)
                .NewRegistryClient();

            Assert.IsFalse(await registryClient.PushBlobAsync(testBlobDigest, testBlob, null, _ => { }).ConfigureAwait(false));
        }
Exemplo n.º 39
0
        public static void Save(string path, IBlob data, bool deleteFolder = false)
        {
            DirectoryInfo folder = Directory.GetParent(path);

            if (!folder.Exists)
            {
                folder.Create();
            }
            else if (deleteFolder)
            {
                folder.Delete(true);
                folder.Create();
            }

            File.WriteAllBytes(path, data.ToBytes());
        }
Exemplo n.º 40
0
        public async Task StoreAsync(string relativePath, IBlob blob, BlobStoreOptions options = BlobStoreOptions.None)
        {
            var containerClient = await GetContainerClientAsync();

            var blobClient = containerClient.GetBlobClient(relativePath);

            if (options != BlobStoreOptions.Overwrite && await blobClient.ExistsAsync())
            {
                throw new IOException("Blob already exists");
            }

            using (var inputStream = await blob.OpenReadAsync())
            {
                await blobClient.UploadAsync(inputStream);
            }
        }
Exemplo n.º 41
0
    public IBehavior CreateBehavior(string behaviorType, IBlob blob)
    {
        Type type = Assembly
                    .GetExecutingAssembly()
                    .GetTypes()
                    .FirstOrDefault(t => t.Name == behaviorType);

        if (type == null)
        {
            throw new ArgumentException("Unknown behavior type.");
        }

        IBehavior behavior = (IBehavior)Activator.CreateInstance(type, blob);

        return(behavior);
    }
Exemplo n.º 42
0
        public IAttack ModifyAttack(IAttack attack, IBlob blob)
        {
            string behaviourName = blob.Behaviour.GetType().Name.ToString();

            switch (behaviourName)
            {
            case "AggressiveBehaviour":
                attack.Damage += blob.CurrentDamage;
                return(attack);

            case "InflatedBehaviour":
                return(attack);

            default:
                throw  new ArgumentException("Unknown attack");
            }
        }
Exemplo n.º 43
0
        /// <summary>
        /// Preprocesses the provided shader or effect source.
        /// </summary>
        /// <param name="shaderSource">An array of bytes containing the raw source of the shader or effect to preprocess.</param>
        /// <param name="sourceFileName">Name of the source file.</param>
        /// <param name="defines">A set of macros to define during preprocessing.</param>
        /// <param name="include">An interface for handling include files.</param>
        /// <returns>
        /// The preprocessed shader source.
        /// </returns>
        public static string Run(string shaderSource, string sourceFileName = null, ShaderMacro[] defines = null, IncludeHandler include = null)
        {
            // Stringify/Concat not supported by D3DCompiler preprocessor.
            shaderSource = ConcatenateTokens(shaderSource, defines);

            try
            {
#if FRAMEWORK_SHADER_USE_SHARPDX
                string compilationErrors;
                shaderSource = SharpDX.D3DCompiler.ShaderBytecode.Preprocess(
                    shaderSource,
                    defines != null ? defines.Select(x => new SharpDX.Direct3D.ShaderMacro(x.Name, x.Definition)).ToArray() : null,
                    new IncludeShadow(include),
                    out compilationErrors, sourceFileName);
#else
                IBlob blobForText   = null;
                IBlob blobForErrors = null;

                var shadow = include == null ? null : new IncludeShadow(include);

                var data = Encoding.ASCII.GetBytes(shaderSource);
                int result;
                unsafe
                {
                    fixed(void *pData = data)
                    result = D3DPreprocess((IntPtr)pData, new IntPtr(data.Length), sourceFileName, PrepareMacros(defines), shadow != null ? shadow.NativePointer : IntPtr.Zero, out blobForText, out blobForErrors);
                }

                if (shadow != null)
                {
                    shadow.Dispose();
                }

                if (result < 0)
                {
                    throw new InvalidOperationException(string.Format("Include errors: {0}", blobForErrors == null ? "" : Marshal.PtrToStringAnsi(blobForErrors.GetBufferPointer())));
                }

                shaderSource = Marshal.PtrToStringAnsi(blobForText.GetBufferPointer());
#endif
            } catch (Exception ex)
            {
                Console.WriteLine("Warning, error while preprocessing file [{0}] : {1}", sourceFileName, ex.Message);
            }
            return(shaderSource);
        }
Exemplo n.º 44
0
        public static bool IsHidden(this IBlob blob)
        {
            // contains a period in the path....

            // .something.jpeg
            // /.git

            foreach (var part in blob.Key.Split(Seperators.ForwardSlash))
            {
                if (part.Length > 0 && part[0] == '.')
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 45
0
        public override void ApplyRecurrentEffect(IBlob blob)
        {
            if (this.IsDelayNeeded)
            {
                this.IsDelayNeeded = false;
                return;
            }

            if (blob.Damage > this.initialDamage)
            {
                if (blob.Damage - DamageDecrementerPerTurn > this.initialDamage)
                {
                    this.InfluencingProperty
                    .SetValue(blob, (int)this.InfluencingProperty.GetValue(blob) - DamageDecrementerPerTurn);
                }
            }
        }
 public override void AttackBehavior(IBlob blob)
 {
     if (blob.Health == 1)
     {
         goto done;
     }
     if (blob.Health % 2 == 0)
     {
         blob.Health = blob.Health / 2;
     }
     else if (blob.Health % 2 != 0)
     {
         blob.Health  = blob.Health / 2;
         blob.Health += 1;
     }
     blob.Damage = blob.Damage * 2;
     done :;
 }
Exemplo n.º 47
0
 public override void PerformNegativeEffects(IBlob blob)
 {
     if (ShouldDelayBeforeExecution)
     {
         this.ShouldDelayBeforeExecution = false;
     }
     else
     {
         if (blob.Damage - DamageReductionValue < initialBlobDamage)
         {
             this.IsTriggered = false;
         }
         else
         {
             blob.Damage -= DamageReductionValue;
         }
     }
 }
Exemplo n.º 48
0
        public async Task <IEnumerable <string> > UploadAsync(IBlob file)
        {
            if (file == null)
            {
                return new[] { "no-file" }
            }
            ;

            using (var stream = await file.OpenReadAsync())
            {
                return(new[]
                {
                    file.Name,
                    stream.Length.ToString()
                });
            }
        }
    }
Exemplo n.º 49
0
 public void PerformAttack(IBlob blob, IBlob target)
 {
     if (!blob.Behaviour.IsTriggered)
     {
         var attack = this.ProduceAttack(blob);
         blob.UpdateBehaviour();
         if (blob.Behaviour.IsTriggered)
         {
             attack = blob.Attack.ModifyAttack(attack, blob);
         }
         this.RespondToAttack(target, attack);
         return;
     }
     else
     {
         var attack = this.ProduceAttack(blob);
         this.RespondToAttack(target, attack);
     }
 }
Exemplo n.º 50
0
        public bool Equals(IBlob obj)
        {
            if (ReferenceEquals(this, obj))
            {
                return(true);
            }

            if (obj == null)
            {
                return(false);
            }

            if (this.Id == obj.Id)
            {
                return(true);
            }

            return(false);
        }
Exemplo n.º 51
0
        /// <summary>
        /// Получить тело письма.
        /// </summary>
        /// <param name="fileElements">Элементы xml c информацией об импортируемых файлах.</param>
        /// <param name="packageFolderPath">Путь к папке хранения файлов, переданных в пакете.</param>
        /// <returns>Запись справочника с телом письма и сопутствующей информацией.
        /// Если тела нет, то пустую запись справочника.</returns>
        public virtual IBlob GetMailBody(List <System.Xml.Linq.XElement> fileElements, string packageFolderPath)
        {
            var fileDescriptionTagName = Constants.Module.DcsInputFilesTagNames.FileDescription;
            var mailBodyHtmlName       = Constants.Module.DcsMailBodyName.Html;
            var mailBodyTxtName        = Constants.Module.DcsMailBodyName.Txt;

            var htmlBodyElement = fileElements
                                  .FirstOrDefault(x => string.Equals(x.Element(fileDescriptionTagName).Value, mailBodyHtmlName, StringComparison.InvariantCultureIgnoreCase));
            var txtBodyElement = fileElements
                                 .FirstOrDefault(x => string.Equals(x.Element(fileDescriptionTagName).Value, mailBodyTxtName, StringComparison.InvariantCultureIgnoreCase));
            var hasHtmlBody = htmlBodyElement != null;
            var hasTxtBody  = txtBodyElement != null;

            // Не создавать документ для писем с пустым телом.
            // В некоторых случаях (например, при отправке из Outlook в Яндекс) для писем с пустым телом генерируется фейковое тело,
            // представляющее из себя только перевод строки. Такие тела заносить также не нужно.

            // Получить текст из тела письма.
            IBlob mailBodyBlob = Blobs.Null;
            var   bodyText     = string.Empty;

            if (hasHtmlBody)
            {
                mailBodyBlob = this.CreateBlobFromXelement(htmlBodyElement, packageFolderPath, true);
                bodyText     = AsposeExtensions.HtmlTagReader.GetTextFromHtml(mailBodyBlob.FilePath);
            }
            else if (hasTxtBody)
            {
                mailBodyBlob = this.CreateBlobFromXelement(txtBodyElement, packageFolderPath, true);
                bodyText     = File.ReadAllText(mailBodyBlob.FilePath);
            }

            // Очистить текст из тела письма от спецсимволов, чтобы определить, пуст ли он.
            var clearBodyText = bodyText.Trim(new[] { ' ', '\r', '\n', '\0' });

            if (!string.IsNullOrWhiteSpace(clearBodyText))
            {
                return(mailBodyBlob);
            }

            return(Blobs.Null);
        }
        public override void CurrentBehavior(IBlob blob)
        {
            if (isTrigered == true)
            {
                if (blob.Health - 10 <= 0)
                {
                    blob.Health = 0;
                }
                else
                {
                    blob.Health -= 10;
                }
                goto done;
            }

            isTrigered = true;

            blob.Health += 50;
            done :;
        }
        private bool CheckBehavior(IBlob attacker)
        {
            if (attacker.Health <= attacker.InitialHealth / 2)
            {
                attacker.InSpecialBahavior = true;

                if (attacker is Aggressive)
                {
                    attacker.Damage *= 2;
                }

                if (attacker is Inflated)
                {
                    attacker.Health += 50;
                }

                return(true);
            }
            return(false);
        }
Exemplo n.º 54
0
        public void SetBinaryStream()
        {
            IBlob testSubject = NewTestSubject();

            if (testSubject.CanWrite)
            {
                Stream stream = testSubject.SetBinaryStream(1);

                stream.WriteByte((byte)10);
            }

            try
            {
                Stream stream = testSubject.SetBinaryStream(0);

                Assert.Fail("successful invocation of SetBinaryStream(pos) with pos too small (<1)");
            }
            catch (AssertionException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(typeof(HsqlDataSourceException), ex);
            }

            try
            {
                Stream stream = testSubject.SetBinaryStream(LobBytesLength + 1);

                Assert.Fail("successful invocation of SetBinaryStream(pos) with pos too large (LobBytesLength + 1)");
            }
            catch (AssertionException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(typeof(HsqlDataSourceException), ex);
            }
        }
Exemplo n.º 55
0
        public void Run()
        {
            string input = null;

            while (input != "drop")
            {
                input = consoleRead.Read();

                string[] command = input.Split();

                switch (command[0])
                {
                case "create":
                    string name     = command[1];
                    int    health   = Int32.Parse(command[2]);
                    int    damage   = Int32.Parse(command[3]);
                    string behavior = command[4];
                    string attack   = command[5];

                    blob = blobCreator.Create(name, health, damage, behavior, attack);
                    data.AddBlob(blob);
                    break;

                case "attack":
                    string attacker = command[1];
                    string defender = command[2];
                    data.Blobs = attackBlob.Attack(data.Blobs, attacker, defender);
                    break;

                case "status":
                    consoleWrite.WriteList(data.Blobs);
                    break;

                case "pass":
                    break;

                default:
                    break;
                }
            }
        }
Exemplo n.º 56
0
        public async Task UpsertAsync(IBlob t)
        {
            var blobReference = _container.GetBlockBlobReference(t.Id);

            // concurrency check
            var concurrencyAware = t as IConcurrencyAware;

            CheckConcurrency(concurrencyAware, blobReference);

            await blobReference.UploadFromStreamAsync(t.Body);

            if (t.Metadata != null)
            {
                foreach (var kv in t.Metadata)
                {
                    blobReference.Metadata[kv.Key] = kv.Value;
                }
                await blobReference.SetMetadataAsync();
            }
            t.UnderlyingBlob = blobReference;
        }
Exemplo n.º 57
0
        private async Task VerifyCachedLayerAsync(CachedLayer cachedLayer, IBlob uncompressedLayerBlob)
        {
            BlobDescriptor layerBlobDescriptor = await GetDigestAsync(Compress(uncompressedLayerBlob)).ConfigureAwait(false);

            BlobDescriptor layerDiffDescriptor = await GetDigestAsync(uncompressedLayerBlob).ConfigureAwait(false);

            DescriptorDigest layerDiffId = layerDiffDescriptor.GetDigest();

            // Verifies cachedLayer is correct.
            Assert.AreEqual(layerBlobDescriptor.GetDigest(), cachedLayer.GetDigest());
            Assert.AreEqual(layerDiffId, cachedLayer.GetDiffId());
            Assert.AreEqual(layerBlobDescriptor.GetSize(), cachedLayer.GetSize());
            CollectionAssert.AreEqual(
                await Blobs.WriteToByteArrayAsync(uncompressedLayerBlob).ConfigureAwait(false),
                await Blobs.WriteToByteArrayAsync(await DecompressAsync(cachedLayer.GetBlob()).ConfigureAwait(false)).ConfigureAwait(false));

            // Verifies that the files are present.
            Assert.IsTrue(
                Files.Exists(
                    cacheStorageFiles.GetLayerFile(cachedLayer.GetDigest(), cachedLayer.GetDiffId())));
        }
Exemplo n.º 58
0
        public void Create(string[] parameters)
        {
            string blobName = parameters[0];

            int health = int.Parse(parameters[1]);

            int damage = int.Parse(parameters[2]);

            string behaviourName = parameters[3];

            string attackName = parameters[4];

            IBehaviour behaviour = this.BehaviourFactory.CreateBehaviour(behaviourName);

            IAttack attack = this.AttackFactory.CreateAttack(attackName);

            IBlob blob = this.BlobFactory.CreateBlob(blobName, health, damage, behaviour, attack);


            this.Database.BlobsCollection.Add(blob);
        }
Exemplo n.º 59
0
        /**
         * Writes an uncompressed {@link Blob} out to the cache directory in the form:
         *
         * <ul>
         *   <li>The {@code uncompressedLayerBlob} is written to the layer directory under the layers
         *       directory corresponding to the layer blob.
         *   <li>The {@code selector} is written to the selector file under the selectors directory.
         * </ul>
         *
         * @param uncompressedLayerBlob the {@link Blob} containing the uncompressed layer contents to
         *     write out
         * @param selector the optional selector digest to also reference this layer data. A selector
         *     digest may be a secondary identifier for a layer that is distinct from the default layer
         *     digest.
         * @return the {@link CachedLayer} representing the written entry
         * @throws IOException if an I/O exception occurs
         */
        public async Task <CachedLayer> WriteUncompressedAsync(IBlob uncompressedLayerBlob, DescriptorDigest selector)
        {
            uncompressedLayerBlob = uncompressedLayerBlob ?? throw new ArgumentNullException(nameof(uncompressedLayerBlob));
            // Creates the layers directory if it doesn't exist.
            Files.CreateDirectories(cacheStorageFiles.GetLayersDirectory());

            // Creates the temporary directory. The temporary directory must be in the same FileStore as the
            // final location for Files.move to work.
            Files.CreateDirectories(cacheStorageFiles.GetTemporaryDirectory());
            using (TemporaryDirectory temporaryDirectory =
                       new TemporaryDirectory(cacheStorageFiles.GetTemporaryDirectory()))
            {
                SystemPath temporaryLayerDirectory = temporaryDirectory.GetDirectory();

                // Writes the layer file to the temporary directory.
                WrittenLayer writtenLayer =
                    await WriteUncompressedLayerBlobToDirectoryAsync(uncompressedLayerBlob, temporaryLayerDirectory).ConfigureAwait(false);

                // Moves the temporary directory to the final location.
                temporaryDirectory.MoveIfDoesNotExist(cacheStorageFiles.GetLayerDirectory(writtenLayer.LayerDigest));

                // Updates cachedLayer with the blob information.
                SystemPath layerFile =
                    cacheStorageFiles.GetLayerFile(writtenLayer.LayerDigest, writtenLayer.LayerDiffId);
                CachedLayer.Builder cachedLayerBuilder =
                    CachedLayer.CreateBuilder()
                    .SetLayerDigest(writtenLayer.LayerDigest)
                    .SetLayerDiffId(writtenLayer.LayerDiffId)
                    .SetLayerSize(writtenLayer.LayerSize)
                    .SetLayerBlob(Blobs.From(layerFile));

                // Write the selector file.
                if (selector != null)
                {
                    WriteSelector(selector, writtenLayer.LayerDigest);
                }

                return(cachedLayerBuilder.Build());
            }
        }
Exemplo n.º 60
0
        public override void ProduceAttack(IBlob target)
        {
            if (this.Attacker.IsAlive && target.IsAlive)
            {
                var initialHealth = this.Attacker.Health;
                if (this.Attacker.Health - (this.Attacker.Health / HealthPointsReductor) > 1)
                {
                    this.Attacker.Health -= (this.Attacker.Health / HealthPointsReductor);
                }

                if (this.Attacker.Health <= (initialHealth / HealthPointsReductor))
                {
                    this.Attacker.Behavior.IsTriggered = true;
                }

                if (this.Attacker.Behavior.IsTriggered)
                {
                    this.Attacker.Behavior.Blob = this.Attacker;
                    this.Attacker.Behavior.TriggerBehavior();
                }

                var prevTargetHealth = target.Health;
                target.Health -= this.Attacker.AttackDamage * AttackDamageMultiplier;
                if (target.Health < 0)
                {
                    target.Health = 0;
                }

                if (target.Health <= prevTargetHealth / 2)
                {
                    target.Behavior.IsTriggered = true;
                }

                if (target.Behavior.IsTriggered)
                {
                    target.Behavior.Blob = target;
                    target.Behavior.TriggerBehavior();
                }
            }
        }