public IProductRecipe ConvertRecipeBack(RecipeModel recipe, IProductType productType)
        {
            IProductRecipe productRecipe;

            if (recipe.Id == 0)
            {
                var type = ReflectionTool.GetPublicClasses <IProductRecipe>(t => t.Name == recipe.Type).First();
                productRecipe = (IProductRecipe)Activator.CreateInstance(type);
            }
            else
            {
                productRecipe = RecipeManagement.Get(recipe.Id);
            }

            productRecipe.Name     = recipe.Name;
            productRecipe.Revision = recipe.Revision;
            productRecipe.State    = recipe.State;

            // Only load workplan if it changed
            var workplanRecipe = productRecipe as IWorkplanRecipe;

            if (workplanRecipe != null && workplanRecipe.Workplan?.Id != recipe.WorkplanId)
            {
                workplanRecipe.Workplan = WorkplanManagement.LoadWorkplan(recipe.WorkplanId);
            }

            if (productRecipe.Product == null)
            {
                productRecipe.Product = productType;
            }

            switch (recipe.Classification)
            {
            case RecipeClassificationModel.Unset:
                productRecipe.Classification = RecipeClassification.Unset;
                break;

            case RecipeClassificationModel.Default:
                productRecipe.Classification = RecipeClassification.Default;
                break;

            case RecipeClassificationModel.Alternative:
                productRecipe.Classification = RecipeClassification.Alternative;
                break;

            case RecipeClassificationModel.Intermediate:
                productRecipe.Classification = RecipeClassification.Intermediate;
                break;

            case RecipeClassificationModel.Part:
                productRecipe.Classification = RecipeClassification.Part;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            EntryConvert.UpdateInstance(productRecipe, recipe.Properties, RecipeSerialization);
            return(productRecipe);
        }
        private void UpdateCollection(IList value, IEnumerable <PartModel> parts)
        {
            // Track which part links are still represented by the models
            var unused = new List <IProductPartLink>(value.OfType <IProductPartLink>());
            // Iterate over the part models
            // Create or update the part links
            var elemType = value.GetType().GetGenericArguments()[0];

            foreach (var partModel in parts)
            {
                var match = unused.Find(r => r.Id == partModel.Id);
                if (match == null)
                {
                    match = (IProductPartLink)Activator.CreateInstance(elemType);
                    value.Add(match);
                }
                else
                {
                    unused.Remove(match);
                }
                EntryConvert.UpdateInstance(match, partModel.Properties);
                match.Product = (ProductType)ProductManager.LoadType(partModel.Product.Id);
            }

            // Clear all values no longer present in the model
            foreach (var link in unused)
            {
                value.Remove(link);
            }
        }
예제 #3
0
        public void SetConfig(string moduleName, SaveConfigRequest request)
        {
            try
            {
                var module        = GetModuleFromManager(moduleName);
                var serialization = CreateSerialization(module);
                var config        = GetConfig(module, true);
                EntryConvert.UpdateInstance(config, request.Config.Root, serialization);
                ConfigManager.SaveConfiguration(config, request.UpdateMode == ConfigUpdateMode.UpdateLiveAndSave);

                if (request.UpdateMode == ConfigUpdateMode.SaveAndReincarnate)
                {
                    // This has to be done parallel so we can also reincarnate the Maintenance itself
                    ParallelOperations.ExecuteParallel(() => ModuleManager.ReincarnateModule(module));
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(LogLevel.Warning, ex, "Failed to save config of {0}", moduleName);
#if USE_WCF
                var ctx = WebOperationContext.Current;
                // ReSharper disable once PossibleNullReferenceException
                ctx.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
#else
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
#endif
            }
        }
        public void AddItemToCollectionWhichIsArray()
        {
            //Arrange
            var dummy = new DummyClassIList();

            dummy.Number      = 10;
            dummy.Name        = "Thomas";
            dummy.SingleClass = null;
            dummy.SubArray    = new[] { new SubClass {
                                            Foo = (float)1.2, Enum = DummyEnum.ValueB
                                        } };
            dummy.SubList = new List <SubClass> {
                new SubClass {
                    Foo = (float)3.4, Enum = DummyEnum.ValueA
                }
            };
            dummy.SubEnumerable = new List <SubClass> {
                new SubClass {
                    Foo = (float)3.4, Enum = DummyEnum.ValueA
                }
            };
            dummy.SubDictionary = new Dictionary <int, SubClass>();
            dummy.SubIList      = new int[] { 1, 2, 3, 7 };

            var entry = EntryConvert.EncodeObject(dummy);
            var x     = entry.SubEntries.FirstOrDefault(e => e.Identifier == "SubIList");

            x.SubEntries.Add(x.Prototypes.First());

            //Act
            EntryConvert.UpdateInstance(dummy, entry);

            //Assert
            Assert.AreEqual(dummy.SubIList.Count, 5);
        }
        public void ConvertFromModelAndBackToModel()
        {
            // Arrange
            var dummyClass       = CreateDummyServer();
            var dummyClassClient = new EntryModelDummyClient();

            // Act
            var serverEntry = EntryConvert.EncodeObject(dummyClass, new DefaultSerialization {
                FormatProvider = new CultureInfo("en-us")
            });

            var clientConverter = EntryToModelConverter.Create <EntryModelDummyClient>(new CultureInfo("en-us"));

            clientConverter.FromModel(serverEntry, dummyClassClient);

            // Assert
            // Check server to client conversion
            Assert.AreEqual(73, dummyClassClient.Value);
            Assert.AreEqual(true, dummyClassClient.HasAnything);
            Assert.AreEqual("0.5", dummyClassClient.Class.Value);
            Assert.AreEqual("ValueB", dummyClassClient.Class.Enum);
            Assert.AreEqual(2, dummyClassClient.Collection.Count());
            Assert.AreEqual(2, dummyClassClient.Dictionary.Count <EntryModelSubClassDummyClient>());
            Assert.AreEqual("15.8", dummyClassClient.Dictionary["1"].Value);
            Assert.AreEqual("Unset", dummyClassClient.Dictionary["1"].Enum);
            Assert.AreEqual("435.2", dummyClassClient.Dictionary["2"].Value);
            Assert.AreEqual("ValueA", dummyClassClient.Dictionary["2"].Enum);

            // Arrange
            dummyClassClient.Value       = 174;
            dummyClassClient.HasAnything = false;
            dummyClassClient.Class.Value = "15.8";
            dummyClassClient.Class.Enum  = "ValueA";
            dummyClassClient.Collection.Remove(dummyClassClient.Collection.First());
            dummyClassClient.Collection.First().Value = "90";
            dummyClassClient.Collection.First().Enum  = "ValueA";
            dummyClassClient.Dictionary["1"].Value = "10076";
            dummyClassClient.Dictionary["1"].Enum  = "ValueB";
            dummyClassClient.Dictionary.Remove("2");

            // Act
            clientConverter.ToModel(dummyClassClient, serverEntry);

            EntryConvert.UpdateInstance(dummyClass, serverEntry, new DefaultSerialization {
                FormatProvider = new CultureInfo("en-us")
            });

            // Assert
            // Check client to server conversion
            Assert.AreEqual(174, dummyClass.Value);
            Assert.AreEqual(false, dummyClass.HasAnything);
            Assert.AreEqual(15.8f, dummyClass.Class.Value);
            Assert.AreEqual(DummyEnum.ValueA, dummyClass.Class.Enum);
            Assert.AreEqual(1, dummyClass.Collection.Count);
            Assert.AreEqual(90f, dummyClass.Collection.First().Value);
            Assert.AreEqual(DummyEnum.ValueA, dummyClass.Collection.First().Enum);
            Assert.AreEqual(1, dummyClass.Dictionary.Count);
            Assert.AreEqual(10076f, dummyClass.Dictionary[1].Value);
            Assert.AreEqual(DummyEnum.ValueB, dummyClass.Dictionary[1].Enum);
        }
예제 #6
0
        /// <summary>
        /// Convert ResourceModel back to resource and/or update its properties
        /// </summary>
        public Resource FromModel(ResourceModel model, HashSet <Resource> resourcesToSave, Resource resource = null)
        {
            // Break recursion if we converted this instance already
            // Try to load by real id first
            if (_resourceCache.ContainsKey(model.Id))
            {
                return(_resourceCache[model.Id]);
            }
            // Otherwise by reference id
            if (model.Id == 0 && _resourceCache.ContainsKey(model.ReferenceId))
            {
                return(_resourceCache[model.ReferenceId]);
            }

            // Only fetch resource object if it was not given
            if (resource == null)
            {
                resource = model.Id == 0
                    ? _resourceGraph.Instantiate(model.Type)
                    : _resourceGraph.Get(model.Id);
            }

            // Write to cache because following calls might only have an empty reference
            if (model.Id == 0)
            {
                _resourceCache[model.ReferenceId] = resource;
            }
            else
            {
                _resourceCache[model.Id] = resource;
            }

            // Do not copy values from partially loaded models
            if (model.PartiallyLoaded)
            {
                return(resource);
            }

            // Add to list if object was created or modified
            if (model.Id == 0 || model.DifferentFrom(resource, _serialization))
            {
                resourcesToSave.Add(resource);
            }

            // Copy standard properties
            resource.Name        = model.Name;
            resource.Description = model.Description;

            // Copy extended properties
            EntryConvert.UpdateInstance(resource.Descriptor, model.Properties, _serialization);

            // Set all other references
            UpdateReferences(resource, resourcesToSave, model);

            return(resource);
        }
        private IProductType ConvertProductBack(ProductModel product)
        {
            // Fetch instance and copy base values
            ProductType converted;

            if (product.Id == 0)
            {
                converted = (ProductType)ProductManager.CreateType(product.Type);
            }
            else
            {
                converted = (ProductType)ProductManager.LoadType(product.Id);
            }

            converted.Identity = new ProductIdentity(product.Identifier, product.Revision);
            converted.Name     = product.Name;
            converted.State    = product.State;

            // Copy extended properties
            var properties = converted.GetType().GetProperties();

            EntryConvert.UpdateInstance(converted, product.Properties, ProductSerialization);

            ConvertFilesBack(converted, product, properties);

            // Save recipes
            var recipes = product.Recipes.Select(r => ConvertRecipeBack(r, converted)).ToList();

            RecipeManagement.Save(product.Id, recipes);

            // Convert parts
            foreach (var partConnector in product.Parts)
            {
                var prop  = properties.First(p => p.Name == partConnector.Name);
                var value = prop.GetValue(converted);
                if (partConnector.IsCollection)
                {
                    UpdateCollection((IList)value, partConnector.Parts);
                }
                else if (partConnector.Parts.Length == 1)
                {
                    if (value == null)
                    {
                        value = Activator.CreateInstance(prop.PropertyType);
                        prop.SetValue(converted, value);
                    }
                    UpdateReference((IProductPartLink)value, partConnector.Parts[0]);
                }
                else if (partConnector.Parts.Length == 0)
                {
                    prop.SetValue(converted, null);
                }
            }

            return(converted);
        }
        public void RemoveEntry(CollectionType type, int prefill, int[] removedIndexes)
        {
            // Arrange
            var obj     = Prebuild(type, prefill);
            var encoded = EntryConvert.EncodeObject(obj);

            // Act
            var colEntry = CollectionEntry(encoded.SubEntries, type);

            if (type == CollectionType.Dictionary)
            {
                colEntry.SubEntries.RemoveAll(e => removedIndexes.Contains(int.Parse(e.Identifier) - 1));
            }
            else
            {
                colEntry.SubEntries.RemoveAll(e => removedIndexes.Contains(int.Parse(e.Identifier)));
            }
            EntryConvert.UpdateInstance(obj, encoded);

            // Assert
            var collection = ExtractCollection(type, obj);
            var totalSize  = prefill - removedIndexes.Length;

            Assert.AreEqual(totalSize, collection.Count, "New size invalid");


            if (type == CollectionType.Dictionary)
            {
                var array = (collection as IEnumerable <KeyValuePair <int, SubClass> >).ToArray();
                for (var i = 0; i < prefill; i++)
                {
                    if (removedIndexes.Contains(i))
                    {
                        continue;
                    }

                    var match = array.FirstOrDefault(e => e.Key == i + 1);
                    Assert.NotNull(match);
                }
            }
            else
            {
                var array = (collection as IEnumerable <SubClass>).ToArray();
                for (var i = 0; i < prefill; i++)
                {
                    if (removedIndexes.Contains(i))
                    {
                        continue;
                    }

                    var match = array.FirstOrDefault(e => e.Foo == i + 1);
                    Assert.NotNull(match);
                }
            }
        }
        private IImportParameters ConvertParametersBack(string importerName, Entry currentParameters, bool updateFirst = false)
        {
            var importer   = Manager.Importers.First(i => i.Name == importerName);
            var parameters = (IImportParameters)EntryConvert.UpdateInstance(importer.Parameters, currentParameters);

            if (updateFirst)
            {
                parameters = importer.Update(parameters);
            }
            return(parameters);
        }
예제 #10
0
        public IProductRecipe ConvertRecipeBack(RecipeModel recipe, IProductRecipe productRecipe, IProductType productType)
        {
            productRecipe.Name     = recipe.Name;
            productRecipe.Revision = recipe.Revision;
            productRecipe.State    = recipe.State;

            // Only load workplan if it changed
            var workplanRecipe = productRecipe as IWorkplanRecipe;

            if (workplanRecipe != null && workplanRecipe.Workplan?.Id != recipe.WorkplanId)
            {
                workplanRecipe.Workplan = WorkplanManagement.LoadWorkplan(recipe.WorkplanId);
            }

            if (productRecipe.Product == null)
            {
                productRecipe.Product = productType;
            }

            EntryConvert.UpdateInstance(productRecipe, recipe.Properties, RecipeSerialization);

            // Do not update a clones classification
            if (productRecipe.Classification.HasFlag(RecipeClassification.Clone))
            {
                return(productRecipe);
            }

            switch (recipe.Classification)
            {
            case RecipeClassificationModel.Unset:
                productRecipe.Classification = RecipeClassification.Unset;
                break;

            case RecipeClassificationModel.Default:
                productRecipe.Classification = RecipeClassification.Default;
                break;

            case RecipeClassificationModel.Alternative:
                productRecipe.Classification = RecipeClassification.Alternative;
                break;

            case RecipeClassificationModel.Intermediate:
                productRecipe.Classification = RecipeClassification.Intermediate;
                break;

            case RecipeClassificationModel.Part:
                productRecipe.Classification = RecipeClassification.Part;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            return(productRecipe);
        }
        public void UpdateDictionary()
        {
            // Arrange
            var dummy = new DictionaryClass
            {
                SubDictionary = new Dictionary <string, int>
                {
                    { "077", 6 },
                    { "088", 9 }
                },
                EnumDictionary = new Dictionary <string, DummyEnum>
                {
                    { "011", DummyEnum.Unset },
                    { "022", DummyEnum.ValueB }
                }
            };

            var encoded = EntryConvert.EncodeObject(dummy);

            var entry1 = encoded.SubEntries[1];
            var entry2 = encoded.SubEntries[2];


            for (var i = 1; i <= 2; i++)
            {
                var newInstance = entry1.Prototypes[0].Instantiate();
                newInstance.Value.Current = (1 + i).ToString();
                newInstance.DisplayName   = "Key" + i;
                entry1.SubEntries.Add(newInstance);
            }

            entry1.SubEntries[0].Value.Current = "123";
            entry1.SubEntries[0].DisplayName   = "022";

            for (var i = 1; i <= 3; i++)
            {
                var newInstance = entry2.Prototypes[0].Instantiate();
                newInstance.Value.Current = ((DummyEnum)(i % 3)).ToString();
                newInstance.DisplayName   = "Key_0121" + i;
                entry2.SubEntries.Add(newInstance);
            }

            entry2.SubEntries[0].Value.Current = DummyEnum.ValueA.ToString();
            entry2.SubEntries[0].DisplayName   = "555";

            // Act
            EntryConvert.UpdateInstance(dummy, encoded);

            // Assert
            Assert.AreEqual(5, dummy.EnumDictionary.Count);
            Assert.AreEqual(4, dummy.SubDictionary.Count);
            Assert.AreEqual(123, dummy.SubDictionary["022"]);
            Assert.AreEqual(DummyEnum.ValueA, dummy.EnumDictionary["555"]);
        }
        public void UpdateEntries(CollectionType type)
        {
            // Arrange
            var obj     = Prebuild(type, 3);
            var encoded = EntryConvert.EncodeObject(obj);

            // Act
            var colEntry = CollectionEntry(encoded.SubEntries, type);

            if (type == CollectionType.Dictionary)
            {
                foreach (var entry in colEntry.SubEntries)
                {
                    //change "Key" + 10
                    entry.DisplayName = "1" + entry.SubEntries[0].Value.Current;
                    // change "Value"
                    entry.SubEntries[0].Value.Current = "1" + entry.SubEntries[0].Value.Current;
                    entry.SubEntries[1].Value.Current = entry.SubEntries[1].Value.Possible[2];
                }

                EntryConvert.UpdateInstance(obj, encoded);

                // Assert
                var collection = ExtractCollection(type, obj);

                for (var i = 0; i < collection.Count; i++)
                {
                    Assert.IsTrue(obj.SubDictionary.ContainsKey(11 + i));
                    Assert.AreEqual((float)11 + i, obj.SubDictionary[11 + i].Foo);
                    Assert.AreEqual(DummyEnum.ValueB, obj.SubDictionary[11 + i].Enum);
                }
            }
            else
            {
                foreach (var entry in colEntry.SubEntries)
                {
                    entry.SubEntries[0].Value.Current = "1" + entry.SubEntries[0].Value.Current;
                    entry.SubEntries[1].Value.Current = entry.SubEntries[1].Value.Possible[2];
                }
                EntryConvert.UpdateInstance(obj, encoded);

                // Assert
                var collection = ExtractCollection(type, obj);

                var array = (collection as IEnumerable <SubClass>).ToArray();

                for (var i = 0; i < collection.Count; i++)
                {
                    Assert.AreEqual((float)11 + i, array[i].Foo);
                    Assert.AreEqual(DummyEnum.ValueB, array[i].Enum);
                }
            }
        }
        private object ConvertParametersBack(string importerName, Entry currentParameters)
        {
            var oldParameters = _productManagement.Importers.FirstOrDefault(i => i.Key == importerName).Value;

            if (oldParameters == null)
            {
                return(null);
            }

            var parameters = EntryConvert.UpdateInstance(oldParameters, currentParameters);

            return(parameters);
        }
        public void UpdatePrimitiveList()
        {
            // Arrange
            var defaultSerialization = new DefaultSerialization {
                FormatProvider = new CultureInfo("en-US")
            };

            var dummy = new ListDummy
            {
                Number     = 0,
                DoubleList = new List <double> {
                    1.7, 2.5, 3
                },
                EnumList = new List <DummyEnum> {
                    DummyEnum.ValueA, DummyEnum.Unset, DummyEnum.ValueB
                }
            };

            var encoded = EntryConvert.EncodeObject(dummy, defaultSerialization);
            var ent     = encoded.SubEntries[1];
            var ent2    = encoded.SubEntries[2];

            // Act
            encoded.SubEntries[0].Value.Current = "5";
            ent.SubEntries[1].Value.Current     = 12.34d.ToString(defaultSerialization.FormatProvider);
            var newInstance = ent.Prototypes[0].Instantiate();

            newInstance.Value.Current = 133.7d.ToString(defaultSerialization.FormatProvider);
            ent.SubEntries.Add(newInstance);

            ent2.SubEntries[1].Value.Current = "ValueB";
            newInstance = ent2.Prototypes[0].Instantiate();
            newInstance.Value.Current = "ValueA";
            ent2.SubEntries.Add(newInstance);

            EntryConvert.UpdateInstance(dummy, encoded, defaultSerialization);

            // Assert
            Assert.AreEqual(5, dummy.Number);
            Assert.AreEqual(4, dummy.DoubleList.Count);
            Assert.AreEqual(1.7, dummy.DoubleList[0]);
            Assert.AreEqual(12.34, dummy.DoubleList[1]);
            Assert.AreEqual(3.0, dummy.DoubleList[2]);
            Assert.AreEqual(133.7, dummy.DoubleList[3]);

            Assert.AreEqual(4, dummy.EnumList.Count);
            Assert.AreEqual(DummyEnum.ValueA, dummy.EnumList[0]);
            Assert.AreEqual(DummyEnum.ValueB, dummy.EnumList[1]);
            Assert.AreEqual(DummyEnum.ValueB, dummy.EnumList[2]);
            Assert.AreEqual(DummyEnum.ValueA, dummy.EnumList[3]);
        }
        public void UpdateArray()
        {
            // Arrange
            var dummy = new ArrayDummy
            {
                Array = new[] { 2, 5, 7 },
                Keys  = new[] { "test1_2", "test_02", "1245" },
                Enums = new[] { DummyEnum.Unset, DummyEnum.ValueB, DummyEnum.ValueA }
            };

            // Act
            var encoded = EntryConvert.EncodeObject(dummy);
            var entry1  = encoded.SubEntries[0];
            var entry2  = encoded.SubEntries[1];
            var entry3  = encoded.SubEntries[2];

            entry1.SubEntries[1].Value.Current = "42";
            var instance1 = encoded.SubEntries[0].Prototypes[0].Instantiate();

            instance1.Value.Current = "1337";
            entry1.SubEntries.Add(instance1);

            entry2.SubEntries[2].Value.Current = "hallo";
            var instance2 = entry2.Prototypes[0].Instantiate();

            instance2.Value.Current = "new_Value";
            entry2.SubEntries.Add(instance2);

            entry3.SubEntries[0].Value.Current = "ValueA";
            var instance3 = entry3.Prototypes[0].Instantiate();

            instance3.Value.Current = "ValueB";
            entry3.SubEntries.Add(instance3);

            EntryConvert.UpdateInstance(dummy, encoded);

            // Assert
            Assert.AreEqual(4, dummy.Array.Length);
            Assert.AreEqual(42, dummy.Array[1]);
            Assert.AreEqual(1337, dummy.Array[3]);
            Assert.AreEqual(4, dummy.Keys.Length);
            Assert.AreEqual("test1_2", dummy.Keys[0]);
            Assert.AreEqual("test_02", dummy.Keys[1]);
            Assert.AreEqual("hallo", dummy.Keys[2]);
            Assert.AreEqual("new_Value", dummy.Keys[3]);
            Assert.AreEqual(DummyEnum.ValueA, dummy.Enums[0]);
            Assert.AreEqual(DummyEnum.ValueB, dummy.Enums[1]);
            Assert.AreEqual(DummyEnum.ValueA, dummy.Enums[2]);
            Assert.AreEqual(DummyEnum.ValueB, dummy.Enums[3]);
        }
        public void MemoryStreamDecode()
        {
            // Arrange
            var testString            = "This is a test";
            var streamDummy           = new MemoryStreamDummy(testString);
            var targetStreamDummy     = new MemoryStreamDummy("");
            var streamInstanceToCheck = targetStreamDummy.MemoryStream;
            var entry = EntryConvert.EncodeObject(streamDummy);

            // Act
            EntryConvert.UpdateInstance(targetStreamDummy, entry);

            // Assert
            var stringValue = Encoding.UTF8.GetString(targetStreamDummy.MemoryStream.ToArray());

            Assert.AreEqual(testString, stringValue);
            Assert.AreNotSame(streamInstanceToCheck, targetStreamDummy.MemoryStream);
        }
예제 #17
0
        private object ConvertParametersBack(string importerName, Entry currentParameters, bool updateFirst = false)
        {
            var importer = ProductManager.Importers.FirstOrDefault(i => i.Name == importerName);

            if (importer == null)
            {
                return(null);
            }

            var parameters = EntryConvert.UpdateInstance(importer.Parameters, currentParameters);

            if (updateFirst)
            {
                parameters = importer.Update(parameters);
            }

            return(parameters);
        }
        public void MemoryStreamDecodeReuseCurrentStreamInitSizeIsGreaterThanNewData()
        {
            // Arrange
            var testString            = "A test";
            var dummyString           = "12345678912345";
            var streamDummy           = new MemoryStreamDummy(testString);
            var targetStreamDummy     = new MemoryStreamDummy(dummyString);
            var streamInstanceToCheck = targetStreamDummy.MemoryStream;
            var entry = EntryConvert.EncodeObject(streamDummy);

            // Act
            EntryConvert.UpdateInstance(targetStreamDummy, entry);

            // Assert
            var stringValue = Encoding.UTF8.GetString(targetStreamDummy.MemoryStream.ToArray());

            Assert.AreEqual(testString, stringValue);
            Assert.AreSame(streamInstanceToCheck, targetStreamDummy.MemoryStream);
        }
        /// <summary>
        /// Convert ResourceModel back to resource and/or update its properties
        /// </summary>
        public Resource FromModel(ResourceModel model, HashSet <Resource> resourcesToSave, Resource resource = null)
        {
            // Break recursion if we converted this instance already
            if (_resourceCache.ContainsKey(model))
            {
                return(_resourceCache[model]);
            }

            // Only fetch resource object if it was not given
            if (resource == null)
            {
                // Get or create resource
                resource = model.Id == 0
                    ? _resourceGraph.Instantiate(model.Type)
                    : _resourceGraph.Get(model.Id);
                _resourceCache[model] = resource;
            }

            // Add to list if object was created or modified
            if (model.Id == 0 || model.DifferentFrom(resource, _serialization))
            {
                resourcesToSave.Add(resource);
            }

            // Copy standard properties
            resource.Name        = model.Name;
            resource.Description = model.Description;

            // Copy extended properties
            if (model.Properties != null)
            {
                EntryConvert.UpdateInstance(resource.Descriptor, model.Properties, _serialization);
            }

            // Set all other references
            if (model.References != null)
            {
                UpdateReferences(resource, resourcesToSave, model);
            }

            return(resource);
        }
        public void SetConfig(string moduleName, SaveConfigRequest request)
        {
            try
            {
                var module        = GetModuleFromManager(moduleName);
                var serialization = CreateSerialization(module);
                var config        = GetConfig(module, true);
                EntryConvert.UpdateInstance(config, request.Config.Root, serialization);
                ConfigManager.SaveConfiguration(config, request.UpdateMode == ConfigUpdateMode.UpdateLiveAndSave);

                if (request.UpdateMode == ConfigUpdateMode.SaveAndReincarnate)
                {
                    // This has to be done parallel so we can also reincarnate the Maintenance itself
                    ParallelOperations.ExecuteParallel(() => ModuleManager.ReincarnateModule(module));
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(LogLevel.Warning, ex, "Failed to save config of {0}", moduleName);
                HttpHelper.SetStatusCode(HttpStatusCode.InternalServerError);
            }
        }
        public void FileStreamDecodeReuseCurrentStream()
        {
            // Arrange
            var testString                   = "This is a test";
            var testFilePath                 = Path.Combine(TestContext.CurrentContext.TestDirectory, "text1.txt");
            var testFilePath2                = Path.Combine(TestContext.CurrentContext.TestDirectory, "text2.txt");
            var streamDummy                  = new FileStreamDummy(testFilePath, FileMode.Create);
            var targetStreamDummy            = new FileStreamDummy(testFilePath2, FileMode.Create);
            var targetStreamDummyInitialData = Encoding.UTF8.GetBytes("12345678901234567890");

            targetStreamDummy.FileStream.Write(targetStreamDummyInitialData, 0, targetStreamDummyInitialData.Length);

            var streamInstanceToCheck = targetStreamDummy.FileStream;
            var testBytes             = Encoding.UTF8.GetBytes(testString);

            streamDummy.FileStream.Write(testBytes, 0, testBytes.Length);

            var entry = EntryConvert.EncodeObject(streamDummy);

            // Act
            EntryConvert.UpdateInstance(targetStreamDummy, entry);

            // Assert
            var buffer = new byte[targetStreamDummy.FileStream.Length];

            targetStreamDummy.FileStream.Seek(0, SeekOrigin.Begin);
            targetStreamDummy.FileStream.Read(buffer, 0, buffer.Length);

            var stringValue = Encoding.UTF8.GetString(buffer);

            Assert.AreEqual(testString, stringValue);
            Assert.AreSame(streamInstanceToCheck, targetStreamDummy.FileStream);

            streamDummy.FileStream.Close();
            File.Delete(testFilePath);
            targetStreamDummy.FileStream.Close();
            File.Delete(testFilePath2);
        }
        private void UpdateCollection(IList value, IEnumerable <PartModel> parts)
        {
            // Track which part links are still represented by the models
            var unused = new List <IProductPartLink>(value.OfType <IProductPartLink>());
            // Iterate over the part models
            // Create or update the part links
            var elemType = value.GetType().GetInterfaces()
                           .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList <>))
                           .Select(i => i.GetGenericArguments()[0]).Single();

            foreach (var partModel in parts)
            {
                if (partModel is null)
                {
                    continue;
                }

                var match = unused.Find(r => r.Id == partModel?.Id);
                if (match == null)
                {
                    match = (IProductPartLink)Activator.CreateInstance(elemType);
                    value.Add(match);
                }
                else
                {
                    unused.Remove(match);
                }

                EntryConvert.UpdateInstance(match, partModel.Properties);
                match.Product = _productManagement.LoadType(partModel.Product.Id);
            }

            // Clear all values no longer present in the model
            foreach (var link in unused)
            {
                value.Remove(link);
            }
        }
예제 #23
0
        public void SetConfigTest()
        {
            TransformerTestConfig config = new TransformerTestConfig();

            //var provider = new TransformationProviderMock(config);
            // tranform a config object
            var configToModel   = new PossibleValuesSerialization(null, null);
            var convertedObject = EntryConvert.EncodeObject(config, configToModel);

            // find the int field to chang its value
            var intFieldEntry = convertedObject.SubEntries.Find(entry => entry.DisplayName == "IntField");

            // check the initial value
            Assert.AreEqual(intFieldEntry.Value.Current, config.IntField.ToString(), "Initially the the gerneric and the object must be the same.");
            // change the value
            intFieldEntry.Value.Current = "999";
            // check that it has changed.
            Assert.AreNotEqual(intFieldEntry.Value.Current, config.IntField.ToString(), "The generic must be changed!");
            // save changes
            EntryConvert.UpdateInstance(config, convertedObject);
            //provider.SetConfig(config);
            // check changes are safed to the config object.
            Assert.AreEqual(intFieldEntry.Value.Current, config.IntField.ToString(), "After set, both must be the same.");
        }
        public void AddEntry(CollectionType type, int prefill, int newValues)
        {
            // Arrange
            var defaultSerialization = new DefaultSerialization();
            var obj     = Prebuild(type, prefill);
            var encoded = EntryConvert.EncodeObject(obj, defaultSerialization);

            // Act
            var colEntry = CollectionEntry(encoded.SubEntries, type);

            if (type == CollectionType.Dictionary)
            {
                for (var i = 1; i <= newValues; i++)
                {
                    var newInstance = colEntry.Prototypes[0].Instantiate();
                    // change "Key" + 10
                    newInstance.DisplayName = (prefill + i).ToString();
                    // change "Value"
                    newInstance.SubEntries[0].Value.Current = (prefill + i).ToString("F2", defaultSerialization.FormatProvider);
                    newInstance.SubEntries[1].Value.Current = newInstance.SubEntries[1].Value.Possible[2];

                    colEntry.SubEntries.Add(newInstance);
                }
            }
            else
            {
                for (var i = 1; i <= newValues; i++)
                {
                    var newInstance = colEntry.Prototypes[0].Instantiate();
                    newInstance.SubEntries[0].Value.Current = (prefill + i).ToString();
                    newInstance.SubEntries[1].Value.Current = newInstance.SubEntries[1].Value.Possible[2];
                    colEntry.SubEntries.Add(newInstance);
                }
            }

            EntryConvert.UpdateInstance(obj, encoded);

            // Assert
            var collection = ExtractCollection(type, obj);
            var totalSize  = prefill + newValues;

            Assert.AreEqual(totalSize, collection.Count, "New size invalid");

            if (type == CollectionType.Dictionary)
            {
                var array = (collection as IEnumerable <KeyValuePair <int, SubClass> >).ToArray();
                for (var i = 0; i < totalSize; i++)
                {
                    Assert.AreEqual((float)i + 1, array[i].Key, "Key not set!");
                    Assert.AreEqual((float)i + 1, array[i].Value.Foo, "Value not set!");
                    var expectedEnum = i < prefill ? DummyEnum.ValueA : DummyEnum.ValueB;
                    Assert.AreEqual(expectedEnum, array[i].Value.Enum, "Enum not set");
                }
            }
            else
            {
                var array = (collection as IEnumerable <SubClass>).ToArray();
                for (var i = 0; i < totalSize; i++)
                {
                    Assert.AreEqual((float)i + 1, array[i].Foo, "Value not set!");
                    var expectedEnum = i < prefill ? DummyEnum.ValueA : DummyEnum.ValueB;
                    Assert.AreEqual(expectedEnum, array[i].Enum, "Enum not set");
                }
            }
        }
        /// <summary>
        /// Convert ResourceModel back to resource and/or update its properties
        /// </summary>
        private Resource FromModel(ResourceModel model, HashSet <long> resourcesToSave, Dictionary <long, Resource> cache, Resource resource = null)
        {
            // Break recursion if we converted this instance already
            // Try to load by real id first
            if (cache.ContainsKey(model.Id))
            {
                return(cache[model.Id]);
            }
            // Otherwise by reference id
            if (model.Id == 0 && cache.ContainsKey(model.ReferenceId))
            {
                return(cache[model.ReferenceId]);
            }

            // Only fetch resource object if it was not given
            if (resource is null)
            {
                if (model.Id == 0 && model.PartiallyLoaded)
                {
                    resource = (Resource)Activator.CreateInstance(_resourceTypeTree[model.Type].ResourceType);
                }
                else if (model.Id == 0)
                {
                    var id = _resourceModification.Create(_resourceTypeTree[model.Type].ResourceType, r => { });
                    resource = _resourceModification.Read <Resource>(id, resource => resource);
                }
                else
                {
                    resource = _resourceModification.Read <Resource>(model.Id, resource => resource);
                }
            }

            // Write to cache because following calls might only have an empty reference
            if (model.Id == 0)
            {
                cache[model.ReferenceId] = resource;
            }
            else
            {
                cache[model.Id] = resource;
            }

            // Do not copy values from partially loaded models
            if (model.PartiallyLoaded)
            {
                return(resource);
            }

            // Add to list if object was created or modified
            if (model.Id == 0 || model.DifferentFrom(resource, _serialization))
            {
                resourcesToSave.Add(resource.Id);
            }

            // Copy standard properties
            resource.Name        = model.Name;
            resource.Description = model.Description;

            // Copy extended properties
            EntryConvert.UpdateInstance(resource.Descriptor, model.Properties, _serialization);

            // Set all other references
            UpdateReferences(resource, resourcesToSave, cache, model);

            return(resource);
        }
예제 #26
0
 private void UpdateReference(IProductPartLink value, PartModel part)
 {
     EntryConvert.UpdateInstance(value, part.Properties);
     value.Product = part.Product is null ? null : ProductManager.LoadType(part.Product.Id);
 }
예제 #27
0
        public IProductType ConvertProductBack(ProductModel source, ProductType converted)
        {
            // Copy base values
            converted.Identity = new ProductIdentity(source.Identifier, source.Revision);
            converted.Name     = source.Name;
            converted.State    = source.State;

            // Save recipes
            var recipes = new List <IProductRecipe>(source.Recipes?.Length ?? 0);

            foreach (var recipeModel in source.Recipes ?? Enumerable.Empty <RecipeModel>())
            {
                IProductRecipe productRecipe;
                if (recipeModel.Id == 0)
                {
                    var type = ReflectionTool.GetPublicClasses <IProductRecipe>(t => t.Name == recipeModel.Type).First();
                    productRecipe = (IProductRecipe)Activator.CreateInstance(type);
                }
                else
                {
                    productRecipe = RecipeManagement.Get(recipeModel.Id);
                }

                ConvertRecipeBack(recipeModel, productRecipe, converted);
                recipes.Add(productRecipe);
            }
            if (recipes.Any())
            {
                RecipeManagement.Save(source.Id, recipes);
            }

            // Product is flat
            if (source.Properties is null)
            {
                return(converted);
            }

            // Copy extended properties
            var properties = converted.GetType().GetProperties();

            EntryConvert.UpdateInstance(converted, source.Properties, ProductSerialization);

            // Copy Files
            ConvertFilesBack(converted, source, properties);

            // Convert parts
            foreach (var partConnector in source.Parts ?? Enumerable.Empty <PartConnector>())
            {
                if (partConnector.Parts is null)
                {
                    continue;
                }

                var prop  = properties.First(p => p.Name == partConnector.Name);
                var value = prop.GetValue(converted);
                if (partConnector.IsCollection)
                {
                    if (value == null)
                    {
                        value = Activator.CreateInstance(typeof(List <>)
                                                         .MakeGenericType(prop.PropertyType.GetGenericArguments().First()));
                        prop.SetValue(converted, value);
                    }
                    UpdateCollection((IList)value, partConnector.Parts);
                }
                else if (partConnector.Parts.Length == 1)
                {
                    if (value == null)
                    {
                        value = Activator.CreateInstance(prop.PropertyType);
                        prop.SetValue(converted, value);
                    }
                    UpdateReference((IProductPartLink)value, partConnector.Parts[0]);
                }
                else if (partConnector.Parts.Length == 0)
                {
                    prop.SetValue(converted, null);
                }
            }

            return(converted);
        }