コード例 #1
0
        protected virtual void UpdateSettings(object settingsObj)
        {
            PropertyInfo[] properties = GetProperties(settingsObj);
            string[]       keys       = GetKeys(properties);
            IDictionary <string, Setting> settings = GetSettings(keys);

            foreach (PropertyInfo property in properties)
            {
                SettingAttribute settingAttribute = property.GetCustomAttribute <SettingAttribute>();

                if (settingAttribute == null)
                {
                    continue;
                }

                string key   = settingAttribute.Key;
                string value = property.GetValue(settingsObj)?.ToString();

                if (settings.ContainsKey(key))
                {
                    Setting setting = settings[key];
                    setting.Value = value;
                    DataContext.Entry(setting).State = EntityState.Modified;
                }
                else
                {
                    Setting setting = new Setting
                    {
                        Key   = key,
                        Value = value
                    };
                    DataContext.Settings.Add(setting);
                }
            }
        }
コード例 #2
0
        protected void SaveSettingsObject(object settingsObject)
        {
            try
            {
                Type t = settingsObject.GetType();
                SettingsFileHandler globalSerializer = new SettingsFileHandler(GetGlobalFilePath(t));
                SettingsFileHandler userSerializer   = new SettingsFileHandler(GetUserFilePath(t));
                foreach (PropertyInfo property in t.GetProperties())
                {
                    SettingAttribute att = GetSettingAttribute(property);
                    if (att == null)
                    {
                        continue;
                    }
                    SettingsFileHandler s = (att.SettingScope == SettingScope.Global ? globalSerializer : userSerializer);
                    object value          = property.GetValue(settingsObject, null);
                    s.SetValue(property.Name, value);
                }
                globalSerializer.Close();
                userSerializer.Close();

                // Send a message that the setting has been changed.
                SettingsManagerMessaging.SendSettingsChangeMessage(t);
            }
            catch (Exception e)
            {
                ServiceRegistration.Get <ILogger>().Error("SettingsManager: Error writing settings of type '{0}'... Will clear settings files for this setting", e, settingsObject.GetType().Name);
                RemoveSettingsData(settingsObject.GetType(), true, true);
            }
        }
コード例 #3
0
        private void AddSettingDescription(SettingAttribute settingAttribute, int i)
        {
            var textBlock = settingAttribute.GetDescriptionElement();

            textBlock.SetValue(Grid.RowProperty, i);
            Main.Children.Add(textBlock);
        }
コード例 #4
0
ファイル: SettingMetadata.cs プロジェクト: wkfff/reusable
        private SettingMetadata(Type type, object instance, MemberInfo member)
        {
            Type       = type;
            Instance   = instance;
            Member     = member;
            MemberType = GetMemberType(member);

            //var asdf1 = member.GetCustomAttributes<SettingMemberAttribute>(inherit: true);
            //var asdf2 = member.GetCustomAttributes<SettingMemberAttribute>(inherit: false);

            var attributes =
                new SettingAttribute[]
            {
                member.GetCustomAttributes <SettingMemberAttribute>(inherit: true).FirstOrDefault(),
                type.GetCustomAttribute <SettingTypeAttribute>(),
            }
            .Where(Conditional.IsNotNull)
            .ToList();

            SettingNameStrength = attributes.FirstOrDefault(x => x.Strength != SettingNameStrength.Inherit)?.Strength ?? SettingNameStrength.Inherit;
            Prefix         = attributes.Select(x => x.Prefix).FirstOrDefault(Conditional.IsNotNullOrEmpty);
            PrefixHandling = attributes.FirstOrDefault(x => x.PrefixHandling != PrefixHandling.Inherit)?.PrefixHandling ?? PrefixHandling.Inherit;

            Namespace  = type.Namespace;
            TypeName   = type.GetCustomAttribute <SettingTypeAttribute>()?.Name ?? type.ToPrettyString();
            MemberName = member.GetCustomAttribute <SettingMemberAttribute>()?.Name ?? member.Name;

            ProviderName = attributes.Select(x => x.ProviderName).FirstOrDefault(Conditional.IsNotNullOrEmpty);
            ProviderType = attributes.Select(x => x.ProviderType).FirstOrDefault(Conditional.IsNotNull);
            DefaultValue = member.GetCustomAttribute <DefaultValueAttribute>()?.Value;
            Validations  = member.GetCustomAttributes <ValidationAttribute>();
        }
コード例 #5
0
        protected override ISetting SaveSetting(SettingAttribute person_attribute, object value)
        {
            if (person_attribute.SettingType != SettingType.Personal)
                throw new Exception("PersonSettingsInterceptor can't handle non-personal settings");

            //Возможно, к настройке уже обращались, тогда она есть в кеше
            ISetting setting = null;
            if (!m_Cache.TryGetValue(person_attribute.SettingName, out setting))
                setting = GetSetting(person_attribute);//Если в кеше записи нет, то попробуем взять из таблицы

            if (setting == null)//Если такой записи в таблице нет, создадим её
            {
                //Если значение пользовательской настройки совпадает со значением аналогичной глобальной настройки,
                //то хранить ее для пользователя не будем
                if (PersonalSettings.IsGlobalEqual(person_attribute, value))
                    return null;

                PersonAttribute attr = m_Person.AddStandardStringAttribute(person_attribute.SettingName, value.ToString());
                return new PersonalSettingEntity(person_attribute, attr);
            }
            else
            {
                //Если новое значение пользовательской настройки совпадает со значением аналогичной глобальной настройки,
                //то просто удалим для этого пользователя эту настройку
                if (PersonalSettings.IsGlobalEqual(person_attribute, value))
                    m_Person.RemoveStandardAttributes(PersonAttributeType.GetAttributeType(person_attribute.SettingName));

                ((PersonalSettingEntity)setting).Value = value.ToString();
                (((PersonalSettingEntity)setting).PersonAttribute).Save();
                return setting;
            }
        }
コード例 #6
0
        /// <summary>
        /// Gets a list of setting attributes associated with the current action
        /// </summary>
        /// <param name="pageToUse"></param>
        /// <param name="moduleInstance"></param>
        /// <returns></returns>
        public List <SettingAttribute> GetSettingAttributes()
        {
            List <SettingAttribute> properties = new List <SettingAttribute>();

            if (this.DataUpdateAction != null)
            {
                foreach (PropertyInfo pi in this.DataUpdateAction.GetType().GetProperties())
                {
                    Object[] customAttributes = pi.GetCustomAttributes(typeof(SettingAttribute), true);
                    foreach (object attr in customAttributes)
                    {
                        SettingAttribute settingAttribute = (SettingAttribute)attr;
                        settingAttribute.Setting = pi.Name.Replace("Setting", "");
                        settingAttribute.Value   = this.Settings[settingAttribute.Setting].Value;

                        bool loaded = false;
                        foreach (SettingAttribute attribute in properties)
                        {
                            if (attribute.Setting.ToLower() == settingAttribute.Setting.ToLower())
                            {
                                loaded = true;
                                break;
                            }
                        }
                        if (!loaded)
                        {
                            properties.Add(settingAttribute);
                        }
                    }
                }
            }
            return(properties);
        }
コード例 #7
0
        private void AddSettingValue(PropertyInfo property, SettingAttribute settingAttribute, Settings settings, int i)
        {
            var element = settingAttribute.GetValueElement(property, settings);

            element.SetValue(Grid.ColumnProperty, 1);
            element.SetValue(Grid.RowProperty, i);
            Main.Children.Add(element);
        }
コード例 #8
0
        protected virtual void DefaultSetAttribute(string attributeName, string attributeValue)
        {
            SettingAttribute?.Invoke(this, new ComponentActionEventArgs(this));

            JavaScriptService.Execute(
                $"arguments[0].setAttribute('{attributeName}', '{attributeValue}');", this);

            AttributeSet?.Invoke(this, new ComponentActionEventArgs(this));
        }
コード例 #9
0
ファイル: IVisitor.cs プロジェクト: saber-wang/nlite
 private static IAppSettingInjection CreateFieldInjection(FieldInfo f, SettingAttribute settingAttr)
 {
     return(new AppSettingFieldInjection
     {
         Member = f,
         Setter = f.ToMemberSetter(),//通过Emit的方式进行注入
         Dependency = DependencyManager.GetAppSettingDependency(settingAttr.Name, f.FieldType),
     });
 }
コード例 #10
0
ファイル: IVisitor.cs プロジェクト: saber-wang/nlite
 private static IAppSettingInjection CreatePropertyInjection(PropertyInfo p, SettingAttribute settingAttr)
 {
     return(new AppSettingPropertyInjection
     {
         Member = p,
         Setter = p.ToMemberSetter(),//通过Emit的方式进行注入
         Dependency = DependencyManager.GetAppSettingDependency(settingAttr.Name, p.PropertyType),
     });
 }
コード例 #11
0
        protected override ISetting GetSetting(SettingAttribute person_attribute)
        {
            if (person_attribute.SettingType != SettingType.Personal)
                throw new Exception("PersonSettingsInterceptor can't handle non-personal settings");

            IList<PersonAttribute> person_attrs =
                                PersonAttributes.GetPersonAttributesByKeyword((int)m_Person.ID, person_attribute.SettingName);

            return person_attrs.Count != 0 ? new PersonalSettingEntity(person_attribute, person_attrs[0]) : null;
        }
コード例 #12
0
 protected override void InitializeTarget()
 {
     _setting = new SettingAttribute
     {
         Name        = this.TableName,
         Period      = this.Period,
         RemoveAfter = this.RemoveAfter,
     };
     _client = CloudClient.Get(this.ConnectionName);
     base.InitializeTarget();
 }
コード例 #13
0
        protected override ISetting SaveSetting(SettingAttribute attribute, object value)
        {
            validateSettingType(attribute.SettingType);

            ISetting setting = null;
            if (!m_Cache.TryGetValue(attribute.SettingName, out setting))
                setting = loadSetting(attribute);

            setting.Value = value.ToString();
            ((BasePlainObject) setting).Save();

            return setting;
        }
コード例 #14
0
        public void ProcessFile()
        {
            XmlDocument XmlDoc = new XmlDocument();

            XmlDoc.Load(FilePath);

            foreach (var Node in XmlDoc.DocumentElement.GetElementsByTagName("SettingGroup"))
            {
                XmlElement Element = (XmlElement)Node;

                SettingGroup SetGroup = new SettingGroup();

                SetGroup.GroupKey         = Element.GetElementsByTagName("GroupKey")[0].InnerText;
                SetGroup.UserFriendlyName = Element.GetElementsByTagName("UserFriendlyName")[0].InnerText;
                SetGroup.Description      = Element.GetElementsByTagName("Description")[0].InnerText;
                SetGroup.ParentCategory   = (ParentCategoryType)Enum.Parse(typeof(ParentCategoryType), Element.GetElementsByTagName("ParentCategory")[0].InnerText);

                foreach (var ChildNode in Element.GetElementsByTagName("Setting"))
                {
                    XmlElement ChildElement = (XmlElement)ChildNode;

                    Setting Sett = new Setting();

                    Sett.Key = ChildElement.GetElementsByTagName("Key")[0].InnerText;
                    Sett.UserFriendlyName           = ChildElement.GetElementsByTagName("UserFriendlyName")[0].InnerText;
                    Sett.Description                = ChildElement.GetElementsByTagName("Description")[0].InnerText;
                    Sett.Value                      = ChildElement.GetElementsByTagName("Value")[0].InnerText;
                    Sett.EntryType                  = (DataEntryType)Enum.Parse(typeof(DataEntryType), ChildElement.GetElementsByTagName("EntryType")[0].InnerText);
                    Sett.DataEntryStaticPropertyKey = ChildElement.GetElementsByTagName("DataEntryStaticPropertyKey")[0].InnerText;

                    foreach (var ChildChildNode in ChildElement.GetElementsByTagName("SettingAttribute"))
                    {
                        XmlElement ChildChildElement = (XmlElement)ChildChildNode;

                        SettingAttribute SetAttr = new SettingAttribute();

                        SetAttr.Key   = ChildChildElement.GetElementsByTagName("Key")[0].InnerText;
                        SetAttr.Value = ChildChildElement.GetElementsByTagName("Value")[0].InnerText;

                        Sett.SettingAttributeList.Add(SetAttr);
                    }

                    SetGroup.SettingsList.Add(Sett);
                }

                SettingGroupDAO.Save(SetGroup);
            }
        }
コード例 #15
0
        private ISetting loadSetting(SettingAttribute attribute)
        {
            ISetting setting = null;
            switch (attribute.SettingType)
            {
                case SettingType.Global:
                case SettingType.Forum:
                    {
                        setting = new GlobalSettingEntity(attribute);
                        break;
                    }

                case SettingType.Office:
                    {
                        setting = new office();
                        break;
                    }
            }

            // TODO:
            ((BasePlainObject)setting).LoadByReference(setting.KeyColumnName, attribute.SettingName);
            return setting;
        }
コード例 #16
0
        private void Scan()
        {
            foreach (FieldInfo info in GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
            {
                object[] attrs = info.GetCustomAttributes(typeof(SettingAttribute), false);
                string   nm    = info.Name;
                object   def   = null;

                Setting item = new Setting();
                item.Info = info;

                if (attrs.Length != 0)
                {
                    SettingAttribute attr = attrs[0] as SettingAttribute;

                    nm  = attr.Name;
                    def = attr.Default;

                    item.Attribute = attr;
                }

                if (def != null)
                {
                    try
                    {
                        object val = Convert.ChangeType(def, info.FieldType);
                        info.SetValue(this, val);
                    }
                    catch
                    {
                        Console.WriteLine("Could not set default value {0} for setting {1}", def, nm);
                    }
                }

                d_settings[nm] = item;
            }
        }
コード例 #17
0
        protected virtual T GetSettings <T>() where T : new()
        {
            T obj = new T();

            PropertyInfo[] properties = GetProperties(obj);
            string[]       keys       = GetKeys(properties);
            IDictionary <string, Setting> settings = GetSettings(keys);

            foreach (PropertyInfo property in properties)
            {
                SettingAttribute settingAttribute = property.GetCustomAttribute <SettingAttribute>();

                if (settingAttribute == null)
                {
                    continue;
                }

                if (settings.ContainsKey(settingAttribute.Key))
                {
                    Setting setting = settings[settingAttribute.Key];
                    string  value   = setting?.Value;

                    if (property.PropertyType == typeof(bool))
                    {
                        bool bValue;
                        bool.TryParse(value, out bValue);
                        property.SetValue(obj, bValue);
                    }
                    else
                    {
                        property.SetValue(obj, value);
                    }
                }
            }

            return(obj);
        }
コード例 #18
0
        public SettingsPage(DarknetService darknetService)
        {
            this.darknetService = darknetService;
            // First copy the current darknet settings
            // The new settings will be modified by the user in this page, and only written after the "Apply Changes" Button is pressed
            newSettings = new DarknetSettings(darknetService.Settings);
            NavigationPage.SetHasNavigationBar(this, false);

            var stackLayout = new StackLayout()
            {
                Children = { new Label()
                             {
                                 Text = "Darknet Settings", FontSize = 30, HorizontalTextAlignment = TextAlignment.Center
                             }, new SectionLine(), }
            };

            // Setup user interface for each property
            foreach (var property in newSettings)
            {
                SettingAttribute attr    = property.GetCustomAttribute(typeof(SettingAttribute)) as SettingAttribute;
                bool             Enabled = attr.Degree <= UserDegree;

                stackLayout.Children.Add(new SettingsInfoLabel(attr.Name));

                // Pattern matching, C# 7.0
                // Choose User Control depending on the property type and attribute
                switch (attr as object)
                {
                case SettingMinMax darkSlider:
                    var label = new Label()
                    {
                        HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center, Text = property.GetValue(newSettings).ToString() + darkSlider.Unit
                    };
                    // The following cast will result in InvalidCastException:  int -> object -> double
                    // So the object needs to be casted to int before:          int -> object -> int -> double
                    var slider = new SettingSlider(property, label)
                    {
                        IsEnabled = Enabled
                    };
                    slider.Value         = (int)property.GetValue(newSettings);
                    slider.ValueChanged += (o, e) => {
                        var sl = o as SettingSlider;
                        // Same as above
                        sl.PropertyInfo.SetValue(newSettings, (int)(e.NewValue));
                        sl.Label.Text = sl.PropertyInfo.GetValue(newSettings).ToString() + sl.SettingAttribute.Unit;
                    };
                    stackLayout.Children.Add(label);
                    stackLayout.Children.Add(slider);
                    break;

                case SettingEnum darkEnum:
                    SettingPicker picker = new SettingPicker(property)
                    {
                        Title     = attr.Name,
                        IsEnabled = Enabled
                    };

                    picker.SelectedIndex         = Array.IndexOf(picker.Values, property.GetValue(newSettings));
                    picker.SelectedIndexChanged += (o, e) =>
                    {
                        var pick = o as SettingPicker;
                        pick.PropertyInfo.SetValue(newSettings, pick.Values.GetValue(pick.SelectedIndex));
                    };
                    stackLayout.Children.Add(picker);
                    break;

                case SettingString darkEntry:
                    var entry = new SettingEntry(property)
                    {
                        Text = property.GetValue(newSettings).ToString(), IsEnabled = Enabled
                    };
                    entry.TextChanged += (o, e) =>
                    {
                        var entr = o as SettingEntry;
                        if (e.NewTextValue.Length > entr.SettingAttribute.MaxChars)
                        {
                            entr.TextColor = Color.Red;
                            return;
                        }
                        foreach (char c in e.NewTextValue)
                        {
                            bool containsAtLeastOneChar = false;
                            foreach (char c2 in entr.SettingAttribute.AllowedChars)
                            {
                                if (c2 == c)
                                {
                                    containsAtLeastOneChar = true;
                                }
                            }
                            if (containsAtLeastOneChar == false)
                            {
                                entr.TextColor = Color.Red;
                                return;
                            }
                        }
                        entr.TextColor = Color.Black;
                        switch (Type.GetTypeCode(entr.PropertyInfo.PropertyType))
                        {
                        case TypeCode.Int32:
                            entr.PropertyInfo.SetValue(newSettings, int.Parse(e.NewTextValue));
                            break;

                        case TypeCode.String:
                            entr.PropertyInfo.SetValue(newSettings, e.NewTextValue);
                            break;
                        }
                    };
                    stackLayout.Children.Add(entry);
                    break;

                default:
                    switch (property.Name)
                    {
                    case "Resolution":
                        int index   = 0;
                        var resList = darknetService.CameraPreview.SupportedResolutions.ToList();
                        foreach (var obj in resList)
                        {
                            if (obj.Height == newSettings.Resolution.Height && obj.Width == newSettings.Resolution.Width)
                            {
                                index = resList.IndexOf(obj);
                                break;
                            }
                        }

                        Picker resolutionsPicker = new Picker()
                        {
                            Title = "Resolutions", ItemsSource = resList, SelectedIndex = index, IsEnabled = Enabled
                        };
                        resolutionsPicker.SelectedIndexChanged += (o, e) =>
                        {
                            newSettings.Resolution = darknetService.CameraPreview.SupportedResolutions.ToList()[resolutionsPicker.SelectedIndex];
                        };
                        stackLayout.Children.Add(resolutionsPicker);
                        break;
                    }
                    break;
                }
                stackLayout.Children.Add(new SectionLine());
            }

            Button applySettings = new Button()
            {
                Text = "Apply Settings"
            };

            applySettings.Pressed += (o, e) =>
            {
                darknetService.Settings = newSettings;
                Navigation.PopAsync();
            };
            stackLayout.Children.Add(applySettings);
            Content = new ScrollView()
            {
                Content = stackLayout
            };



            /// OUTDATED CODE

            //Label ThresholdLabel = new Label() { HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center, Text = newSettings.Threshold.ToString() + " %" };
            //Slider thresholdSlider = new Slider(0, 100, newSettings.Threshold) { MaximumTrackColor = Color.Blue, MinimumTrackColor = Color.Blue };
            //thresholdSlider.ValueChanged += (o, e) =>
            //{
            //    ThresholdLabel.Text = e.NewValue.ToString() + " %";
            //    newSettings.Threshold = (int)e.NewValue;
            //};

            //Picker formatPicker = new Picker() { Title = "Image Format", ItemsSource = new List<string>() { "compressed", "uncompressed" }, SelectedIndex = newSettings.ImageFormat == ImageFormat.compressed ? 0 : 1, IsEnabled = false };
            //formatPicker.SelectedIndexChanged += (o, e) =>
            //{
            //    newSettings.ImageFormat = formatPicker.SelectedIndex == 0 ? ImageFormat.compressed : ImageFormat.uncompressed;
            //};

            //int index = 0;
            //var resList = darknetService.CameraPreview.SupportedResolutions.ToList();
            //foreach (var obj in resList)
            //{
            //    if (obj.Height == newSettings.Resolution.Height && obj.Width == newSettings.Resolution.Width)
            //    {
            //        index = resList.IndexOf(obj);
            //        break;
            //    }
            //}
            //Picker resolutionsPicker = new Picker() { Title = "Resolutions", ItemsSource = resList, SelectedIndex = index };
            //resolutionsPicker.SelectedIndexChanged += (o, e) =>
            //{
            //    newSettings.Resolution = darknetService.CameraPreview.SupportedResolutions.ToList()[resolutionsPicker.SelectedIndex];
            //};

            //Entry ipEntry = new Entry() { Text = newSettings.IpAddress.ToString(), HorizontalTextAlignment = TextAlignment.Start };
            //ipEntry.TextChanged += (o, e) =>
            //{
            //    newSettings.IpAddress = e.NewTextValue;
            //};

            //Entry portEntry = new Entry() { Text = newSettings.Port.ToString(), HorizontalTextAlignment = TextAlignment.Start };
            //portEntry.TextChanged += (o, e) =>
            //{
            //    int port = 0;
            //    if (int.TryParse(e.NewTextValue, out port))
            //    {
            //        newSettings.Port = port;
            //        portEntry.TextColor = Color.Black;
            //    }
            //    else
            //    {
            //        portEntry.TextColor = Color.Red;
            //    }

            //};

            //Button applySettings = new Button() { Text = "Apply Settings" };
            //applySettings.Pressed += (o, e) =>
            //{
            //    darknetService.Settings = newSettings;
            //    Navigation.PopAsync();
            //};
            //stackLayout.Children.Add(applySettings);
            //Content = new ScrollView()
            //{
            //    Content = new StackLayout
            //    {
            //        Children = {
            //        new Label() {Text = "Darknet Settings", FontSize = 30, HorizontalTextAlignment = TextAlignment.Center }, new SectionLine(),
            //        new SettingsInfoLabel("Prediction Threshold"), ThresholdLabel, thresholdSlider, new SectionLine(),
            //        new SettingsInfoLabel("Image Format"), formatPicker, new SectionLine(),
            //        new SettingsInfoLabel("Image Resolution"), resolutionsPicker, new SectionLine(),
            //        new SettingsInfoLabel("Host IP Address"), ipEntry, new SectionLine(),
            //        new SettingsInfoLabel("Host Port"), portEntry, new SectionLine(),
            //        applySettings
            //    }
            //    }
            //};
        }
コード例 #19
0
 protected override ISetting GetSetting(SettingAttribute attribute)
 {
     validateSettingType(attribute.SettingType);
     return loadSetting(attribute);
 }
コード例 #20
0
        protected object LoadSettingsObject(Type settingsType)
        {
            SettingsFileHandler globalHandler = new SettingsFileHandler(GetGlobalFilePath(settingsType));
            SettingsFileHandler userHandler   = new SettingsFileHandler(GetUserFilePath(settingsType));

            try
            {
                globalHandler.Load();
            }
            catch (Exception e)
            {
                ServiceRegistration.Get <ILogger>().Error("SettingsManager: Error loading global settings file for setting type '{0}'... Will clear this settings file.", e, settingsType.Name);
                globalHandler.Clear();
                RemoveSettingsData(settingsType, false, true);
            }
            try
            {
                userHandler.Load();
            }
            catch (Exception e)
            {
                ServiceRegistration.Get <ILogger>().Error("SettingsManager: Error loading user settings file for setting type '{0}'... Will clear this settings file.", e, settingsType.Name);
                userHandler.Clear();
                RemoveSettingsData(settingsType, true, false);
            }
            try
            {
                object result = Activator.CreateInstance(settingsType);
                foreach (PropertyInfo property in result.GetType().GetProperties())
                {
                    SettingAttribute att = GetSettingAttribute(property);
                    if (att == null)
                    {
                        continue;
                    }
                    SettingsFileHandler s = (att.SettingScope == SettingScope.Global ? globalHandler : userHandler);
                    try
                    {
                        object value = s.GetValue(property.Name, property.PropertyType);
                        if (value == null)
                        {
                            if (att.HasDefault)
                            {
                                value = att.DefaultValue;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        property.SetValue(result, value, null);
                    }
                    catch (Exception e)
                    {
                        ServiceRegistration.Get <ILogger>().Error("SettingsManager: Error setting property '{0}' in settings of type '{1}'" +
                                                                  (att.HasDefault ? ", using default value" : string.Empty), e, property.Name, settingsType.Name);
                        if (att.HasDefault)
                        {
                            property.SetValue(result, att.DefaultValue, null);
                        }
                    }
                }
                if (!globalHandler.SettingsFileExists && !userHandler.SettingsFileExists)
                {
                    SaveSettingsObject(result);
                }
                return(result);
            }
            catch (Exception e)
            {
                ServiceRegistration.Get <ILogger>().Error("SettingsManager: Error loading settings of type '{0}'", e, settingsType.Name);
                return(null);
            }
        }
コード例 #21
0
        private void ReadFromPath(string absPathSettingsFile, bool quiet)
        {
            StringSettings = new Dictionary <string, string>();
            IntSettings    = new Dictionary <string, int>();

            Dictionary <string, PropertyInfo> props = GetPropertyDictionary();

            if (!File.Exists(absPathSettingsFile))
            {
                using (StreamWriter file = new StreamWriter(absPathSettingsFile))
                {
                    Debug?.WriteLine(string.Format("File {0} does not exist. Create with default values.", absPathSettingsFile));
                    foreach (var prop in props)
                    {
                        SettingAttribute attr = prop.Value.GetCustomAttribute(typeof(SettingAttribute)) as SettingAttribute;
                        if (attr == null)
                        {
                            throw new ArgumentNullException();
                        }
                        if (!string.IsNullOrWhiteSpace(attr.Comment))
                        {
                            file.WriteLine(string.Format("# {0}", attr.Comment));
                        }
                        string name        = prop.Key;
                        object valueObject = GetValueFromProp(prop.Value);
                        string value       = valueObject.ToString();
                        file.WriteLine(string.Format("{0}={1}", name, value));
                    }
                }
            }
            if (!quiet)
            {
                Debug?.WriteLine(string.Format("Reading settings from file {0}...", absPathSettingsFile));
            }
            using (StreamReader reader = File.OpenText(absPathSettingsFile))
            {
                string line;
                int    lineCount = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    lineCount++;
                    string trim = line.TrimStart();
                    if (trim.StartsWith(';') || trim.StartsWith('#') || trim.StartsWith("//"))
                    {
                        continue;
                    }
                    int posEq = line.IndexOf('=');
                    if (posEq > 0 && line.Length > posEq)
                    {
                        string name  = line.Substring(0, posEq);
                        string value = line.Substring(posEq + 1);
                        if (props.TryGetValue(name, out PropertyInfo prop))
                        {
                            object propValue = GetValueFromProp(prop);
                            if (propValue is string)
                            {
                                prop.SetValue(this, value, null);
                                propValue = value;
                                StringSettings.Add(name, value);
                            }
                            else if (propValue is int)
                            {
                                if (int.TryParse(value, out int intValue))
                                {
                                    propValue = intValue;
                                    prop.SetValue(this, intValue, null);
                                    IntSettings.Add(name, intValue);
                                }
                            }
                            else
                            {
                                Debug?.WriteLine(string.Format("Unsupprted type of setting \"{0}\" on line {1}", name, lineCount));
                            }
                        }
                        else
                        {
                            Debug?.WriteLine(string.Format("Unknown setting \"{0}\" on line {1}", name, lineCount));
                        }
                    }
                    else
                    {
                        Debug?.WriteLine(string.Format("Bad syntax on line {0}", lineCount));
                    }
                }
            }
        }
コード例 #22
0
        public void CreaDocumentosElectronicos()

        {
            AppDbContex dbContex = new AppDbContex();

            string LogName = "Facturacion.log";
            string errores = "";


            try
            {
                dbContex = new AppDbContex();


                //buscar cabeceras sin folio y sin procesar

                List <VentaDTOs> pedidos = dbContex.VentaDTOs.Where(c => ((c.folio == null) || (c.pdf == null))).ToList <VentaDTOs>();

                Log("Pendientes: " + (Convert.ToString(pedidos.Count)), ruta + @"\Pendientes.txt");


                foreach (VentaDTOs pedidoReferencia in pedidos)
                {
                    if (finalizar)
                    {
                        break;
                    }

                    try
                    {
                        VentaDTOs pedido = dbContex.VentaDTOs.Find(pedidoReferencia.id);

                        var cfg = Properties.Settings.Default;

                        pedido.FechaDocele = DateTime.Now;

                        if (pedido.rutEmpresa != cfg.RutEmisor)
                        {
                            pedido.ErrorDocElec = "Rut empresa no coincide con el configurado";
                            try
                            {
                                dbContex.SaveChanges();
                            }
                            catch (Exception e)
                            {
                                errores += e.Message;
                            }
                            continue;
                        }


                        string mensajeValidacion = "";

                        if (!Validaciones(pedido, ref mensajeValidacion))
                        {
                            pedido.ErrorDocElec = mensajeValidacion;
                            try
                            {
                                dbContex.SaveChanges();
                                Log(mensajeValidacion, ruta + @"\ErrorValidacion.txt");
                            }
                            catch (Exception e)
                            {
                                errores += e.Message;
                            }
                            continue;
                        }


                        try
                        {
                            dbContex.SaveChanges();
                        }
                        catch (Exception e)
                        {
                            errores += e.Message;
                            continue;
                        }



                        if (string.IsNullOrEmpty(ruta))
                        {
                            return;
                        }



                        try
                        {
                            string test = ruta + @"\Pdfs";

                            File.WriteAllText(test + @"\test.pdf", "test");
                        }
                        catch (Exception)
                        {
                            return;
                        }

                        SettingAttribute st = new SettingAttribute();

                        string rutEmisor = cfg.RutEmisor;


                        ServiceFacturacionBES.SolicitarFolio ResponseFolio = new ServiceFacturacionBES.SolicitarFolio();



                        ServiceFacturacionBES.DTELocal WS = new ServiceFacturacionBES.DTELocal();//  ("DTELocalSoap", tienda.Facturador.HostWebService);
                        //WS.Url = tienda.Facturador.HostWebService;



                        int folio = 0;

                        if (pedido.folio != null)
                        {
                            folio = (int)pedido.folio;
                        }

                        //Si es cero se solicita un nuevo Folio y lo asigna al registro
                        if (folio == 0)
                        {
                            ResponseFolio = WS.Solicitar_Folio(rutEmisor, 39);
                            pedido.folio  = ResponseFolio.Folio;

                            try
                            {
                                dbContex.SaveChanges();
                                Log("SaveChanges: OK ", "debug.txt");
                            }
                            catch (Exception e)
                            {
                                errores += e.Message;
                            }
                        }
                        else
                        {
                            //lleno fake response :)
                            ResponseFolio.Folio      = folio;
                            ResponseFolio.Estatus    = 0;
                            ResponseFolio.MsgEstatus = "folio Bkp: ";
                        }



                        if (ResponseFolio.Estatus == 0)
                        {
                            try
                            {
                                string idVisual = "";


                                string email = "";
                                Log("Estatus 0 : " + ResponseFolio.MsgEstatus + Convert.ToString(ResponseFolio.Folio), ruta + @"\LastResponseFolio.txt");

                                //Entry entry = new Entry();

                                //entry = (Entry)JsonConvert.DeserializeObject<Entry>(entry.json, settings);


                                EnvioBOLETA txtBoleta = new EnvioBOLETA();
                                txtBoleta.version = "1.0";
                                //CARATULA
                                txtBoleta.SetDTE = new EnvioBOLETASetDTE();


                                txtBoleta.SetDTE.Caratula         = new EnvioBOLETASetDTECaratula();
                                txtBoleta.SetDTE.Caratula.version = "1.0";

                                txtBoleta.SetDTE.Caratula.RutEmisor = rutEmisor;
                                txtBoleta.SetDTE.Caratula.RutEnvia  = rutEmisor;

                                txtBoleta.SetDTE.Caratula.FchResol         = DateTime.Now;//2018-09-13
                                txtBoleta.SetDTE.Caratula.NroResol         = 80;
                                txtBoleta.SetDTE.Caratula.TmstFirmaEnv     = DateTime.Now;
                                txtBoleta.SetDTE.Caratula.SubTotDTE        = new EnvioBOLETASetDTECaratulaSubTotDTE();
                                txtBoleta.SetDTE.Caratula.SubTotDTE.TpoDTE = 39;
                                txtBoleta.SetDTE.Caratula.SubTotDTE.NroDTE = 1;

                                txtBoleta.SetDTE.DTE           = new EnvioBOLETASetDTEDTE();
                                txtBoleta.SetDTE.DTE.version   = "1.0";
                                txtBoleta.SetDTE.DTE.Documento = new EnvioBOLETASetDTEDTEDocumento();
                                //CABECERA
                                txtBoleta.SetDTE.DTE.Documento.Encabezado = new EnvioBOLETASetDTEDTEDocumentoEncabezado();

                                txtBoleta.SetDTE.DTE.Documento.Encabezado.IdDoc = new EnvioBOLETASetDTEDTEDocumentoEncabezadoIdDoc();

                                txtBoleta.SetDTE.DTE.Documento.Encabezado.IdDoc.TipoDTE = 39;
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.IdDoc.Folio   = Convert.ToInt32(ResponseFolio.Folio);

                                //se creara con fecha del pedido de Internet
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.IdDoc.FchEmis     = Convert.ToDateTime(pedido.created_date);
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.IdDoc.IndServicio = 3;

                                //EMISOR
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Emisor = new EnvioBOLETASetDTEDTEDocumentoEncabezadoEmisor();

                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Emisor.RUTEmisor    = rutEmisor;
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Emisor.RznSocEmisor = Norm(cfg.RznSocEmisor);
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Emisor.GiroEmisor   = Norm(cfg.GiroEmisor);
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Emisor.CdgSIISucur  = cfg.CdgSIISucur;
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Emisor.DirOrigen    = Norm(cfg.DirOrigen);
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Emisor.CmnaOrigen   = Norm(cfg.CmnaOrigen);
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Emisor.CiudadOrigen = Norm(cfg.CiudadOrigen);

                                //RECEPTOR
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor = new EnvioBOLETASetDTEDTEDocumentoEncabezadoReceptor();

                                email = pedido.email_addr;

                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor.RUTRecep = validarRut(pedido.cust_rut);
                                //CARATULA
                                txtBoleta.SetDTE.Caratula.RutReceptor = txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor.RUTRecep;

                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor.CdgIntRecep = "";
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor.RznSocRecep = Norm(pedido.first_name + " " + pedido.last_name);
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor.Contacto    = "";


                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor.DirRecep    = Norm(pedido.direccion1);
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor.CmnaRecep   = Norm(pedido.comuna);
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor.CiudadRecep = Norm(pedido.ciudad);

                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor.DirPostal    = Norm(pedido.direccion1);
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor.CmnaPostal   = Norm(pedido.comuna);
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Receptor.CiudadPostal = Norm(pedido.ciudad);



                                if (string.IsNullOrEmpty(email))
                                {
                                    email = "SinMail";
                                }

                                //FIN ENCABEZADO

                                //DETALLE

                                //Despacho
                                //double dif = 0;
                                //dif = Math.Round(entry.gross) - Math.Round(entry.totalWithDiscount);

                                //if (dif > 0)
                                //{
                                //    txtBoleta.SetDTE.DTE.Documento.Detalle = new EnvioBOLETASetDTEDTEDocumentoDetalle[entry.CheckoutItems.Count() + 1];
                                //}
                                //else
                                //{
                                txtBoleta.SetDTE.DTE.Documento.Detalle = new EnvioBOLETASetDTEDTEDocumentoDetalle[pedido.Items.Count()];
                                //}

                                int index = 0;


                                double ItemUnitario = 0;

                                foreach (var linea in pedido.Items)
                                {
                                    ItemUnitario = 0;
                                    txtBoleta.SetDTE.DTE.Documento.Detalle[index] = new EnvioBOLETASetDTEDTEDocumentoDetalle();

                                    txtBoleta.SetDTE.DTE.Documento.Detalle[index].NroLinDet = index + 1;

                                    ItemUnitario = linea.PriceLine / linea.qty;


                                    txtBoleta.SetDTE.DTE.Documento.Detalle[index].CdgItem           = new EnvioBOLETASetDTEDTEDocumentoDetalleCdgItem();
                                    txtBoleta.SetDTE.DTE.Documento.Detalle[index].CdgItem.TpoCodigo = "ALU";

                                    txtBoleta.SetDTE.DTE.Documento.Detalle[index].CdgItem.VlrCodigo = Norm(linea.itemcode);
                                    txtBoleta.SetDTE.DTE.Documento.Detalle[index].DscItem           = "";
                                    txtBoleta.SetDTE.DTE.Documento.Detalle[index].NmbItem           = Norm(linea.descripcion);
                                    txtBoleta.SetDTE.DTE.Documento.Detalle[index].QtyItem           = linea.qty;
                                    txtBoleta.SetDTE.DTE.Documento.Detalle[index].PrcItem           = Convert.ToInt32(Math.Round(ItemUnitario));
                                    txtBoleta.SetDTE.DTE.Documento.Detalle[index].MontoItem         = Convert.ToInt32(Math.Truncate(linea.PriceLine));

                                    index = index + 1;
                                }

                                // restar total items si total mayor agregar item po recargo despacho

                                ////calculo despacho


                                //if (dif > 0)
                                //{
                                //    txtBoleta.SetDTE.DTE.Documento.Detalle[index] = new EnvioBOLETASetDTEDTEDocumentoDetalle();

                                //    txtBoleta.SetDTE.DTE.Documento.Detalle[index].NroLinDet = index + 1;

                                //    txtBoleta.SetDTE.DTE.Documento.Detalle[index].CdgItem = new EnvioBOLETASetDTEDTEDocumentoDetalleCdgItem();
                                //    txtBoleta.SetDTE.DTE.Documento.Detalle[index].CdgItem.TpoCodigo = "ALU";

                                //    txtBoleta.SetDTE.DTE.Documento.Detalle[index].CdgItem.VlrCodigo = tienda.Facturador.DifDespachoOtrosCodigo;
                                //    txtBoleta.SetDTE.DTE.Documento.Detalle[index].DscItem = "";
                                //    txtBoleta.SetDTE.DTE.Documento.Detalle[index].NmbItem = tienda.Facturador.DifDespachoOtros; ;
                                //    txtBoleta.SetDTE.DTE.Documento.Detalle[index].QtyItem = 1;
                                //    txtBoleta.SetDTE.DTE.Documento.Detalle[index].PrcItem = Convert.ToInt32(Math.Truncate(dif));
                                //    txtBoleta.SetDTE.DTE.Documento.Detalle[index].MontoItem = Convert.ToInt32(Math.Truncate(dif));

                                //}


                                //66666666-6

                                //REF PAra PAGOS y caja vendedor
                                txtBoleta.SetDTE.DTE.Documento.Referencia = new EnvioBOLETASetDTEDTEDocumentoReferencia[3];

                                txtBoleta.SetDTE.DTE.Documento.Referencia[0]           = new EnvioBOLETASetDTEDTEDocumentoReferencia();
                                txtBoleta.SetDTE.DTE.Documento.Referencia[0].NroLinRef = 1;
                                txtBoleta.SetDTE.DTE.Documento.Referencia[0].CodRef    = "CAJA";
                                txtBoleta.SetDTE.DTE.Documento.Referencia[0].RazonRef  = "";
                                txtBoleta.SetDTE.DTE.Documento.Referencia[0].CodVndor  = " Venta Web " + pedido.id;

                                //idVisual = pedido.comments;


                                txtBoleta.SetDTE.DTE.Documento.Referencia[0].CodCaja = "Orden N: " + pedido.comments;



                                txtBoleta.SetDTE.DTE.Documento.Referencia[1]           = new EnvioBOLETASetDTEDTEDocumentoReferencia();
                                txtBoleta.SetDTE.DTE.Documento.Referencia[1].NroLinRef = 2;
                                txtBoleta.SetDTE.DTE.Documento.Referencia[1].CodRef    = "PAGO";

                                txtBoleta.SetDTE.DTE.Documento.Referencia[1].RazonRef = "TOTAL PAGOS: " + pedido.Pagos.Sum(p => p.monto);


                                txtBoleta.SetDTE.DTE.Documento.Referencia[1].CodVndor = "";
                                txtBoleta.SetDTE.DTE.Documento.Referencia[1].CodCaja  = "";

                                txtBoleta.SetDTE.DTE.Documento.Referencia[2]           = new EnvioBOLETASetDTEDTEDocumentoReferencia();
                                txtBoleta.SetDTE.DTE.Documento.Referencia[2].NroLinRef = 3;
                                txtBoleta.SetDTE.DTE.Documento.Referencia[2].CodRef    = "MTO";
                                txtBoleta.SetDTE.DTE.Documento.Referencia[2].RazonRef  = email;//cliente.email
                                txtBoleta.SetDTE.DTE.Documento.Referencia[2].CodVndor  = "";
                                txtBoleta.SetDTE.DTE.Documento.Referencia[2].CodCaja   = "";

                                //Totales
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Totales          = new EnvioBOLETASetDTEDTEDocumentoEncabezadoTotales();
                                txtBoleta.SetDTE.DTE.Documento.Encabezado.Totales.MntTotal = Convert.ToInt32(pedido.total_amt);

                                txtBoleta.SetDTE.DTE.Documento.ID = "R" + txtBoleta.SetDTE.DTE.Documento.Encabezado.Emisor.RUTEmisor + "T" + Convert.ToString(txtBoleta.SetDTE.DTE.Documento.Encabezado.IdDoc.TipoDTE) + "F" + Convert.ToString(ResponseFolio.Folio);
                                txtBoleta.SetDTE.ID = "R" + txtBoleta.SetDTE.DTE.Documento.Encabezado.Emisor.RUTEmisor + "T" + Convert.ToString(txtBoleta.SetDTE.DTE.Documento.Encabezado.IdDoc.TipoDTE) + "F" + Convert.ToString(ResponseFolio.Folio);

                                string temp = txtBoleta.ToXML().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n", "");



                                ServiceFacturacionBES.ProcesarTXTBoleta ResponseBOL = WS.Carga_TXTBoleta(temp, "XML");

                                if (ResponseBOL.Estatus == 0)
                                {
                                    string rutaPdfBkp = ruta + @"\Pdfs";



                                    pedido.folio        = ResponseFolio.Folio;
                                    pedido.pdf          = ResponseBOL.PDF;
                                    pedido.ErrorDocElec = "PROCESADO OK";
                                    pedido.FechaDocele  = DateTime.Now;

                                    dbContex.SaveChanges();


                                    Log(temp, ruta + @"\LastBolXML.txt");

                                    //escribe PDF

                                    try
                                    {
                                        File.WriteAllBytes(rutaPdfBkp + @"\" + idVisual + "-BO-" + Convert.ToString(ResponseFolio.Folio) + ".pdf", ResponseBOL.PDF);
                                    }
                                    catch (Exception e)
                                    {
                                    }
                                }
                                else
                                {
                                    pedido.ErrorDocElec = "Estatus: " + Convert.ToString(ResponseBOL.Estatus) + " " + ResponseBOL.MsgEstatus;
                                    pedido.FechaDocele  = DateTime.Now;
                                    dbContex.SaveChanges();
                                    Log("Estatus: " + Convert.ToString(ResponseBOL.Estatus) + " " + ResponseBOL.MsgEstatus, ruta + @"\LastResponseBOLError.txt");
                                    Log(temp, ruta + @"\BolXMLError.txt");
                                }
                            }

                            catch (Exception ex0)
                            {
                                Log("ex0:" + ex0.Message + ex0.ToString() + " " + ex0.Message + " " + ex0.InnerException, ruta + @"\ErrorTXTBoleta.txt");
                            }
                        }
                        else
                        {
                            Log(Convert.ToString(ResponseFolio.Estatus) + " " + ResponseFolio.MsgEstatus, ruta + @"\LastResponseFolio.txt");
                        }
                    }


                    catch (Exception ex1)
                    {
                        Log("ex1:" + ex1.Message + ex1.ToString(), ruta + @"\LastError.txt");
                    }
                }// Ciclo foreach
            }
            catch (Exception ex)
            {
                Log("ex: " + ex.ToString() + ex.Message, ruta + @"\LastError.txt");
            }

            finally
            {
                dbContex.Dispose();
            }
        }