Пример #1
0
        public void DeeplyNestedExpandoConvert()
        {
            // can't use GetUUT here since this will already involve conversion
            var name      = "Types";
            var jsonTests = Assembly.GetExecutingAssembly().GetManifestResourceStream("JsonConfig.Tests.JSON." + name + ".json");

            using (var sReader = new StreamReader(jsonTests))
            {
                var     json   = sReader.ReadToEnd();
                dynamic parsed = JsonConvert.DeserializeObject <JObject>(json);

                dynamic config = ConfigObject.FromJobject(parsed);

                Assert.AreEqual("bar", config.Foo);
                Assert.AreEqual("bar", Enumerable.First(config.NestedArray).Foo);
                Assert.AreEqual("bar", config.DoubleNestedArray[0].One[0].Foo);

                Assert.IsInstanceOfType(typeof(ConfigObject[]), config.DoubleNestedArray[0].One);
                Assert.AreEqual("bar", config.DoubleNestedArray[0].One[0].Foo);
                Assert.AreEqual(4, config.DoubleNestedArray[0].One.Length);

                Assert.AreEqual("bar", config.DoubleNestedArray[1].Two[0].Foo);
                Assert.AreEqual("bar", config.DoubleNestedArray[1].Two[3].Foo);
                Assert.AreEqual("bar", config.DoubleNestedArray[1].Two[3].Foo);
            }
        }
        private void ConfigureValues(Enumeration enumeration, ConfigObject values)
        {
            int valuesCount = values.GetInt32(new int[] { 1 }); // количество значений

            if (valuesCount == 0)
            {
                return;
            }

            int offset = 2;

            for (int v = 0; v < valuesCount; v++)
            {
                // V.0.1.1.2 - value uuid
                Guid uuid = values.GetUuid(new int[] { v + offset, 0, 1, 1, 2 });
                // V.0.1.2 - value name
                string name = values.GetString(new int[] { v + offset, 0, 1, 2 });
                // P.0.1.3 - value alias descriptor
                string       alias           = string.Empty;
                ConfigObject aliasDescriptor = values.GetObject(new int[] { v + offset, 0, 1, 3 });
                if (aliasDescriptor.Values.Count == 3)
                {
                    // P.0.1.3.2 - value alias
                    alias = values.GetString(new int[] { v + offset, 0, 1, 3, 2 });
                }
                enumeration.Values.Add(new EnumValue()
                {
                    Uuid  = uuid,
                    Name  = name,
                    Alias = alias
                });
            }
        }
Пример #3
0
        private void ConfigureCompoundTypes(InfoBase infoBase, ConfigObject config)
        {
            // 3.1.23.0 = c045099e-13b9-4fb6-9d50-fca00202971e - идентификатор коллекции определяемых типов
            Guid collectionUuid = config.GetUuid(new int[] { 3, 1, 23, 0 });

            if (collectionUuid == new Guid("c045099e-13b9-4fb6-9d50-fca00202971e"))
            {
                // 3.1.23.1 - количество объектов в коллекции
                int count = config.GetInt32(new int[] { 3, 1, 23, 1 });
                if (count == 0)
                {
                    return;
                }

                // 3.1.23 - коллекция определяемых типов
                ConfigObject collection = config.GetObject(new int[] { 3, 1, 23 });

                // 3.1.23.N - идентификаторы файлов определяемых типов
                int          offset = 2;
                CompoundType compound;
                for (int i = 0; i < count; i++)
                {
                    compound = new CompoundType()
                    {
                        FileName = collection.GetUuid(new int[] { i + offset })
                    };
                    ConfigureCompoundType(compound, infoBase);
                    infoBase.CompoundTypes.Add(compound.Uuid, compound);
                }
            }
        }
Пример #4
0
        public TValue?GetValue(ConfigObject inner)
        {
            if (_value == null)
            {
                // Multiple threads can get a property at the same time. We want this to be safe.
                // Because a value could be lazily initialized, lock to ensure multiple threads
                // don't try to update the underlying dictionary at the same time.
                lock (this)
                {
                    // Double-check locking.
                    if (_value == null)
                    {
                        var innerValue = inner.GetValue <TInner>(_key);
                        _value = _valueFactory(innerValue);

                        if (_value != null && innerValue == null)
                        {
                            // Set newly created value
                            SetValue(inner, _value);
                        }
                    }
                }
            }

            return(_value);
        }
Пример #5
0
        public override bool Verify()
        {
            TaskLogger.LogEnter();
            if ("" == this.ObjectIdentity)
            {
                throw new ConditionInitializationException("ObjectIdentity", this);
            }
            if (this.ObjectIdentity == null)
            {
                throw new ConditionInitializationException("ObjectIdentity", this);
            }
            if (null == this.ObjectType)
            {
                throw new ConditionInitializationException("ObjectType", this);
            }
            if (!this.ObjectType.IsSubclassOf(typeof(ConfigObject)) || this.ObjectType.IsAbstract)
            {
                throw new ConditionInitializationException("ObjectType", this, new LocalizedException(Strings.ExceptionInvalidConfigObjectType(this.ObjectType)));
            }
            ConfigObject configObject = ConfigObjectReader.FindById(this.ObjectType, this.ObjectIdentity);
            bool         result       = configObject != null;

            TaskLogger.LogExit();
            return(result);
        }
Пример #6
0
        private void Init()
        {
            if (PropertyInfoItem == null)
            {
                return;
            }
            CurrentApp = PropertyInfoItem.CurrentApp;
            ConfigObject configObject = PropertyInfoItem.ConfigObject;

            if (configObject != null)
            {
                mConfigObject = configObject;
            }
            ObjectPropertyInfo propertyInfo = PropertyInfoItem.PropertyInfo;

            if (propertyInfo != null)
            {
                mPropertyInfo = propertyInfo;
            }
            ResourceProperty propertyValue = PropertyInfoItem.ResourceProperty;

            if (propertyValue != null)
            {
                mPropertyValue = propertyValue;
                string path = propertyValue.Value;
                TxtDirPath.Text = path;
            }
        }
Пример #7
0
        private void WriteToFile(StreamWriter stream, ConfigObject mdObject, int level, string path)
        {
            string indent = level == 0 ? string.Empty : "-".PadLeft(level * 4, '-');

            for (int i = 0; i < mdObject.Values.Count; i++)
            {
                object value = mdObject.Values[i];

                string thisPath = path + (string.IsNullOrEmpty(path) ? string.Empty : ".") + i.ToString();

                if (value is ConfigObject child)
                {
                    stream.WriteLine(indent + "[" + level.ToString() + "] (" + thisPath + ") " + value.ToString());
                    WriteToFile(stream, child, level + 1, thisPath);
                }
                else if (value is string text)
                {
                    stream.WriteLine(indent + "[" + level.ToString() + "] (" + thisPath + ") \"" + text.ToString() + "\"");
                }
                else
                {
                    stream.WriteLine(indent + "[" + level.ToString() + "] (" + thisPath + ") " + value.ToString());
                }
            }
        }
Пример #8
0
        public void Can_get_config_info()
        {
            var config = new ConfigObject
            {
                Field   = "foo",
                Nested1 = new ConfigObject.Nested
                {
                    Field = "bar",
                },
                Nested2 = new ConfigObject.Nested
                {
                    Field = "baz"
                }
            };
            var configuration = new ConfigurationBuilder()
                                .AddInMemoryCollection(new Dictionary <string, string>
            {
                { "foo:bar", "a" },
                { "foo:bar:baz", "b" }
            })
                                .AddObject(config)
                                .AddJsonFile("testappsettings.json", false)
                                .Build();

            var configInfo = configuration.GetConfigInfo();

            configInfo.ShouldNotBeNull();

            _outputHelper.WriteLine(configInfo.ToString());
        }
Пример #9
0
        public void When_supply_non_secret_paths_then_values_should_not_be_hashed()
        {
            var config = new ConfigObject
            {
                Field   = "foo",
                Nested1 = new ConfigObject.Nested
                {
                    Field = "bar",
                },
                Nested2 = new ConfigObject.Nested
                {
                    Field = "baz"
                }
            };
            var configuration = new ConfigurationBuilder()
                                .AddInMemoryCollection(new Dictionary <string, string>
            {
                { "foo:bar", "a" },
                { "foo:bar:baz", "b" }
            })
                                .AddObject(config)
                                .AddJsonFile("testappsettings.json", false)
                                .Build();

            var nonSecretPaths = new HashSet <string>
            {
                "Field",
                "foo:bar:baz"
            };
            var configInfo = configuration.GetConfigInfo(nonSecretPaths);

            configInfo.Items.Single(i => i.Path == "Field").Value.ShouldBe("foo");
            configInfo.Items.Single(i => i.Path == "foo:bar:baz").Value.ShouldBe("b");
            _outputHelper.WriteLine(configInfo.ToString());
        }
Пример #10
0
        private void SaveCTIConfig()
        {
            Init();
            //生成242ConfigObject,绑给CTIConfigObject的ListChildObject,写入CTIConfigObject是CTI类型属性值。将CTIConfigObject写入mList

            if (this.ComCTIType.SelectedIndex != -1)
            {
                var propertyItem = this.ComCTIType.SelectedItem as PropertyValueEnumItem;
                if (propertyItem != null)
                {
                    IntCTIType = propertyItem.Value;
                }
                var property = CTIConfigObject.ListProperties.FirstOrDefault(p => p.PropertyID == 11);
                if (property != null)
                {
                    property.Value = IntCTIType;
                }
            }
            ConfigObject CTIGroup    = WizardHelper.CreateNewConfigObject(CTIConfigObject, 242);
            var          property242 = CTIGroup.ListProperties.FirstOrDefault(p => p.PropertyID == 11);

            if (property242 != null)
            {
                property242.Value = IntCTIType;
            }
            mListCTIConfigObjs.Add(CTIConfigObject);
            mListCTIConfigObjs.Add(CTIGroup);
            MainPage.RefreshConfigObjectItem(CTIObjItem);
            CTICount++;
        }
 private void InitResourceObjects()
 {
     try
     {
         mListConfigObjects.Clear();
         if (mParentObject == null)
         {
             return;
         }
         List <ConfigObject> listItems =
             mParentObject.ListChildObjects.Where(o => o.ObjectType == mObjectType).ToList();
         listItems = listItems.OrderBy(o => o.ID).ToList();
         for (int i = 0; i < listItems.Count; i++)
         {
             ConfigObject configObject = listItems[i];
             configObject.StrIcon = string.Format("Images/{0}", configObject.Icon);
             if (i % 2 == 1)
             {
                 configObject.Background = Brushes.LightGray;
             }
             else
             {
                 configObject.Background = Brushes.Transparent;
             }
             mListConfigObjects.Add(listItems[i]);
         }
     }
     catch (Exception ex)
     {
         ShowException("InitResourceObjects:" + ex.Message);
     }
 }
Пример #12
0
        private void ShowDiffObject(StreamWriter stream, DiffObject parent, int level)
        {
            string indent = level == 0 ? string.Empty : "-".PadLeft(level * 4, '-');

            ConfigObject mdSource = parent.SourceValue as ConfigObject;
            ConfigObject mdTarget = parent.TargetValue as ConfigObject;

            if (mdSource != null && mdTarget != null)
            {
                stream.WriteLine(CreateObjectPresentation(parent, level, indent));
            }
            else if (mdSource != null)
            {
                stream.WriteLine(CreateObjectPresentation(parent, level, indent));
            }
            else if (mdTarget != null)
            {
                stream.WriteLine(CreateObjectPresentation(parent, level, indent));
            }
            else
            {
                stream.WriteLine(CreateDiffPresentation(parent, level, indent));
            }

            foreach (DiffObject diff in parent.DiffObjects)
            {
                ShowDiffObject(stream, diff, level + 1);
            }
        }
Пример #13
0
        public void WriteToml_WhenConfigHasConverter_ConverterGetsUsed()
        {
            // Arrange
            var config = TomlSettings.Create(cfg => cfg
                                             .ConfigureType <TestStruct>(ct => ct
                                                                         .WithConversionFor <TomlInt>(conv => conv
                                                                                                      .FromToml((m, ti) => new TestStruct()
            {
                Value = (int)ti.Value
            })
                                                                                                      .ToToml(ts => ts.Value)
                                                                                                      )
                                                                         .CreateInstance(() => new TestStruct())
                                                                         .TreatAsInlineTable()
                                                                         )
                                             );
            var obj = new ConfigObject()
            {
                S = new TestStruct()
                {
                    Value = 222
                }
            };

            // Act
            var ser = Toml.WriteString(obj, config);

            // Assert
            Assert.Equal("S = 222\r\n", ser);
        }
Пример #14
0
 private void InitBaseChannels()
 {
     try
     {
         if (ParentItem == null)
         {
             return;
         }
         ConfigGroup configGroup = ParentItem.Data as ConfigGroup;
         if (configGroup == null)
         {
             return;
         }
         ConfigObject parentObject = configGroup.ConfigObject;
         if (parentObject == null || parentObject.ObjectType != S1110Consts.RESOURCE_SCREENSERVER)
         {
             return;
         }
         mListBaseChannels.Clear();
         for (int i = 0; i < parentObject.ListChildObjects.Count; i++)
         {
             ConfigObject configObject = parentObject.ListChildObjects[i];
             if (configObject.ObjectType == S1110Consts.RESOURCE_SCREENCHANNEL)
             {
                 mListBaseChannels.Add(configObject);
             }
         }
     }
     catch (Exception ex)
     {
         ShowException(ex.Message);
     }
 }
Пример #15
0
    public static void init()
    {
        if (File.Exists(ConfigFile))
        {
            string       data = File.ReadAllText(ConfigFile);
            ConfigObject obj  = JsonUtility.FromJson <ConfigObject>(data);
            config = obj;

            Debug    = obj.debug;
            Timespan = obj.timespan;

            int id = -1;
            foreach (DataObject d in obj.data)
            {
                if (d.id > id)
                {
                    id = d.id;
                }
            }

            UserId = id + 1;
        }
        else
        {
            UnityEngine.Debug.Log("Config File not found");
            Application.Quit();
        }
    }
        public void Enrich(MetadataObject metadataObject)
        {
            if (!(metadataObject is Enumeration enumeration))
            {
                throw new ArgumentOutOfRangeException();
            }

            ConfigObject configObject = Configurator.FileReader.ReadConfigObject(enumeration.FileName.ToString());

            enumeration.Uuid = configObject.GetUuid(new int[] { 1, 1 });
            enumeration.Name = configObject.GetString(new int[] { 1, 5, 1, 2 });
            ConfigObject alias = configObject.GetObject(new int[] { 1, 5, 1, 3 });

            if (alias.Values.Count == 3)
            {
                enumeration.Alias = configObject.GetString(new int[] { 1, 5, 1, 3, 2 });
            }
            Configurator.ConfigurePropertyСсылка(enumeration);
            Configurator.ConfigurePropertyПорядок(enumeration);

            // 6 - коллекция значений
            ConfigObject values = configObject.GetObject(new int[] { 6 });
            // 6.0 = bee0a08c-07eb-40c0-8544-5c364c171465 - идентификатор коллекции значений
            Guid valuesUuid = configObject.GetUuid(new int[] { 6, 0 });

            if (valuesUuid == new Guid("bee0a08c-07eb-40c0-8544-5c364c171465"))
            {
                ConfigureValues(enumeration, values);
            }
        }
Пример #17
0
        private void ConfigureArticles(Publication publication)
        {
            string       fileName     = publication.FileName.ToString() + ".1";
            ConfigObject configObject = Configurator.FileReader.ReadConfigObject(fileName);

            if (configObject == null)
            {
                return;                       // not found
            }
            int count = configObject.GetInt32(new int[] { 1 });

            if (count == 0)
            {
                return;
            }

            int step = 2;

            for (int i = 1; i <= count; i++)
            {
                Guid            uuid    = configObject.GetUuid(new int[] { i *step });
                AutoPublication setting = (AutoPublication)configObject.GetInt32(new int[] { (i * step) + 1 });
                publication.Articles.Add(uuid, setting);
            }
        }
Пример #18
0
        private void ConfigureSharedProperties(InfoBase infoBase, ConfigObject config)
        {
            // 3.1.8.0 = 15794563-ccec-41f6-a83c-ec5f7b9a5bc1 - идентификатор коллекции общих реквизитов
            Guid collectionUuid = config.GetUuid(new int[] { 3, 1, 8, 0 });

            if (collectionUuid == new Guid("15794563-ccec-41f6-a83c-ec5f7b9a5bc1"))
            {
                // количество объектов в коллекции
                int count = config.GetInt32(new int[] { 3, 1, 8, 1 });
                if (count == 0)
                {
                    return;
                }

                // 3.1.8 - коллекция общих реквизитов
                ConfigObject collection = config.GetObject(new int[] { 3, 1, 8 });

                int            offset = 2;
                SharedProperty property;
                for (int i = 0; i < count; i++)
                {
                    property = new SharedProperty()
                    {
                        FileName = collection.GetUuid(new int[] { i + offset })
                    };
                    ConfigureSharedProperty(property, infoBase);
                    infoBase.SharedProperties.Add(property.FileName, property);
                }
            }
        }
Пример #19
0
        public void Enrich(MetadataObject metadataObject)
        {
            if (!(metadataObject is InfoBase infoBase))
            {
                throw new ArgumentOutOfRangeException();
            }

            ConfigObject configObject = Configurator.FileReader.ReadConfigObject(DBNAMES_FILE_NAME);

            int entryCount = configObject.GetInt32(new int[] { 1, 0 });

            for (int i = 1; i <= entryCount; i++)
            {
                Guid uuid = configObject.GetUuid(new int[] { 1, i, 0 });
                if (uuid == Guid.Empty)
                {
                    continue;
                }

                string token = configObject.GetString(new int[] { 1, i, 1 });
                int    code  = configObject.GetInt32(new int[] { 1, i, 2 });

                ProcessEntry(infoBase, uuid, token, code);
            }
        }
Пример #20
0
 private void Init()
 {
     try
     {
         if (PropertyInfoItem == null)
         {
             return;
         }
         CurrentApp = PropertyInfoItem.CurrentApp;
         ConfigObject configObject = PropertyInfoItem.ConfigObject;
         if (configObject != null)
         {
             mConfigObject = configObject;
         }
         ObjectPropertyInfo propertyInfo = PropertyInfoItem.PropertyInfo;
         if (propertyInfo != null)
         {
             mPropertyInfo = propertyInfo;
         }
         ResourceProperty propertyValue = PropertyInfoItem.ResourceProperty;
         if (propertyValue != null)
         {
             mPropertyValue = propertyValue;
         }
         if (mPropertyValue == null)
         {
             return;
         }
         if (!string.IsNullOrEmpty(mPropertyValue.Value))
         {
             string cardID   = mPropertyValue.Value;
             string cardName = cardID;
             if (mPropertyValue.ListOtherValues != null && mPropertyValue.ListOtherValues.Count > 0)
             {
                 cardName = mPropertyValue.ListOtherValues[0];
             }
             NetworkCardInfo info = new NetworkCardInfo();
             info.ID          = cardID;
             info.Name        = cardName;
             info.Description = string.Format("{0}({1})", cardName, cardID);
             PropertyValueEnumItem item = new PropertyValueEnumItem();
             item.Value       = info.ID;
             item.Display     = info.Name;
             item.Description = info.Description;
             item.Info        = info;
             var temp = mListNetworkCardItems.FirstOrDefault(c => c.Value == cardID);
             if (temp == null)
             {
                 temp = item;
                 mListNetworkCardItems.Add(temp);
             }
             ComboNetworkCards.SelectedItem = temp;
         }
     }
     catch (Exception ex)
     {
         ShowException(ex.Message);
     }
 }
Пример #21
0
        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(pwd.Password))
            {
                MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.PormptSetLoginPwd, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }
            if (pwd.Password != confirmPwd.Password)
            {
                MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.NotSamePwd, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(tbRegNsrsbh.Text))
            {
                MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.NsrsbhNotEmpty, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(tbRegNsrmc.Text))
            {
                MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.NsrsmcNotEmpty, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }
            if (cbxArea.SelectedIndex < 0)
            {
                MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.PromptSelectArea, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(tbRegCode.Text))
            {
                //如果注册码为空,则上传试用注册码  20190419
                tbRegCode.Text = "RJTECH2019";
//                 MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.PormptInputZcm, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
//                 return;
            }

            string errorMsg          = string.Empty;
            bool   isRegisterSuccess = loginService.Register(tbRegCode.Text, tbRegNsrsbh.Text, tbRegNsrmc.Text, pwd.Password, cbxArea.SelectedValue.ToString(), out errorMsg);

            if (!isRegisterSuccess)
            {
                MessageBoxEx.Show(this, errorMsg, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);
                return;
            }
            else
            {
                ConfigObject configObject = new ConfigObject();
                configObject.NSRSBH  = tbRegNsrsbh.Text;
                configObject.NSRMC   = tbRegNsrmc.Text;
                configObject.DQDM    = cbxArea.SelectedValue.ToString();
                configObject.TaxType = GlobalInfo.DeviceType;
                loginService.SaveUserInfo(configObject);
                MessageBoxEx.Show(this, PRO_ReceiptsInvMgr.Resources.Message.RegisterSuccess, PRO_ReceiptsInvMgr.Resources.Message.Tips, MessageBoxExButtons.OK, MessageBoxExIcon.Error);

                ResetRegistControl();
                tbTaxKey.IsEnabled = true;
                TextBlock_MouseLeftButtonDown(tbLogin, null);
            }
        }
        public void Enrich(MetadataObject metadataObject)
        {
            if (!(metadataObject is InformationRegister register))
            {
                throw new ArgumentOutOfRangeException();
            }

            ConfigObject configObject = Configurator.FileReader.ReadConfigObject(register.FileName.ToString());

            register.Name = configObject.GetString(new int[] { 1, 15, 1, 2 });
            ConfigObject alias = configObject.GetObject(new int[] { 1, 15, 1, 3 });

            if (alias.Values.Count == 3)
            {
                register.Alias = configObject.GetString(new int[] { 1, 15, 1, 3, 2 });
            }
            register.UseRecorder = configObject.GetInt32(new int[] { 1, 19 }) != 0;
            register.Periodicity = (RegisterPeriodicity)configObject.GetInt32(new int[] { 1, 18 });

            if (register.Periodicity != RegisterPeriodicity.None)
            {
                Configurator.ConfigurePropertyПериод(register);
            }
            if (register.UseRecorder)
            {
                Configurator.ConfigurePropertyНомерЗаписи(register);
                Configurator.ConfigurePropertyАктивность(register);
            }

            // 4 - коллекция измерений
            ConfigObject properties = configObject.GetObject(new int[] { 4 });
            // 4.0 = 13134203-f60b-11d5-a3c7-0050bae0a776 - идентификатор коллекции измерений
            Guid propertiesUuid = configObject.GetUuid(new int[] { 4, 0 });

            if (propertiesUuid == new Guid("13134203-f60b-11d5-a3c7-0050bae0a776"))
            {
                Configurator.ConfigureProperties(register, properties, PropertyPurpose.Dimension);
            }

            // 3 - коллекция ресурсов
            properties = configObject.GetObject(new int[] { 3 });
            // 3.0 = 13134202-f60b-11d5-a3c7-0050bae0a776 - идентификатор коллекции ресурсов
            propertiesUuid = configObject.GetUuid(new int[] { 3, 0 });
            if (propertiesUuid == new Guid("13134202-f60b-11d5-a3c7-0050bae0a776"))
            {
                Configurator.ConfigureProperties(register, properties, PropertyPurpose.Measure);
            }

            // 7 - коллекция реквизитов
            properties = configObject.GetObject(new int[] { 7 });
            // 7.0 = a2207540-1400-11d6-a3c7-0050bae0a776 - идентификатор коллекции реквизитов
            propertiesUuid = configObject.GetUuid(new int[] { 7, 0 });
            if (propertiesUuid == new Guid("a2207540-1400-11d6-a3c7-0050bae0a776"))
            {
                Configurator.ConfigureProperties(register, properties, PropertyPurpose.Property);
            }

            Configurator.ConfigureSharedProperties(register);
        }
Пример #23
0
        public void MergeTwoEmptyConfigObject()
        {
            var     n1     = new ConfigObject();
            var     n2     = new ConfigObject();
            dynamic merged = Merger.Merge(n1, n2);

            Assert.IsInstanceOfType(typeof(ConfigObject), merged);
        }
Пример #24
0
 private void SetValuesByConfigObject(ConfigObject co)
 {
     // Set the ServerSettings values by the givin object
     ServerSettings.maxPlayerCount           = co.maxPlayerCount;
     ServerSettings.tickRate                 = co.tickRate;
     ServerSettings.lagCompensation          = co.lagCompensation;
     ServerSettings.backTrackingBufferTimeMS = co.backTrackingBufferTimeMS;
 }
Пример #25
0
        static void SaveConfig()
        {
            IConfigManager configManager = new ConfigManager();
            ConfigObject   configObject  = new ConfigObject();

            configObject.Fix();
            configManager.Write <ConfigObject>(configObject, HostingEnvironment.MapPath("~/bin/") + "Config.xml");
        }
Пример #26
0
 public void readcfg()
 {
     cf = JsonConfig.Config.Default;
     if (System.IO.File.Exists(CFG_FILE_NAME))
     {
         cf.ApplyJson(System.IO.File.ReadAllText(CFG_FILE_NAME));
     }
 }
Пример #27
0
        public static void PopulateCommands()
        {
            var FullNames = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.IsClass && x.Namespace == "socon.Commands.CP").Select(x => x).Where(x => x.Attributes == TypeAttributes.BeforeFieldInit);

            Debug.Assert(!FullNames.Select(x => x.Name).Contains("Alias"));

            ConfigObject commandsList = null;

            if (!(Settings.Global?.Commands is null) && Settings.GlobalNonDynamic != null)
            {
                commandsList = ((ConfigObject)Settings.GlobalNonDynamic["Commands"]);
            }

            FullNames.ToList().ForEach(x => AllCommands.Add(new Command(x)));

            /*foreach (var c in FullNames) {
             *      Command toAdd = new Command(c);
             *      if (commandsList != null && commandsList.ContainsKey(c)) {
             *              dynamic properties = ((dynamic)commandsList[c]);
             *
             *              try {
             *                      if (!(properties.Regex as string is null))
             *                              toAdd.Regex = new Regex(properties.Regex, RegexOptions.Compiled);
             *              } catch (Exception ex) {
             *                      Debug.WriteLine("Failed to compile regex (1):\n" + ex);
             *              }
             *
             *              try {
             *                      if (!(properties.UsageTrigger as string is null))
             *                              toAdd.UsageTrigger = new Regex(properties.UsageTrigger, RegexOptions.Compiled);
             *              } catch (Exception ex) {
             *                      Debug.WriteLine("Failed to compile regex (2):\n" + ex);
             *              }
             *
             *              toAdd.Usage = properties.Usage as string ?? "";
             *      }
             *      AllCommands.Add(toAdd);
             * }*/

            string key = "";

            foreach (var kv in ((dynamic)commandsList)?.Alias)
            {
                if (key == "")
                {
                    key = kv;
                }
                else
                {
                    try {
                        Aliases.Add(new Regex(key, RegexOptions.Compiled), kv);
                    } catch (Exception ex) {
                        Debug.WriteLine("Failed to compile regex (3):\n" + ex);
                    }
                    key = "";
                }
            }
        }
Пример #28
0
        public static BaseResult ReadConfig()
        {
            if (!File.Exists(ConfigFileName))
            {
                Log.Logger.Debug($"【read config】:config file does not exist, use default config");

                string defaultConfigString = Config.Default.ToString();
                using (StreamWriter sw = new StreamWriter(ConfigFileName, false, Encoding.UTF8))
                {
                    sw.Write(defaultConfigString);
                }
            }

            ConfigObject configObject = Config.ApplyJsonFromPath(ConfigFileName);

            if (GlobalData.Instance.RunMode == RunMode.Development && File.Exists(DevConfigFileName))
            {
                configObject = Config.ApplyJsonFromPath(DevConfigFileName, configObject);
            }

            Config.SetUserConfig(Config.User.GetType() == typeof(NullExceptionPreventer)
                ? configObject
                : Config.ApplyJson(Config.User.ToString(), configObject));


            AggregatedConfig aggregatedConfig;

            try
            {
                aggregatedConfig = JsonConvert.DeserializeObject <AggregatedConfig>(Config.User.ToString());
            }
            catch (Exception ex)
            {
                Log.Logger.Error($"【read config exception】:{ex}");
                return(new BaseResult()
                {
                    Status = "-1",
                    Message = Messages.ErrorReadConfigFailed
                });
            }

            if (aggregatedConfig == null)
            {
                Log.Logger.Error($"【read config】:empty config");
                return(new BaseResult()
                {
                    Status = "-1",
                    Message = Messages.ErrorReadEmptyConfig
                });
            }

            GlobalData.Instance.AggregatedConfig = aggregatedConfig;
            return(new BaseResult()
            {
                Status = "0",
            });
        }
Пример #29
0
 private void Init()
 {
     try
     {
         if (PropertyInfoItem == null)
         {
             return;
         }
         CurrentApp = PropertyInfoItem.CurrentApp;
         ConfigObject configObject = PropertyInfoItem.ConfigObject;
         if (configObject != null)
         {
             mConfigObject = configObject;
         }
         ObjectPropertyInfo propertyInfo = PropertyInfoItem.PropertyInfo;
         if (propertyInfo != null)
         {
             mPropertyInfo = propertyInfo;
         }
         ResourceProperty propertyValue = PropertyInfoItem.ResourceProperty;
         if (propertyValue != null)
         {
             mPropertyValue = propertyValue;
         }
         if (mPropertyValue == null)
         {
             return;
         }
         if (!string.IsNullOrEmpty(mPropertyValue.Value))
         {
             mListCTIServiceNameItems.Clear();
             CTIServiceNameInfo info = new CTIServiceNameInfo();
             info.Name = mPropertyValue.Value;
             PropertyValueEnumItem item = new PropertyValueEnumItem();
             item.Value       = info.Name;
             item.Display     = info.Name;
             item.Description = info.Name;
             item.Info        = info;
             mListCTIServiceNameItems.Add(item);
             for (int i = 0; i < ComboServiceNames.Items.Count; i++)
             {
                 var temp = ComboServiceNames.Items[i] as PropertyValueEnumItem;
                 if (temp != null)
                 {
                     if (temp.Value == item.Value)
                     {
                         ComboServiceNames.SelectedItem = temp;
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         ShowException(ex.Message);
     }
 }
Пример #30
0
 private void restoreSettingBtn_Click(object sender, RoutedEventArgs e)
 {
     if (MessageBox.Show("您确定要重置设置吗?\n 包括键盘映射在内的所有设置都将恢复原始!", "警告:", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
     {
         Config.config = ConfigObject.GetDefaultConfig();
         Config.Save();
         Window_Initialized(this, new System.EventArgs());
     }
 }
Пример #31
0
        public void CastConfigObjectToBool()
        {
            // if a ConfigObject has nested members, we wan't to be able to do
            // a fast check for non null in if statements:
            //
            // if (config.SomeMember) { ... }

            string conf = @"{ SomeMember: { Foo: 42 } }";
            dynamic c = new ConfigObject();
            c.ApplyJson(conf);

            bool t = (bool) c.SomeMember;
            Assert.AreEqual(true, t);

            bool f = (bool) c.NonExistantMember;
            Assert.AreEqual (f, false);
        }
Пример #32
0
		public static ConfigObject ApplyFromDirectoryInfo (DirectoryInfo info, ConfigObject config = null, bool recursive = false)
		{
			return ApplyFromDirectory (info.FullName, config, recursive);
		}
Пример #33
0
		public static void SetUserConfig (ConfigObject config)
		{
			User = config;
			// disable the watcher
			if (userConfigWatcher != null) {
				userConfigWatcher.EnableRaisingEvents = false;
				userConfigWatcher.Dispose ();
				userConfigWatcher = null;
			}

			// invalidate the Global config, forcing a re-merge next time its accessed
			global_config = null;
		}
Пример #34
0
		public static ConfigObject ApplyJson (string json, ConfigObject config = null)
		{
			if (config == null)
				config = new ConfigObject ();

			dynamic parsed = ParseJson (json);
			return Merger.Merge (parsed, config);
		}
Пример #35
0
		// seeks a folder for .conf files
		public static ConfigObject ApplyFromDirectory (string path, ConfigObject config = null, bool recursive = false)
		{
			if (!Directory.Exists (path))
				throw new Exception ("no folder found in the given path");

			if (config == null)
				config = new ConfigObject ();

			DirectoryInfo info = new DirectoryInfo (path);
			if (recursive) {
				foreach (var dir in info.GetDirectories ()) {
					Console.WriteLine ("reading in folder {0}", dir.ToString ());
					config = ApplyFromDirectoryInfo (dir, config, recursive);
				}
			}

			// find all files
			var files = info.GetFiles ();
			foreach (var file in files) {
				Console.WriteLine ("reading in file {0}", file.ToString ());
				config = ApplyJsonFromFileInfo (file, config);
			}
			return config;
		}
Пример #36
0
		public static ConfigObject ApplyJsonFromFileInfo (FileInfo file, ConfigObject config = null)
		{
			var overlay_json = File.ReadAllText (file.FullName);
			dynamic overlay_config = ParseJson (overlay_json);
			return Merger.Merge (overlay_config, config);
		}
Пример #37
0
		public static ConfigObject ApplyJsonFromPath (string path, ConfigObject config = null)
		{
			return ApplyJsonFromFileInfo (new FileInfo (path), config);
		}
Пример #38
0
		public void MergeEmptyConfigObjects ()
		{
			dynamic c1 = new ConfigObject ();
			dynamic c2 = new ConfigObject ();

			c1.Foo = "bar";
			c1.X = 1;
			dynamic merged = Merger.Merge (c1, c2);

			Assert.IsInstanceOfType (typeof(ConfigObject), merged);
			Assert.AreEqual ("bar", c1.Foo);
			Assert.AreEqual (1, c1.X);
		}
Пример #39
0
		public void MergeConfigObjects ()
		{
			dynamic c1 = new ConfigObject ();
			dynamic c2 = new ConfigObject ();
			c1.Foo = "bar";
			c2.Bla = "blubb";
			dynamic merged = Merger.Merge (c1, c2);
			Assert.IsInstanceOfType (typeof(ConfigObject), merged);
			Assert.AreEqual ("bar", merged.Foo);
			Assert.AreEqual ("blubb", merged.Bla);
		}
Пример #40
0
		public void MaintainHierarchy ()
		{
			dynamic Default = new ConfigObject ();
			dynamic User = new ConfigObject ();
			dynamic Scope = new ConfigObject ();

			Default.Foo = 1;
			User.Foo = 2;
			Scope.Foo = 3;

			dynamic merged = Merger.MergeMultiple (Scope, User, Default);
			Assert.AreEqual (3, merged.Foo);

		}
Пример #41
0
		/// <summary>
		/// Merge the specified obj2 and obj1, where obj1 has precendence and
		/// overrules obj2 if necessary.
		/// </summary>
		/// <exception cref='TypeMissmatchException'>
		/// Is thrown when the type missmatch exception.
		/// </exception>
		public static dynamic Merge (dynamic m_obj1, dynamic m_obj2)
		{
			dynamic obj1 = m_obj1;
			dynamic obj2 = m_obj2;

			// make sure we only deal with ConfigObject but not ExpandoObject as currently
			// return from JsonFX
			if (obj1 is ExpandoObject) obj1 = ConfigObject.FromExpando (obj1);
			if (obj2 is ExpandoObject) obj2 = ConfigObject.FromExpando (obj2);

			// if both objects are NullExceptionPreventer, return a ConfigObject so the
			// user gets an "Empty" ConfigObject
			if (obj1 is NullExceptionPreventer && obj2 is NullExceptionPreventer)
				return new ConfigObject ();

			// if any object is of NullExceptionPreventer, the other object gets precedence / overruling
			if (obj1 is NullExceptionPreventer && obj2 is ConfigObject)
				return obj2;
			if (obj2 is NullExceptionPreventer && obj1 is ConfigObject)
				return obj1;

			// handle what happens if one of the args is null
			if (obj1 == null && obj2 == null)
				return new ConfigObject ();

			if (obj2 == null) return obj1;
			if (obj1 == null) return obj2;

			if (obj1.GetType () != obj2.GetType ())	
				throw new TypeMissmatchException ();
			
			// changes in the dictionary WILL REFLECT back to the object
			var dict1 = (IDictionary<string, object>) (obj1);
			var dict2 = (IDictionary<string, object>) (obj2);

			dynamic result = new ConfigObject ();
			var rdict = (IDictionary<string, object>) result;
			
			// first, copy all non colliding keys over
	        foreach (var kvp in dict1)
				if (!dict2.Keys.Contains (kvp.Key))
					rdict.Add (kvp.Key, kvp.Value);
	        foreach (var kvp in dict2)
				if (!dict1.Keys.Contains (kvp.Key))
					rdict.Add (kvp.Key, kvp.Value);
		
			// now handle the colliding keys	
			foreach (var kvp1 in dict1) {
				// skip already copied over keys
				if (!dict2.Keys.Contains (kvp1.Key) || dict2[kvp1.Key] == null)
					continue;
	
				var kvp2 = new KeyValuePair<string, object> (kvp1.Key, dict2[kvp1.Key]);
				
				// some shortcut variables to make code more readable		
				var key = kvp1.Key;
				var value1 = kvp1.Value;
				var value2 = kvp2.Value;
				var type1 = value1.GetType ();
				var type2 = value1.GetType ();
				
				// check if both are same type
				if (type1 != type2)
					throw new TypeMissmatchException ();

				if (value1 is ConfigObject[]) {
					rdict[key] = CollectionMerge (value1, value2);
					/*var d1 = val1 as IDictionary<string, object>;
					var d2 = val2 as IDictionary<string, object>;
					rdict[key] = CollectionMerge (val1, val2); */
				}
				else if (value1 is ConfigObject) {
					rdict[key] = Merge (value1, value2);
				}
				else if (value1 is string)
				{
					rdict[key]	= value1;
				}
				else if (value1 is IEnumerable) {
					rdict[key] = CollectionMerge (value1, value2);
				}
				else {
					rdict[key] = value1;
				}					
				
				//else if (kvp.Value.GetType ().IsByRef) {
					// recursively merge it	
				//}
			}
			return result;
		}
 public static void ConfigReader(string path)
 {
     Configuration = JsonConvert.DeserializeObject<ConfigObject>(File.ReadAllText(path));
 }
Пример #43
0
 public void readcfg()
 {
     cf = JsonConfig.Config.Default;
     if(System.IO.File.Exists(CFG_FILE_NAME))
     {
         cf.ApplyJson(System.IO.File.ReadAllText(CFG_FILE_NAME));
     }
 }
Пример #44
0
 public static void SetUserConfig(ConfigObject config)
 {
     User = config;
     // disable the watcher
     if (userConfigWatcher != null) {
         userConfigWatcher.EnableRaisingEvents = false;
         userConfigWatcher.Dispose ();
         userConfigWatcher = null;
     }
 }