public void SetUp()
 {
     using (var stream = TestDataHelper.OpenResource("Text.list_of_values.vdf"))
     {
         data = KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize <ContainerClass>(stream);
     }
 }
Exemple #2
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "GetClientContainerSize/{container}")] HttpRequest req,
            string container)
        {
            try
            {
                IImageService     service          = Utilities.Utilities.GetImageService();
                IContainerService containerService = new ContainerClass(container);
                if (!service.CheckIfContainerExists(containerService))
                {
                    return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                               HttpStatusCode.BadRequest, "Provided container is invalid"));
                }

                double containerSizeInMiB = Math.Round(service.GetImagesDictionaryPathAndSize(containerService).Sum(x => x.Value) / (1024f * 1024f), 2);

                var sizeDictionary = new Dictionary <string, double>();
                sizeDictionary.Add(containerService.GetContainerName(), containerSizeInMiB);

                return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                           HttpStatusCode.OK, JsonConvert.SerializeObject(sizeDictionary)));
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }
Exemple #3
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Dictionary/{container}")] HttpRequest req,
            string container)
        {
            try
            {
                IImageService     service          = Utilities.Utilities.GetImageService();
                IContainerService containerService = new ContainerClass(container);

                if (!service.CheckIfContainerExists(containerService))
                {
                    return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                               HttpStatusCode.BadRequest, ""));
                }

                var cloudImages = service.GetBaseImagesDictionary(containerService);

                return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                           HttpStatusCode.OK, JsonConvert.SerializeObject(cloudImages)));
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }
        public void Should_Match_All_Properties_of_Same_Type()
        {
            //Create an instance of our test class
            var testInstance = new ContainerClass();

            var nameConst = "AaronConst";

            var fake = new Fake<ContainerClass>();

            //Run some tests before we add the custom selector
            var standardFakeInstance = fake.Generate();

            Assert.AreNotEqual(nameConst, standardFakeInstance.Name);

            //Add the custom selector for the Member field
            var selector = fake.SetType(() => nameConst);

            //Assert.IsTrue(selector.CanBind(typeof(string)));

            //Generate a new fake with the custom selector implemented
            var customFakeInstance = fake.Generate();

            Assert.AreEqual(nameConst, customFakeInstance.Name);
            Assert.AreEqual(nameConst, customFakeInstance.OtherName);
            Assert.AreEqual(nameConst, customFakeInstance.Member.Name);
        }
        public void Should_Match_Class_Property_with_CustomSelector()
        {
            //Create an instance of our test class
            var testInstance = new ContainerClass();

            var measureConst = 1;
            var nameConst = "AaronConst";

            var fake = new Fake<ContainerClass>();

            //Run some tests before we add the custom selector
            var standardFakeInstance = fake.Generate();

            Assert.AreNotEqual(measureConst, standardFakeInstance.Member.Measure);
            Assert.AreNotEqual(nameConst, standardFakeInstance.Member.Name);

            //Add the custom selector for the Member field
            var selector = fake.SetProperty(x => x.Member, () => new CustomMember() {Measure = measureConst, Name = nameConst});

            //Assert.IsTrue(selector.CanBind(typeof(CustomMember)));

            //Generate a new fake with the custom selector implemented
            var customFakeInstance = fake.Generate();

            Assert.AreEqual(measureConst, customFakeInstance.Member.Measure);
            Assert.AreEqual(nameConst, customFakeInstance.Member.Name);
        }
 public void SetUp()
 {
     using (var stream = TestDataHelper.OpenResource("Text.list_of_values.vdf"))
     {
         data = KVSerializer.Deserialize <ContainerClass>(stream);
     }
 }
        /// <summary>
        /// This code used to break in version 1.9.0.
        /// </summary>
        public static void OffendingTestBatch()
        {
            var name = "Offending test batch: ";
            // Create an instance with an extra level, with 2 items in its list and serialize it to JSON
            ContainerClass Test = new ContainerClass();

            Test.Inst.Items.Add(new ItemClass {
                A = "NotWorkAsExpected.Test1A", B = "NotWorkAsExpected.Test1B"
            });
            Test.Inst.Items.Add(new ItemClass {
                A = "NotWorkAsExpected.Test2A", B = "NotWorkAsExpected.Test2B"
            });
            JsonSerializerSettings Settings = new JsonSerializerSettings();

            Settings.TypeNameHandling = TypeNameHandling.Objects;

            string Json = JsonConvert.SerializeObject(Test, Formatting.Indented, Settings);

            ContainerClass Result = JsonConvert.DeserializeObject <ContainerClass>(Json, Settings);

            Assert.AreEqual(2, Result.Inst.Items.Count, name + "Amount of items is right.");
            Assert.AreEqual("NotWorkAsExpected.Test1A", Result.Inst.Items[0].A, name + "Item 0, property A is right.");
            Assert.AreEqual("NotWorkAsExpected.Test1B", Result.Inst.Items[0].B, name + "Item 0, property B is right.");
            Assert.AreEqual("NotWorkAsExpected.Test2A", Result.Inst.Items[1].A, name + "Item 1, property A is right.");
            Assert.AreEqual("NotWorkAsExpected.Test2B", Result.Inst.Items[1].B, name + "Item 1, property B is right.");
        }
Exemple #8
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "RemoveOldCache/{container}")] HttpRequest req,
            string container)
        {
            try
            {
                IImageService     service          = Utilities.Utilities.GetImageService();
                IContainerService containerService = new ContainerClass(container);

                if (!service.CheckIfContainerExists(containerService))
                {
                    return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                               HttpStatusCode.BadRequest, "Provided container is invalid"));
                }

                int daysAfterImageCacheWillBeDeleted = Utilities.Utilities.DaysAfterImageCacheWillBeDeleted;

                service.RemoveOldCache(containerService, daysAfterImageCacheWillBeDeleted);

                return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                           HttpStatusCode.OK, "Old Cache was successfully removed"));
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                           HttpStatusCode.InternalServerError, ""));
            }
        }
        public void Should_Match_BuiltIn_Property_with_CustomSelector()
        {
            //Create an instance of our test class
            var testInstance = new ContainerClass();

            var nameConst = "AaronConst";

            var fake = new Fake <ContainerClass>();

            //Run some tests before we add the custom selector
            var standardFakeInstance = fake.Generate();

            Assert.AreNotEqual(nameConst, standardFakeInstance.Name);

            //Add the custom selector for the Member field
            var selector = fake.SetProperty(x => x.Name, () => nameConst);

            //Assert.IsTrue(selector.CanBind(typeof(string)));

            //Generate a new fake with the custom selector implemented
            var customFakeInstance = fake.Generate();

            Assert.AreEqual(nameConst, customFakeInstance.Name);
            Assert.AreNotEqual(nameConst, customFakeInstance.OtherName);
        }
        public async Task <IActionResult> Edit(string id, [Bind("ContainerNumber,OceanFreightETA,TimeToYard,ClientCompanyName,HandlerName,IfCartageOnly,IfRequireDelivery,IfRequireStorage,IfBookedCartage,IfEnteredCartonCloud,ChargeFrom,IfExtraLeg,IfInvoiced")] ContainerClass containerClass)
        {
            if (id != containerClass.ContainerNumber)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(containerClass);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ContainerClassExists(containerClass.ContainerNumber))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(containerClass));
        }
Exemple #11
0
 public Container(int pos)
 {
     _containerType     = ContainerType.NONE;
     _containerClass    = ContainerClass.Empty;
     _isEmpty           = true;
     _containerPosition = pos;
     _dateArrived       = DateTime.Now;
 }
    static void Main(string[] args)
    {
        var o = new ContainerClass();

        o.Values = new List <SomeClass> {
            new SomeClass <int>(), new SomeClass <long>()
        };

        var xml = Atlas.Xml.Serializer.Serialize(o, true);
    }
        public async Task <IActionResult> Create([Bind("ContainerNumber,OceanFreightETA,TimeToYard,ClientCompanyName,HandlerName,IfCartageOnly,IfRequireDelivery,IfRequireStorage,IfBookedCartage,IfEnteredCartonCloud,ChargeFrom,IfExtraLeg,IfInvoiced")] ContainerClass containerClass)
        {
            if (ModelState.IsValid)
            {
                _context.Add(containerClass);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(containerClass));
        }
Exemple #14
0
 public void emptyContainer()
 {
     _containerType   = ContainerType.NONE;
     _containerClass  = ContainerClass.Empty;
     _isEmpty         = true;
     _dateArrived     = DateTime.Now;
     _hiree           = "";
     _colour          = "";
     _containerNumber = 0;
     _price           = 0;
     _serialno        = "";
 }
Exemple #15
0
            public void CorrectlyHandlesSerializationOfCollectionsWithAbstractClasses()
            {
                var collection = new ContainerClass();

                collection.Items.Add(new DerivedClass {
                    Name = "item 1"
                });

                var clonedGraph = SerializationTestHelper.SerializeAndDeserialize(collection, SerializationFactory.GetXmlSerializer());

                Assert.AreEqual(collection, clonedGraph);
            }
Exemple #16
0
        public void Bugfix263_Akka_HyperionSerializer_should_serialize_ActorPath_list()
        {
            var actor     = Sys.ActorOf(Props.Create <MyActor>());
            var container = new ContainerClass(new List <ActorPath> {
                actor.Path, actor.Path
            });
            var serialized   = _serializer.ToBinary(container);
            var deserialized = _serializer.FromBinary <ContainerClass>(serialized);

            deserialized.Destinations.Count.Should().Be(2);
            deserialized.Destinations[0].Should().Be(deserialized.Destinations[1]);
        }
 private void GoToService_Executed(object sender, ExecutedRoutedEventArgs e)
 {
     try
     {
         IPersonService proxy = ContainerClass.GetObject <IPersonService>();
         int            val   = proxy.GetConsistency();
         MessageBox.Show(val.ToString());
     }
     catch
     {
     }
 }
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     try
     {
         IPersonService proxy = ContainerClass.GetObject <IPersonService>();
         //List<Person> persons = proxy.GetPersons();
         Console.WriteLine(proxy.GetCount());
         Console.WriteLine(proxy.GetCount());
     }
     catch (Exception ex)
     {
     }
 }
        private static ContainerClass BuildSampleObject()
        {
            var testObject = new ContainerClass
            {
                S        = "sample",
                Excluded = new ExcludedClass {
                    ExcludedString = "shouldn't be serialized"
                },
                Included = new IncludedClass {
                    IncludedString = "serialized"
                }
            };

            return(testObject);
        }
Exemple #20
0
            public void CorrectlyHandlesSerializationOfCollectionsWithAbstractClasses()
            {
                var collection = new ContainerClass();

                collection.Items.Add(new DerivedClass {
                    Name = "item 1"
                });

                TestSerializationOnAllSerializers((serializer, description) =>
                {
                    var clonedGraph = SerializationTestHelper.SerializeAndDeserialize(collection, serializer);

                    Assert.AreEqual(collection, clonedGraph, description);
                }, false);
            }
        private void Colour_Selector(Button btn, ContainerClass colour)
        {
            //Function that sets the Button style depending on the type of container.

            if (colour == ContainerClass.SelfStorage)
            {
                btn.FlatAppearance.BorderColor = Color.ForestGreen;
                btn.FlatAppearance.BorderSize  = 2;
            }

            if (colour == ContainerClass.AsNew)
            {
                btn.FlatAppearance.BorderColor = Color.RoyalBlue;
                btn.FlatAppearance.BorderSize  = 2;
            }

            if (colour == ContainerClass.Hire)
            {
                btn.FlatAppearance.BorderColor = Color.DarkTurquoise;
                btn.FlatAppearance.BorderSize  = 2;
            }

            if (colour == ContainerClass.HireDirty)
            {
                btn.FlatAppearance.BorderColor = Color.Crimson;
                btn.FlatAppearance.BorderSize  = 2;
            }

            if (colour == ContainerClass.SecondHand)
            {
                btn.FlatAppearance.BorderColor = Color.Indigo;
                btn.FlatAppearance.BorderSize  = 2;
            }

            if (colour == ContainerClass.Empty)
            {
                btn.FlatAppearance.BorderColor = Color.Empty;
                btn.FlatAppearance.BorderSize  = 1;
            }

            if (colour == ContainerClass.YardHire)
            {
                btn.FlatAppearance.BorderColor = Color.DarkOrange;
                btn.FlatAppearance.BorderSize  = 2;
            }
        }
Exemple #22
0
            public bool Equals(ContainerClass other)
            {
                if (ReferenceEquals(null, other))
                {
                    return(false);
                }

                if (ReferenceEquals(this, other))
                {
                    return(true);
                }

                if (ReferenceEquals(other.Elements, Elements))
                {
                    return(true);
                }

                if (other.Elements == null && Elements != null)
                {
                    return(false);
                }

                if (other.Elements != null && Elements == null)
                {
                    return(false);
                }

                if (other.Elements != null && Elements != null)
                {
                    if (other.Elements.Count != Elements.Count)
                    {
                        return(false);
                    }

                    for (int i = 0; i < Elements.Count; i++)
                    {
                        if (!Equals(other.Elements[i], Elements[i]))
                        {
                            return(false);
                        }
                    }
                }

                return(true);
            }
Exemple #23
0
        void ProcessSection(Section section, ContainerClass sections, string datapath = null, FileSystem vfs = null)
        {
            var tgt = sections.GetSection(section.Name);

            if (tgt == null)
            {
                FLLog.Warning("Ini", "Unknown section " + section.Name + FormatLine(section.File, section.Line));
                return;
            }
            if (tgt.Field == null)
            {
                GetFromSection(section, tgt.Type, this);
            }
            else
            {
                if (tgt.Delimiters != null)
                {
                    foreach (var ch in Chunk(tgt.Delimiters, section))
                    {
                        var childObject = GetFromSection(ch, tgt.Type, null, datapath, vfs);
                        if (childObject != null)
                        {
                            var list = tgt.Field.GetValue(this);
                            tgt.Add.Invoke(list, new object[] { childObject });
                        }
                    }
                }
                else
                {
                    var parsed = GetFromSection(section, tgt.Type, null, datapath, vfs);
                    if (parsed != null)
                    {
                        if (tgt.Add != null)
                        {
                            var list = tgt.Field.GetValue(this);
                            tgt.Add.Invoke(list, new object[] { parsed });
                        }
                        else
                        {
                            tgt.Field.SetValue(this, parsed);
                        }
                    }
                }
            }
        }
        public void A_collection_of_objects_should_be_properly_serialized()
        {
            var message = new ContainerClass
            {
                Elements = new List <OuterClass>
                {
                    new OuterClass {
                        Inner = new InnerClass {
                            Name = "Chris"
                        }
                    },
                    new OuterClass {
                        Inner = new InnerClass {
                            Name = "David"
                        }
                    }
                }
            };

            TestSerialization(message);
        }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "ManageDatabase/{container}/{secKey}")] HttpRequest req,
            string container,
            string secKey)
        {
            try
            {
                IImageService     service          = Utilities.Utilities.GetImageService();
                IContainerService containerService = new ContainerClass(container);

                if (service.GetImageSecurityHash(containerService.GetContainerName(), Utilities.Utilities.ContainerRemoveKey) != secKey)
                {
                    return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                               HttpStatusCode.NotFound, "Provided SecKey is invalid"));
                }


                if (!service.CheckIfContainerExists(containerService))
                {
                    return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                               HttpStatusCode.NotFound, "Provided container is invalid"));
                }

                IDatabaseService databaseService = Utilities.Utilities.GetDatabaseService();

                databaseService.CreateTableIfNotExists();
                databaseService.RestoreDataForContainer(service, containerService);
                databaseService.CompareAndCorrectDbDataForContainer(service, containerService);


                return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                           HttpStatusCode.OK, $"Table data for container  was successfully restored"));
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                           HttpStatusCode.InternalServerError, ""));
            }
        }
        public double CalculateHarborFee(ContainerClass containerClass, FeeExempt exempt)
        {
            var container = ReturnHeaviestContainer();
            var weight    = container.FirstOrDefault().Weight;
            var harborFee = 0.0;

            if (exempt != FeeExempt.Yes)
            {
                switch (containerClass)
                {
                case ContainerClass.TwentyFoot:
                    harborFee = weight / (int)containerClass;
                    break;

                case ContainerClass.FourtyFoot:
                    harborFee = (weight / (int)containerClass) * 45750;
                    if (exempt == FeeExempt.Variable)
                    {
                        if (harborFee > 150000)
                        {
                            harborFee = harborFee / 2;
                        }
                    }
                    break;

                default:
                    break;
                }
            }
            else
            {
                harborFee = weight * 1000;
            }

            return(harborFee);
        }
            public void CorrectlyHandlesSerializationOfCollectionsWithAbstractClasses()
            {
                var collection = new ContainerClass();
                collection.Items.Add(new DerivedClass { Name = "item 1" });

                var clonedGraph = SerializationTestHelper.SerializeAndDeserialize(collection, SerializationFactory.GetXmlSerializer());

                Assert.AreEqual(collection, clonedGraph);
            }
Exemple #28
0
        private object CreateObjectFromContainer(ContainerClass JsonSerializedObject)
        {
            var NullArguments = JsonSerializedObject.Constructor;

            if (NullArguments == null)
            {
                return(Activator.CreateInstance(Type.GetType(JsonSerializedObject.Name)));
            }

            int Arguments = JsonSerializedObject.Constructor.Count();

            switch (Arguments)
            {
            case 0:
                return(Activator.CreateInstance(Type.GetType(JsonSerializedObject.Name)));

            case 1:
                return(Activator.CreateInstance(Type.GetType(JsonSerializedObject.Name),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[0])
                                                ));

            case 2:
                return(Activator.CreateInstance(Type.GetType(JsonSerializedObject.Name),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[0]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[1])
                                                ));

            case 3:
                return(Activator.CreateInstance(Type.GetType(JsonSerializedObject.Name),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[0]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[1]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[2])
                                                ));

            case 4:
                return(Activator.CreateInstance(Type.GetType(JsonSerializedObject.Name),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[0]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[1]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[2]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[3])
                                                ));

            case 5:
                return(Activator.CreateInstance(Type.GetType(JsonSerializedObject.Name),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[0]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[1]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[2]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[3]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[4])
                                                ));

            case 6:
                return(Activator.CreateInstance(Type.GetType(JsonSerializedObject.Name),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[0]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[1]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[2]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[3]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[4]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[5])
                                                ));

            case 7:
                return(Activator.CreateInstance(Type.GetType(JsonSerializedObject.Name),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[0]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[1]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[2]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[3]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[4]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[5]),
                                                CheckIfArgumentIsClass(JsonSerializedObject.Constructor[6])
                                                ));

            default:
                throw new Exception("Too many constructor arguments for " + JsonSerializedObject.Name + " class.");
            }
        }
Exemple #29
0
 public void SetUp()
 {
     data = KVSerializer.Deserialize<ContainerClass>(TestDataHelper.ReadTextResource("Text.duplicate_keys_object.vdf"));
 }
Exemple #30
0
        public void TestSerializeMultiple()
        {
            Console.WriteLine("Testing embedded behaviour of AVLTree, AVLHashmap, QueuedAVLTree");

            Person anna = new Person()
            {
                name = "Anna", age = 30
            };
            Person berta = new Person()
            {
                name = "Berta", age = 23
            };
            Person carla = new Person()
            {
                name = "Carla", age = 26
            };
            Person diane = new Person()
            {
                name = "Diane", age = 27
            };

            ContainerClass container = new ContainerClass();

            container.tree.Add(anna, new Couple()
            {
                man = anna, woman = berta
            });

            container.hashmap.Add(anna, new Couple()
            {
                man = anna, woman = berta
            });
            container.hashmap.Add(berta, new Couple()
            {
                man = berta, woman = carla
            });
            container.hashmap.Add(carla, new Couple()
            {
                man = carla, woman = anna
            });

            Console.WriteLine("Serializing...");
            Serializer.WriteXmlData(container, "container");

            Console.WriteLine("Deserializing...");
            container = null;
            container = Serializer.ReadXmlData <ContainerClass>("container");

            Console.WriteLine("Validating...");

            Assert.IsTrue(container.tree.Count == 1);
            Assert.IsTrue(container.hashmap.Count == 3);

            Assert.IsTrue(container.one == "1");
            Assert.IsTrue(container.two == "2");
            Assert.IsTrue(container.three == "3");

            Assert.IsTrue(container.tree[anna].Equals(new Couple()
            {
                man = anna, woman = berta
            }));

            Assert.IsTrue(container.hashmap[anna].Equals(new Couple()
            {
                man = anna, woman = berta
            }));
            Assert.IsTrue(container.hashmap[berta].Equals(new Couple()
            {
                man = berta, woman = carla
            }));
            Assert.IsTrue(container.hashmap[carla].Equals(new Couple()
            {
                man = carla, woman = anna
            }));
        }
Exemple #31
0
        static ContainerClass GetContainerInfo(Type t)
        {
            lock (_cLock)
            {
                ContainerClass cinfo;
                if (containerclasses.TryGetValue(t, out cinfo))
                {
                    return(cinfo);
                }
                cinfo = new ContainerClass();
                var sections = new List <ReflectionSection>();
                foreach (var field in t.GetFields(F_CLASSMEMBERS))
                {
                    foreach (var attr in field.GetCustomAttributes <SectionAttribute>())
                    {
                        var s = new ReflectionSection()
                        {
                            Name = attr.Name
                        };
                        var fieldType = field.FieldType;
                        //Handle lists
                        if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(List <>))
                        {
                            s.Add = fieldType.GetMethod("Add", F_CLASSMEMBERS);
                            if (s.Add == null)
                            {
                                throw new Exception();
                            }
                            fieldType = fieldType.GetGenericArguments()[0]; // use this...
                        }
                        if (attr.Type != null)
                        {
                            s.Type = GetSectionInfo(attr.Type);
                        }
                        else
                        {
                            s.Type = GetSectionInfo(fieldType);
                        }
                        s.Field      = field;
                        s.Delimiters = attr.Delimiters;
                        sections.Add(s);
                    }
                }
                foreach (var attr in t.GetCustomAttributes <SelfSectionAttribute>())
                {
                    var s = new ReflectionSection()
                    {
                        Name = attr.Name
                    };
                    s.Type = GetSectionInfo(t);
                    sections.Add(s);
                }

                cinfo.Sections      = sections.ToArray();
                cinfo.SectionHashes = new uint[cinfo.Sections.Length];
                for (int i = 0; i < cinfo.SectionHashes.Length; i++)
                {
                    cinfo.SectionHashes[i] = HashLC(cinfo.Sections[i].Name);
                }
                return(cinfo);
            }
        }
Exemple #32
0
 public void LoadBuiltinClasses()
 {
     classes["Int"]               = new IntClass();
     classes["Float"]             = new FloatClass();
     classes["Boolean"]           = new BooleanClass();
     classes["String"]            = new StringClass();
     classes["Char"]              = new CharClass();
     classes["Byte"]              = new ByteClass();
     classes["Message"]           = new MessageClass();
     classes["Unassigned"]        = new UnassignedClass();
     classes["Tuple"]             = new TupleClass();
     classes["NameValue"]         = new NameValueClass();
     classes["Lambda"]            = new LambdaClass();
     classes["Void"]              = new VoidClass();
     classes["Some"]              = new SomeClass();
     classes["None"]              = new NoneClass();
     classes["Array"]             = new ArrayClass();
     classes["Iterator"]          = new IteratorClass();
     classes["LazyIterator"]      = new LazyIteratorClass();
     classes["StreamIterator"]    = new StreamIteratorClass();
     classes["Any"]               = new AnyClass();
     classes["Placeholder"]       = new PlaceholderClass();
     classes["Range"]             = new RangeClass();
     classes["Dictionary"]        = new DictionaryClass();
     classes["Container"]         = new ContainerClass();
     classes["Unmatched"]         = new UnmatchedClass();
     classes["Complex"]           = new ComplexClass();
     classes["Rational"]          = new RationalClass();
     classes["Long"]              = new LongClass();
     classes["Lazy"]              = new LazyClass();
     classes["YieldingInvokable"] = new YieldingInvokableClass();
     classes["Del"]               = new DelClass();
     classes["Slice"]             = new SliceClass();
     classes["End"]               = new EndClass();
     classes["List"]              = new ListClass();
     classes["Arguments"]         = new ArgumentsClass();
     classes["Symbol"]            = new SymbolClass();
     classes["Infinity"]          = new InfinityClass();
     classes["OpenRange"]         = new OpenRangeClass();
     classes["KeyValue"]          = new KeyValueClass();
     classes["Regex"]             = new RegexClass();
     classes["Pattern"]           = new PatternClass();
     classes["PackageFunction"]   = new PackageFunctionClass();
     classes["Sys"]               = new SysClass();
     classes["Math"]              = new MathClass();
     classes["RuntimeFunction"]   = new RuntimeFunctionClass();
     classes["Reference"]         = new ReferenceClass();
     classes["Group"]             = new RegexGroupClass();
     classes["Match"]             = new RegexMatchClass();
     classes["Date"]              = new DateClass();
     classes["Interval"]          = new IntervalClass();
     classes["TypeConstraint"]    = new TypeConstraintClass();
     classes["ByteArray"]         = new ByteArrayClass();
     classes["Selector"]          = new SelectorClass();
     classes["Number"]            = new NumberClass();
     classes["Collection"]        = new CollectionClass();
     classes["TextFinding"]       = new TextFindingClass();
     classes["SkipTake"]          = new SkipTakeClass();
     classes["Constructor"]       = new ConstructorClass();
     classes["MutString"]         = new MutStringClass();
     classes["Error"]             = new ErrorClass();
     classes["Success"]           = new SuccessClass();
     classes["Failure"]           = new FailureClass();
     classes["Optional"]          = new OptionalClass();
     classes["Result"]            = new ResultClass();
     classes["Monad"]             = new MonadClass();
     classes["Unit"]              = new UnitClass();
     classes["YieldReturn"]       = new YieldReturnClass();
     classes["Index"]             = new IndexClass();
     classes["Cycle"]             = new CycleClass();
     classes["Set"]               = new SetClass();
 }
        void ProcessSection(Section section, ContainerClass sections, string datapath = null, FileSystem vfs = null)
        {
            var tgt = sections.GetSection(section.Name);

            if (tgt == null)
            {
                FLLog.Warning("Ini", "Unknown section " + section.Name + FormatLine(section.File, section.Line));
                return;
            }
            if (tgt.Field == null)
            {
                GetFromSection(section, tgt.Type, this);
            }
            else
            {
                if (tgt.Delimiters != null)
                {
                    foreach (var ch in Chunk(tgt.Delimiters, section))
                    {
                        var childObject = GetFromSection(ch, tgt.Type, null, datapath, vfs);
                        if (childObject != null)
                        {
                            var list = (IList)tgt.Field.GetValue(this);
                            list.Add(childObject);
                        }
                    }
                }
                else
                {
                    var parsed = GetFromSection(section, tgt.Type, null, datapath, vfs);
                    if (parsed != null)
                    {
                        if (tgt.IsList)
                        {
                            var list = (IList)tgt.Field.GetValue(this);
                            if (tgt.AttachToParent)
                            {
                                var count = list.Count;
                                if (count <= 0)
                                {
                                    FLLog.Warning("Ini", $"Section {section.Name} has no parent {FormatLine(section.File, section.Line)}");
                                    return;
                                }
                                var  parent     = list[count - 1];
                                bool success    = false;
                                var  parentInfo = GetSectionInfo(parent.GetType());
                                foreach (var cs in parentInfo.ChildSections)
                                {
                                    if (cs.Name.Equals(section.Name, StringComparison.OrdinalIgnoreCase))
                                    {
                                        var ls2 = (IList)cs.Field.GetValue(parent);
                                        ls2.Add(parsed);
                                        success = true;
                                        break;
                                    }
                                }
                                if (!success)
                                {
                                    FLLog.Warning("Ini",
                                                  $"Type {parentInfo.GetType().Name} does not accept child section {section.Name} {FormatLine(section.File, section.Line)}");
                                }
                            }
                            else
                            {
                                list.Add(parsed);
                            }
                        }
                        else
                        {
                            tgt.Field.SetValue(this, parsed);
                        }
                    }
                }
            }
        }
Exemple #34
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "Upload")] HttpRequest req)
        {
            try
            {
                if (!req.Form.Files.Any() || req.Form["container"] == string.Empty)
                {
                    return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                               HttpStatusCode.BadRequest, "invalid request data"));
                }

                IImageService service = Utilities.Utilities.GetImageService();

                IContainerService container = new ContainerClass(req.Form["container"]);

                if (!service.CheckIfContainerNameIsValid(container))
                {
                    return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                               HttpStatusCode.BadRequest, "invalid container name"));
                }

                foreach (var imageFile in req.Form.Files)
                {
                    if (!service.CheckIfFileIsSupported(imageFile.FileName))
                    {
                        return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                                   HttpStatusCode.BadRequest, "invalid image format"));
                    }

                    if (service.GetUploadImageSecurityKey(container.GetContainerName(), imageFile.FileName, imageFile.Length.ToString()) != imageFile.Name)
                    {
                        return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                                   HttpStatusCode.Forbidden, ""));
                    }
                }

                List <string>    notUploadedFiles = new List <string>();
                List <ImageData> filesToUpload    = new List <ImageData>();

                IDatabaseService databaseService = Utilities.Utilities.GetDatabaseService();

                foreach (var imageToUpload in req.Form.Files)
                {
                    string    imagePath    = service.GetImagePathUpload(imageToUpload.FileName);
                    ImageData uploadResult = service.UploadImage(
                        req.Form.Files.GetFile(imageToUpload.Name).OpenReadStream(),
                        container,
                        imagePath);

                    if (uploadResult.ImageName.IsNullOrEmpty())
                    {
                        notUploadedFiles.Add(imageToUpload.FileName);
                    }
                    else
                    {
                        filesToUpload.Add(uploadResult);
                    }
                }

                if (filesToUpload.Any())
                {
                    databaseService.SaveImagesData(filesToUpload);
                }

                if (notUploadedFiles.Any())
                {
                    return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                               HttpStatusCode.MultiStatus, JsonConvert.SerializeObject(notUploadedFiles)));
                }


                return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                           HttpStatusCode.Created, "Uploaded successfully"));
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return(Utilities.Utilities.GetHttpResponseMessage_ReturnsStatusCodeAndMessage(
                           HttpStatusCode.InternalServerError, "Something gone wrong"));
            }
        }