Inheritance: MonoBehaviour
        /// <summary>
        /// Initializes a new instance of the <see cref="MainViewModel"/> class.
        /// </summary>
        public MainViewModel()
        {
            _manager = SettingsManager.Instance;
            _manager.Initialize(SettingsManager.SettingsInitialization.IncludeDisplayConfiguration);

            _displayConfiguration = _manager.GetSettingsDisplayConfiguration();

            _sections = new Dictionary<string, SectionViewModel>();

            foreach (SettingDescriptor descriptor in _manager)
            {
                SectionViewModel svm = null;
                if (!_sections.TryGetValue(descriptor.Identifier, out svm))
                {
                    svm = new SectionViewModel(_displayConfiguration.GetIdentifier(descriptor.Identifier));
                    svm.Identifier = descriptor.Identifier;
                    _sections.Add(svm.Identifier, svm);
                }

                SettingInfo setting = _displayConfiguration.GetSetting(descriptor.Identifier, descriptor.SettingItem.Name);
                if (setting == null)
                {
                    Logger.Instance.LogFormat(LogType.Warning, this, Properties.Resources.SettingNotFoundInDisplayConfiguration, descriptor.SettingItem.Name, descriptor.Identifier);
                    continue;
                }
                svm.Add(descriptor, setting);
            }

            // TODO: Sort the list afterwards
        }
Exemple #2
0
        public void SettingManager_With_TrackableObjects()
        {
            // arrange
            var settingsManager = new SettingsManager(SettingsTestsDirectory);
            var settings = new BuildServerSettings
            {
                User = new User { FirstName = "Alexander", LastName = "Beletsky" },
                Jobs = new List<Job> { new Job { Id = 0, Configuration = "Git", Name = "proj" } },
            };

            settingsManager.SaveSettings(settings);

            // act
            using (var trackableSettingsManager = new AutoSaveSettingsManager(settingsManager))
            {
                var restoredSettings = trackableSettingsManager.ReadSettings<BuildServerSettings>();
                restoredSettings.User.FirstName = "John";
                restoredSettings.User.LastName = "Doe";
            }

            // post
            var changedSettings = settingsManager.ReadSettings<BuildServerSettings>();
            Assert.That(changedSettings.User.FirstName, Is.EqualTo("John"));
            Assert.That(changedSettings.User.LastName, Is.EqualTo("Doe"));
        }
Exemple #3
0
 public PaymentController(ISession session, SettingsManager settings, PaymentModuleManager paymentModuleManager)
     : base(session)
 {
     _session = session;
     _settings = settings;
     _paymentModuleManager = paymentModuleManager;
 }
        public GeneratorDialog(IServiceProvider serviceProvider, int length)
        {
            InitializeComponent();

            Loaded += (s, e) =>
            {
                _settings = new ShellSettingsManager(serviceProvider);
                Icon = BitmapFrame.Create(new Uri("pack://application:,,,/TextGenerator;component/Resources/images.png", UriKind.RelativeOrAbsolute));

                Title = Vsix.Name;

                SetLipsumTypes();
                SetSelection();

                txLength.Text = (length == 0 ? 20 : length).ToString();
                txLength.Focus();
                txLength.SelectAll();
            };

            PreviewKeyDown += (a, b) =>
            {
                if (b.Key == Key.Escape)
                    Close();
            };
        }
Exemple #5
0
        public MasterViewModel()
        {
            // Create a new settings manager and associate it with our
            // .eup file type.
            _settingsManager = new SettingsManager(
                "eup",
                "EasyFarm User Preference"
                );

            // Get events from view models to update the status bar's text.
            AppInformer.EventAggregator.GetEvent<StatusBarUpdateEvent>().Subscribe(a => { StatusBarText = a; });

            // Bind commands to their handlers.
            StartCommand = new DelegateCommand(Start);
            ExitCommand = new DelegateCommand(Exit);
            SaveCommand = new DelegateCommand(Save);
            LoadCommand = new DelegateCommand(Load);
            SelectProcessCommand = new DelegateCommand(SelectProcess);

            // Hook up our trayicon for minimization to system tray
            if (File.Exists(TrayIconFileName))
            {
                _trayIcon.Icon = new Icon(TrayIconFileName);
                MasterView.View.StateChanged += OnStateChanged;
                _trayIcon.Click += TrayIcon_Click;
            }
        }
        public InstallDialog(IServiceProvider serviceProvider, params IPackageProvider[] providers)
        {
            InitializeComponent();

            _providers = providers;

            Loaded += (s, e) =>
            {
                _settings = new ShellSettingsManager(serviceProvider);

                Closing += StoreLastUsed;
                cbName.Focus();

                cbVersion.ItemsSource = new[] { LATEST };
                cbVersion.GotFocus += VersionFocus;

                cbType.ItemsSource = _providers;
                cbType.DisplayMemberPath = nameof(IPackageProvider.Name);
                cbType.SelectionChanged += TypeChanged;

                string lastUsed = GetLastUsed();

                if (string.IsNullOrEmpty(lastUsed))
                {
                    cbType.SelectedIndex = 0;
                }
                else
                {
                    var provider = providers.FirstOrDefault(p => p.Name.Equals(lastUsed, StringComparison.OrdinalIgnoreCase));
                    if (provider != null)
                        cbType.SelectedItem = provider;
                }
            };
        }
			public void WhenPersisting_ShouldUseFullTypename()
			{
                var manager = new SettingsManager(Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider);
				var foo = new FooSettings(manager);

				foo.BeginEdit();
				foo.DefaultValueStringProperty = "WhenEndingEdit_ValuesShouldPersist";
				foo.DefaultValueIntProperty = 65001;
				foo.EndEdit();

				var sameTypeName = new Clide.IntegrationTests.OtherNamespace.FooSettings(manager);
				sameTypeName.BeginEdit();
				sameTypeName.DefaultValueStringProperty = "abc";
				sameTypeName.DefaultValueIntProperty = 123;
				sameTypeName.EndEdit();

				// reload from settings store
				manager.Read(foo);
				manager.Read(sameTypeName);

				// check the just edited values are there
				Assert.Equal("WhenEndingEdit_ValuesShouldPersist", foo.DefaultValueStringProperty);
				Assert.Equal(65001, foo.DefaultValueIntProperty);
				Assert.Equal("abc", sameTypeName.DefaultValueStringProperty);
				Assert.Equal(123, sameTypeName.DefaultValueIntProperty);
			}
			public void WhenSavingSettings_ThenCanReadThem()
			{
                var manager = new SettingsManager(Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider);

				var foo = new Foo
				{
					StringProperty = "World",
					IntProperty = -1,
					DefaultValueIntProperty = -20,
					DefaultValueAsStringIntProperty = 25,
					EnumProperty = UriFormat.SafeUnescaped,
					DefaultValueEnumProperty = UriFormat.Unescaped,
					ComplexTypeWithConverter = new Bar("BarValue"),
					PingInterval = TimeSpan.FromMinutes(2),
				};

				manager.Save(foo);

				var saved = new Foo();
				manager.Read(saved);

				Assert.Equal("World", saved.StringProperty);
				Assert.Equal("Hello", saved.DefaultValueStringProperty);
				Assert.Equal(-1, saved.IntProperty);
				Assert.Equal(-20, saved.DefaultValueIntProperty);
				Assert.Equal(25, saved.DefaultValueAsStringIntProperty);
				Assert.Equal(UriFormat.SafeUnescaped, saved.EnumProperty);
				Assert.Equal(UriFormat.Unescaped, saved.DefaultValueEnumProperty);
				Assert.NotNull(saved.ComplexTypeWithConverter);
				Assert.Equal("BarValue", saved.ComplexTypeWithConverter.Value);
				Assert.Equal(TimeSpan.FromMinutes(2), saved.PingInterval);
			}
Exemple #9
0
 private static ISettingsManager GetSettings()
 {
     string execDir = GetExecDir();
     string settingsFilePath = Path.Combine(execDir, "settings.txt");
     SettingsManager smng = new SettingsManager();
     smng.Load(settingsFilePath);
     return smng;
 }
Exemple #10
0
        public Program()
        {
            workers = new List<TaskWorker>();

            _settings = new SettingsManager();
            _settings.Changed += _settings_Changed;
            _settings_Changed(null, null);

            InitializeComponent();
        }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
        {
     EntropySourceManager.Poller.Abort();
     Host.Dispose();
     SettingsManager.Save();
        }
        SettingsManager = null;
        Instance = null;
 }
        private void LoadSettings()
        {
            _hasLoaded = true;

            _settingsManager = new ShellSettingsManager(serviceProvider);
            SettingsStore store = _settingsManager.GetReadOnlySettingsStore(SettingsScope.UserSettings);

            LogoAdornment.VisibilityChanged += AdornmentVisibilityChanged;

            _isVisible = store.GetBoolean(Constants.CONFIG_FILENAME, _propertyName, true);
        }
Exemple #13
0
        public void ReadSettings_IfNoSettingsCreated_ReturnNewObject()
        {
            // arrange
            var settingsManager = new SettingsManager(SettingsTestsDirectory);

            // act
            var settings = settingsManager.ReadSettings<NoSuchSettings>();

            // assert
            Assert.That(settings, Is.Not.Null);
        }
        public void AddOneToManager()
        {
            // Setup
            var settingsManager = new SettingsManager();

            // Operation
            settingsManager.Set(new HierarchicalPath("/a"), new SettingsA1(2, "two"));

            // Verification
            Assert.AreEqual(1, settingsManager.Count);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MainViewModel"/> class.
        /// </summary>
        public MainViewModel()
        {
            _manager = SettingsManager.Instance;
            _manager.Initialize(SettingsManager.SettingsInitialization.IncludeDisplayConfiguration);

            _displayConfiguration = _manager.GetSettingsDisplayConfiguration();
            BuildSectionsTree();

            _serviceStatePollingTimer = new Timer(2000d);
            _serviceStatePollingTimer.Elapsed += _serviceStatePollingTimer_Elapsed;
            _serviceStatePollingTimer.Start();
        }
        public void SettingManagerTest()
        {
            Func<IPlatformRepository> platformRepositoryFactory = GetPlatformRepository;

            var cacheManager = new CacheManager(new InMemoryCachingProvider(), null);
            var settingManager = new SettingsManager(null, platformRepositoryFactory, cacheManager, null);

            var name = Guid.NewGuid().ToString();

            settingManager.SetValue(name, 1); // сохраняется
            settingManager.SetValue(name, 2); // не сохраняется
        }
        public void populateTree(SettingsManager settings)
        {
            this.settings = settings;

            // stop redrawing and clear tree
            advancedSettingsTreeView.BeginUpdate();
            advancedSettingsTreeView.Nodes.Clear();

            // loop through all settings and add nodes for groups and settings accordingly.
            // maintain a dictionary of groups to ensure on one listing per group.
            foreach (DBSetting currSetting in settings.AllSettings) {
                if (currSetting.Hidden) continue;

                string groupKey = "";
                TreeNode parentNode = null;

                // loop through all parent groups of this setting and if no node has been made for any
                // of them yet, go ahead and make a node
                foreach (string currGroup in currSetting.Grouping) {
                    groupKey += currGroup + '|';
                    if (!groups.ContainsKey(groupKey)) {
                        // create new node and place in TreeView
                        TreeNode newNode = new TreeNode(currGroup);
                        if (parentNode == null)
                            advancedSettingsTreeView.Nodes.Add(newNode);
                        else
                            parentNode.Nodes.Add(newNode);

                        // update parentNode var (*since we arer walking up group chain),
                        // and store node in our dictionary.
                        parentNode = newNode;
                        groups.Add(groupKey, newNode);
                    } else
                        parentNode = groups[groupKey];
                }

                // create a node for this setting an place it under it's parent group
                TreeNode settingNode = new TreeNode(currSetting.Name);
                settingNode.Tag = currSetting;
                settingNode.NodeFont = new Font(this.Font.Name, this.Font.Size,
                                                FontStyle.Regular, this.Font.Unit);

                if (parentNode == null)
                    advancedSettingsTreeView.Nodes.Add(settingNode);
                else
                    parentNode.Nodes.Add(settingNode);
            }

            // restrart drawing
            advancedSettingsTreeView.ExpandAll();
            advancedSettingsTreeView.EndUpdate();
        }
Exemple #18
0
 static PintaCore()
 {
     Resources = new ResourceManager ();
     Actions = new ActionManager ();
     Workspace = new WorkspaceManager ();
     Layers = new LayerManager ();
     Tools = new ToolManager ();
     History = new HistoryManager ();
     System = new SystemManager ();
     LivePreview = new LivePreviewManager ();
     Palette = new PaletteManager ();
     Settings = new SettingsManager ();
 }
Exemple #19
0
        void IModule.Install(ModuleManager manager)
        {
            _manager = manager;
            _client = manager.Client;
            _http = _client.Services.Get<HttpService>();
            _settings = _client.Services.Get<SettingsService>()
                .AddModule<StatusModule, Settings>(manager);

            manager.CreateCommands("status", group =>
            {
                group.MinPermissions((int)PermissionLevel.BotOwner);

                group.CreateCommand("enable")
                    .Parameter("channel", ParameterType.Optional)
                    .Do(async e =>
                    {
                        var settings = _settings.Load(e.Server);

                        Channel channel;
                        if (e.Args[0] != "")
                            channel = await _client.FindChannel(e, e.Args[0], ChannelType.Text);
                        else
                            channel = e.Channel;
                        if (channel == null) return;

                        settings.Channel = channel.Id;
                        await _settings.Save(e.Server, settings);

                        await _client.Reply(e, $"Enabled status reports in {channel.Name}");
                    });
                group.CreateCommand("disable")
                    .Do(async e =>
                    {
                        var settings = _settings.Load(e.Server);

                        settings.Channel = null;
                        await _settings.Save(e.Server, settings);

                        await _client.Reply(e, "Disabled status reports on this server.");
                    });
            });

            _client.LoggedIn += (s, e) =>
            {
                if (!_isRunning)
                {
                    Task.Run(Run);
                    _isRunning = true;
                }
            };
        }
        private void LoadSettings()
        {
            if (_hasLoaded)
                return;

            _hasLoaded = true;

            _settingsManager = new ShellSettingsManager(serviceProvider);
            SettingsStore store = _settingsManager.GetReadOnlySettingsStore(SettingsScope.UserSettings);

            LogoAdornment.VisibilityChanged += AdornmentVisibilityChanged;

            _isVisible = store.GetBoolean(Vsix.Name, _propertyName, true);
        }
 public ManagerLibrary(SettingsManager settings)
 {
     if (Instance != null)
     throw new InvalidOperationException("Only one ManagerLibrary instance can " +
      "exist at any one time");
        Instance = this;
        SettingsManager = settings;
        EntropySourceManager = new EntropySourceManager();
        PRNGManager = new PrngManager();
        ErasureMethodManager = new ErasureMethodManager();
        FileSystemManager = new FileSystemManager();
        Host = new Plugin.DefaultHost();
        Host.Load();
 }
        public void FirstSettingsDeployementTestMethod()
        {
            const string configName = "settings.config";
            var fullFileName = _appDataFolder + @"\" + configName;
            if (!Directory.Exists(_appDataFolder)) Directory.CreateDirectory(_appDataFolder);
            if (File.Exists(fullFileName)) File.Delete(fullFileName);

            Assert.IsFalse(File.Exists(fullFileName));

            var settingsManager = new SettingsManager<AppSettings>(AppName, new AppSettings {IsScreenSleepEnabled = false});
            settingsManager.GetConfig(); //First get => Reset config

            Assert.IsTrue(File.Exists(fullFileName));
        }
Exemple #23
0
        public static void Initialize(IServiceProvider provider)
        {
            _manager = new ShellSettingsManager(provider);
            _readStore = _manager.GetReadOnlySettingsStore(SettingsScope.UserSettings);
            _writeStore = _manager.GetWritableSettingsStore(SettingsScope.UserSettings);

            if (!_writeStore.CollectionExists(_name))
            {
                _writeStore.CreateCollection(_name);

                string defaults = string.Join(_separator, PreEnabledExtensions.List);
                _writeStore.SetString(_name, _identifierKey, defaults);
            }
        }
        public RoutesViewModel()
        {
            _settings = new SettingsManager("ewl", "EasyFarm Waypoint List");
                        
            ClearCommand = new DelegateCommand(ClearRoute);
            RecordCommand = new DelegateCommand(Record);
            SaveCommand = new DelegateCommand(Save);
            LoadCommand = new DelegateCommand(Load);
            ResetNavigatorCommand = new DelegateCommand(ResetNavigator);
            RecordHeader = "Record";

            // Create recorder on loaded fface session. 
            ViewModelBase.OnSessionSet += ViewModelBase_OnSessionSet;
        }
        public void ConvertFromAtoB()
        {
            // Setup
            var settingsManager = new SettingsManager();
            settingsManager.Set(new HierarchicalPath("/a"), new SettingsA1(1, "one"));

            // Operation
            var b = settingsManager.Get<SettingsA2>(
                "/a", SettingSearchOptions.SerializeDeserializeMapping);

            // Verification
            Assert.AreEqual(1, settingsManager.Count);
            Assert.AreEqual(1, b.A);
            Assert.AreEqual("one", b.B);
        }
			public void WhenCancellingEdit_ValuesShouldNotPersist()
			{
                var manager = new SettingsManager(Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider);
				var foo = new FooSettings(manager);

				foo.BeginEdit();
				// change the current value
				foo.DefaultValueStringProperty = "WhenCancellingEdit_ValuesShouldNotPersist";
				foo.DefaultValueIntProperty = 65000;
				// cancel edit, should revert edit changes back to original values
				foo.CancelEdit();
				// check just edited values are not there anymore
				Assert.NotEqual("WhenCancellingEdit_ValuesShouldNotPersist", foo.DefaultValueStringProperty);
				Assert.NotEqual(65000, foo.DefaultValueIntProperty);
			}
			public void WhenEndingEdit_ValuesShouldPersist()
			{
                var manager = new SettingsManager(Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider);
				var foo = new FooSettings(manager);

				foo.BeginEdit();
				foo.DefaultValueStringProperty = "WhenEndingEdit_ValuesShouldPersist";
				foo.DefaultValueIntProperty = 65001;
				foo.EndEdit();
				// reload from settings store
				manager.Read(foo);
				// check the just edited values are there
				Assert.Equal("WhenEndingEdit_ValuesShouldPersist", foo.DefaultValueStringProperty);
				Assert.Equal(65001, foo.DefaultValueIntProperty);
			}
        public void LoadCorruptSettingsTestMethod()
        {
            const string configName = "corrupt_settings.config";
            const string corruptConfigContent = "\"IsScredsqdsqs\"enSleepEnabled\":false}";

            var fullFileName = _appDataFolder + @"\" + configName;
            if (!Directory.Exists(_appDataFolder)) Directory.CreateDirectory(_appDataFolder);
            if (File.Exists(fullFileName)) File.Delete(fullFileName);

            File.WriteAllText(fullFileName, corruptConfigContent);

            var settingsManager = new SettingsManager<AppSettings>(AppName, new AppSettings { IsScreenSleepEnabled = false }, configName);
            var config = settingsManager.GetConfig();

            Assert.IsFalse(config.IsScreenSleepEnabled);
        }
Exemple #29
0
        public void SettingsManager_SaveSettings()
        {
            // arrange
            var settingsManager = new SettingsManager(SettingsTestsDirectory);
            var settings = new BuildServerSettings
            {
                User = new User { FirstName = "Alexander", LastName = "Beletsky" },
                Jobs = new List<Job> { new Job { Id = 0, Configuration = "Git", Name = "proj" } },
            };

            // act
            settingsManager.SaveSettings(settings);

            // post
            var restoredSettings = settingsManager.ReadSettings<BuildServerSettings>();
            Assert.That(Comparer.Compare(settings, restoredSettings), Is.True);
        }
			public void WhenReadingSettingsAndNoExistingOne_ThenReadsDefaultValues()
			{
                var manager = new SettingsManager(Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider);

				var foo = new Foo();
				manager.Read(foo);

				Assert.Null(foo.StringProperty);
				Assert.Equal("Hello", foo.DefaultValueStringProperty);
				Assert.Equal(0, foo.IntProperty);
				Assert.Equal(5, foo.DefaultValueIntProperty);
				Assert.Equal(25, foo.DefaultValueAsStringIntProperty);
				Assert.Equal(0, (int)foo.EnumProperty);
				Assert.Equal(UriFormat.Unescaped, foo.DefaultValueEnumProperty);
				Assert.Null(foo.ComplexTypeWithConverter);
				Assert.Equal(TimeSpan.FromSeconds(5), foo.PingInterval);
			}
Exemple #31
0
        public void ChangeParamsWhileActive()
        {
            string settingsFileName = string.Format("{0}\\ServiceSettings.xml", m_TempPath);
            SettingsManager settingsManager = new SettingsManager(settingsFileName);
            settingsManager.ServiceGuid = s_TestServiceGuid;

            StackHashContextSettings settings = settingsManager.CreateNewContextSettings();
            settings.ErrorIndexSettings.Folder = m_TempPath;
            settings.ErrorIndexSettings.Name = "TestIndex";
            settings.ErrorIndexSettings.Type = ErrorIndexType.Xml;

            ScriptManager scriptManager = new ScriptManager(m_ScriptPath);
            IDebugger debugger = new Windbg();

            settings.WinQualSettings.UserName = "******";
            settings.WinQualSettings.Password = "******";
            settings.WinQualSyncSchedule = new ScheduleCollection();
            Schedule schedule = new Schedule();
            schedule.Period = SchedulePeriod.Daily;
            schedule.DaysOfWeek = Schedule.EveryDay;

            DateTime now = DateTime.Now; // Must get local time.
            DateTime syncTime = now.AddSeconds(100);

            schedule.Time = new ScheduleTime(syncTime.Hour, syncTime.Minute, syncTime.Second);
            settings.WinQualSyncSchedule.Add(schedule);

            string licenseFileName = string.Format("{0}\\License.bin", m_TempPath);
            LicenseManager licenseManager = new LicenseManager(licenseFileName, s_TestServiceGuid);
            licenseManager.SetLicense(s_LicenseId);


            ControllerContext context = new ControllerContext(settings, scriptManager, debugger, settingsManager, true, StackHashTestData.Default, licenseManager);
            context.AdminReports += new EventHandler<AdminReportEventArgs>(this.OnAdminReport);

            try
            {
                context.Activate();


                // Create and delete some new context settings - should have no effect.
                StackHashContextSettings settings2 = settingsManager.CreateNewContextSettings();
                settingsManager.RemoveContextSettings(settings2.Id, true);

                // Change the existing active context.
                settings2.Id = 0;
                settings2.ErrorIndexSettings.Folder = m_TempPath;
                settings2.ErrorIndexSettings.Name = "TestIndex";
                settings2.ErrorIndexSettings.Type = ErrorIndexType.Xml;

                settings2.WinQualSettings.UserName = "******";
                settings2.WinQualSettings.Password = "******";
                settings2.WinQualSyncSchedule = new ScheduleCollection();
                schedule = new Schedule();
                schedule.Period = SchedulePeriod.Hourly;
                schedule.DaysOfWeek = Schedule.EveryDay;

                now = DateTime.Now;
                syncTime = now.AddSeconds(5);

                schedule.Time = new ScheduleTime(syncTime.Hour, syncTime.Minute, syncTime.Second);
                settings2.WinQualSyncSchedule.Add(schedule);

                context.UpdateSettings(settings2);

                // Wait for the timer to expire.
                Assert.AreEqual(true, m_WinQualSyncEvent.WaitOne(10000));
                Assert.AreEqual(true, m_AnalyzeEvent.WaitOne(10000));

                Assert.AreEqual(1, m_SyncCount);
                Assert.AreEqual(1, m_AnalyzeCount);

                context.Deactivate();
                Assert.AreEqual(false, context.IsActive);
                Assert.AreEqual(null, context.WinQualSyncTimerTask);
            }
            finally
            {
                context.AdminReports -= new EventHandler<AdminReportEventArgs>(this.OnAdminReport);
                context.Dispose();
            }
        }
        public static SettingsManager GetSettingsManager(IServiceProvider provider)
        {
            SettingsManager settings   = null;
            string          devenvPath = null;

            if (provider == null)
            {
                provider = ServiceProvider.GlobalProvider;
            }

            if (provider != null)
            {
                try {
                    settings = new ShellSettingsManager(provider);
                } catch (NotSupportedException) {
                    var dte = (DTE)provider.GetService(typeof(DTE));
                    if (dte != null)
                    {
                        devenvPath = dte.FullName;
                    }
                }
            }

            if (settings == null)
            {
                if (!File.Exists(devenvPath))
                {
                    // Running outside VS, so we need to guess which SKU of VS
                    // is being used. This will work correctly if any one SKU is
                    // installed, but may select the wrong SKU if multiple are
                    // installed. As a result, custom environments may not be
                    // available when building or testing Python projects.
                    string devenvRoot = null;
                    using (var root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
                        using (var key = root.OpenSubKey(string.Format(@"Software\Microsoft\VisualStudio\{0}\Setup\VS", AssemblyVersionInfo.VSVersion))) {
                            if (key != null)
                            {
                                devenvRoot = key.GetValue("ProductDir") as string;
                            }
                        }
                    if (Directory.Exists(devenvRoot))
                    {
                        foreach (var subPath in new[] {
                            "Common7\\IDE\\devenv.exe",
                            "Common7\\IDE\\vwdexpress.exe",
                            "Common7\\IDE\\wdexpress.exe"
                        })
                        {
                            devenvPath = Path.Combine(devenvRoot, subPath);
                            if (File.Exists(devenvPath))
                            {
                                break;
                            }
                            devenvPath = null;
                        }
                    }
                }
                if (!File.Exists(devenvPath))
                {
                    throw new InvalidOperationException("Cannot find settings store for Visual Studio " + AssemblyVersionInfo.VSVersion);
                }
#if DEBUG
                settings = ExternalSettingsManager.CreateForApplication(devenvPath, "Exp");
#else
                settings = ExternalSettingsManager.CreateForApplication(devenvPath);
#endif
            }

            return(settings);
        }
 public static ProductActionStatus UpdateProduct(ProductInfo product, Dictionary<string, SKUItem> skus, Dictionary<int, IList<int>> attrs, IList<int> tagIds,string wid)
 {
     if (product == null)
     {
         return ProductActionStatus.UnknowError;
     }
     Globals.EntityCoding(product, true);
     int decimalLength = SettingsManager.GetMasterSettings(true,wid).DecimalLength;
     if (product.MarketPrice.HasValue)
     {
         product.MarketPrice = new decimal?(Math.Round(product.MarketPrice.Value, decimalLength));
     }
     ProductActionStatus unknowError = ProductActionStatus.UnknowError;
     using (DbConnection connection = DatabaseFactory.CreateDatabase().CreateConnection())
     {
         connection.Open();
         DbTransaction dbTran = connection.BeginTransaction();
         try
         {
             ProductDao dao = new ProductDao();
             if (!dao.UpdateProduct(product, dbTran))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.DuplicateSKU;
             }
             if (!dao.DeleteProductSKUS(product.ProductId, dbTran))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.SKUError;
             }
             if (((skus != null) && (skus.Count > 0)) && !dao.AddProductSKUs(product.ProductId, skus, dbTran,wid))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.SKUError;
             }
             if (!dao.AddProductAttributes(product.ProductId, attrs, dbTran))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.AttributeError;
             }
             if (!new TagDao().DeleteProductTags(product.ProductId, dbTran))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.ProductTagEroor;
             }
             if ((tagIds.Count > 0) && !new TagDao().AddProductTags(product.ProductId, tagIds, dbTran))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.ProductTagEroor;
             }
             dbTran.Commit();
             unknowError = ProductActionStatus.Success;
         }
         catch (Exception)
         {
             dbTran.Rollback();
         }
         finally
         {
             connection.Close();
         }
     }
     if (unknowError == ProductActionStatus.Success)
     {
         EventLogs.WriteOperationLog(Privilege.EditProducts, string.Format(CultureInfo.InvariantCulture, "修改了编号为 “{0}” 的商品", new object[] { product.ProductId }));
     }
     return unknowError;
 }
Exemple #34
0
 public override void Load()
 {
     _value = SettingsManager.Load <MPExtendedProviderSettings>().TvServerHost;
 }
Exemple #35
0
        public virtual async Task LoadSitemapItemRecordsAsync(Store store, Sitemap sitemap, string baseUrl, Action <ExportImportProgressInfo> progressCallback = null)
        {
            var progressInfo = new ExportImportProgressInfo();

            var contentBasePath           = $"Pages/{sitemap.StoreId}";
            var storageProvider           = _blobStorageProviderFactory.CreateProvider(contentBasePath);
            var options                   = new SitemapItemOptions();
            var staticContentSitemapItems = sitemap.Items.Where(si => !string.IsNullOrEmpty(si.ObjectType) &&
                                                                (si.ObjectType.EqualsInvariant(SitemapItemTypes.ContentItem) ||
                                                                 si.ObjectType.EqualsInvariant(SitemapItemTypes.Folder)))
                                            .ToList();
            var totalCount = staticContentSitemapItems.Count;

            if (totalCount > 0)
            {
                var processedCount = 0;

                var acceptedFilenameExtensions = SettingsManager.GetValue(ModuleConstants.Settings.General.AcceptedFilenameExtensions.Name, ".md,.html")
                                                 .Split(',')
                                                 .Select(i => i.Trim())
                                                 .Where(i => !string.IsNullOrEmpty(i))
                                                 .ToList();

                progressInfo.Description = $"Content: Starting records generation  for {totalCount} pages";
                progressCallback?.Invoke(progressInfo);

                foreach (var sitemapItem in staticContentSitemapItems)
                {
                    var urls = new List <string>();
                    if (sitemapItem.ObjectType.EqualsInvariant(SitemapItemTypes.Folder))
                    {
                        var searchResult = await storageProvider.SearchAsync(sitemapItem.UrlTemplate, null);

                        var itemUrls = await GetItemUrls(storageProvider, searchResult);

                        foreach (var itemUrl in itemUrls)
                        {
                            var itemExtension = Path.GetExtension(itemUrl);
                            if (!acceptedFilenameExtensions.Any() ||
                                string.IsNullOrEmpty(itemExtension) ||
                                acceptedFilenameExtensions.Contains(itemExtension, StringComparer.OrdinalIgnoreCase))
                            {
                                urls.Add(itemUrl);
                            }
                        }
                    }
                    else if (sitemapItem.ObjectType.EqualsInvariant(SitemapItemTypes.ContentItem))
                    {
                        var item = await storageProvider.GetBlobInfoAsync(sitemapItem.UrlTemplate);

                        if (item != null)
                        {
                            urls.Add(item.RelativeUrl);
                        }
                    }
                    totalCount = urls.Count;

                    foreach (var url in urls)
                    {
                        using (var stream = storageProvider.OpenRead(url))
                        {
                            var content    = stream.ReadToString();
                            var yamlHeader = ReadYamlHeader(content);
                            yamlHeader.TryGetValue("permalink", out var permalinks);
                            var frontMatterPermalink = new FrontMatterPermalink(url.Replace(".md", ""));
                            if (permalinks != null)
                            {
                                frontMatterPermalink = new FrontMatterPermalink(permalinks.FirstOrDefault());
                            }
                            sitemapItem.ItemsRecords.AddRange(GetSitemapItemRecords(store, options, frontMatterPermalink.ToUrl().TrimStart('/'), baseUrl));

                            processedCount++;
                            progressInfo.Description = $"Content: Have been generated records for {processedCount} of {totalCount} pages";
                            progressCallback?.Invoke(progressInfo);
                        }
                    }
                }
            }
        }
 public static List <ThumbnailItem> SaveThumbnails(UserPhotoManager userPhotoManager, SettingsManager settingsManager, Point point, Size size, Guid userId)
 {
     return(SaveThumbnails(userPhotoManager, settingsManager, new UserPhotoThumbnailSettings(point, size), userId));
 }
Exemple #37
0
        private static async Task Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

            // var x = string.IsNullOrWhiteSpace("");

            // var ssss = new List<JsonZKill.ZkillOnly>().Count(a => a.killmail_id == 0);
            if (!File.Exists(SettingsManager.FileSettingsPath))
            {
                await LogHelper.LogError("Please make sure you have settings.json file in bot folder! Create it and fill with correct settings.");

                try
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Please make sure you have settings.json file in bot folder! Create it and fill with correct settings.");
                    Console.ReadKey();
                }
                catch
                {
                    // ignored
                }

                return;
            }

            //load settings
            var result = await SettingsManager.Prepare();

            if (!string.IsNullOrEmpty(result))
            {
                await LogHelper.LogError(result);

                try
                {
                    Console.ReadKey();
                }
                catch
                {
                    // ignored
                }

                return;
            }

            APIHelper.Prepare();
            await LogHelper.LogInfo($"ThunderED v{VERSION} is running!").ConfigureAwait(false);

            //load database provider
            var rs = await SQLHelper.LoadProvider();

            if (!string.IsNullOrEmpty(rs))
            {
                await LogHelper.LogError(result);

                try
                {
                    Console.ReadKey();
                }
                catch
                {
                    // ignored
                }

                return;
            }

            await SQLHelper.InitializeBackup();

            //load language
            await LM.Load();

            //load injected settings
            await SettingsManager.UpdateInjectedSettings();

            //load APIs
            await APIHelper.DiscordAPI.Start();

            while (!APIHelper.DiscordAPI.IsAvailable)
            {
                await Task.Delay(10);
            }

            if (APIHelper.DiscordAPI.GetGuild() == null)
            {
                await LogHelper.LogError("[CRITICAL] DiscordGuildId - Discord guild not found!");

                try
                {
                    Console.ReadKey();
                }
                catch
                {
                    // ignored
                }

                return;
            }

            //initiate core timer
            _timer = new Timer(TickManager.Tick, new AutoResetEvent(true), 100, 100);

            Console.CancelKeyPress += (sender, e) =>
            {
                e.Cancel = false;
                _timer?.Dispose();
                APIHelper.DiscordAPI.Stop();
            };

            AppDomain.CurrentDomain.UnhandledException += async(sender, eventArgs) =>
            {
                await LogHelper.LogEx($"[UNHANDLED EXCEPTION]", (Exception)eventArgs.ExceptionObject);

                await LogHelper.LogWarning($"Consider restarting the service...");
            };

            while (true)
            {
                if (!SettingsManager.Settings.Config.RunAsServiceCompatibility)
                {
                    var command = Console.ReadLine();
                    var arr     = command?.Split(" ");
                    if ((arr?.Length ?? 0) == 0)
                    {
                        continue;
                    }
                    switch (arr[0])
                    {
                    case "quit":
                        Console.WriteLine("Quitting...");
                        _timer.Dispose();
                        APIHelper.DiscordAPI.Stop();
                        return;

                    case "flushn":
                        Console.WriteLine("Flushing all notifications DB list");
                        await SQLHelper.RunCommand("delete from notificationsList");

                        break;

                    case "flushcache":
                        Console.WriteLine("Flushing all cache from DB");
                        await SQLHelper.RunCommand("delete from cache");

                        break;

                    case "help":
                        Console.WriteLine("List of available commands:");
                        Console.WriteLine(" quit    - quit app");
                        Console.WriteLine(" flushn  - flush all notification IDs from database");
                        Console.WriteLine(" getnurl - display notification auth url");
                        Console.WriteLine(" flushcache - flush all cache from database");
                        Console.WriteLine(" token [ID] - refresh and display EVE character token from database");
                        break;

                    case "token":
                        if (arr.Length == 1)
                        {
                            continue;
                        }
                        if (!long.TryParse(arr[1], out var id))
                        {
                            continue;
                        }
                        var rToken = await SQLHelper.GetRefreshTokenDefault(id);

                        Console.WriteLine(await APIHelper.ESIAPI
                                          .RefreshToken(rToken, SettingsManager.Settings.WebServerModule.CcpAppClientId, SettingsManager.Settings.WebServerModule.CcpAppSecret));
                        break;
                    }

                    await Task.Delay(10);
                }
                else
                {
                    await Task.Delay(500);
                }
            }
        }
Exemple #38
0
        private void BindControl()
        {
            SiteSettings siteSettings = SettingsManager.GetMasterSettings();

            this.txtContactName.Text  = siteSettings.HiPOSContactName;
            this.txtContactPhone.Text = siteSettings.HiPOSContactPhone;
            this.txtSellerName.Text   = siteSettings.HiPOSSellerName;
            this.txtExpireAt.Text     = siteSettings.HiPOSExpireAt;
            PaymentModeInfo         paymentModeInfo = null;
            IList <PaymentModeInfo> paymentModes    = SalesHelper.GetPaymentModes(PayApplicationType.payOnAll);

            (from c in paymentModes
             where c.Gateway.Contains("alipay")
             select c).ForEach(delegate(PaymentModeInfo alipayPayment)
            {
                paymentModeInfo = SalesHelper.GetPaymentMode(alipayPayment.ModeId);
                Globals.EntityCoding(paymentModeInfo, false);
                ConfigablePlugin configablePlugin2 = PaymentRequest.CreateInstance(paymentModeInfo.Gateway.ToLower());
                if (configablePlugin2 == null)
                {
                    base.GotoResourceNotFound();
                }
                else
                {
                    Globals.EntityCoding(paymentModeInfo, false);
                    ConfigData configData2      = new ConfigData(HiCryptographer.Decrypt(paymentModeInfo.Settings));
                    this.configXml              = configData2.SettingsXml;
                    this.txtZFBConfigData.Value = configData2.SettingsXml;
                    string text5 = this.GetNodeValue(this.txtZFBConfigData.Value, "Partner").Trim();
                    if (string.IsNullOrEmpty(this.txtZFBPID.Text))
                    {
                        this.txtZFBPID.Text = text5;
                    }
                }
            });
            (from c in paymentModes
             where c.Gateway.Contains(".wx")
             select c).ForEach(delegate(PaymentModeInfo wxPayment)
            {
                paymentModeInfo = SalesHelper.GetPaymentMode(wxPayment.ModeId);
                Globals.EntityCoding(paymentModeInfo, false);
                ConfigablePlugin configablePlugin = PaymentRequest.CreateInstance(paymentModeInfo.Gateway.ToLower());
                if (configablePlugin == null)
                {
                    base.GotoResourceNotFound();
                }
                else
                {
                    Globals.EntityCoding(paymentModeInfo, false);
                    ConfigData configData      = new ConfigData(HiCryptographer.Decrypt(paymentModeInfo.Settings));
                    this.txtWXConfigData.Value = configData.SettingsXml;
                    string text  = (!string.IsNullOrEmpty(siteSettings.HiPOSWXAppId)) ? siteSettings.HiPOSWXAppId : this.GetNodeValue(this.txtWXConfigData.Value, "AppId").Trim();
                    string text2 = (!string.IsNullOrEmpty(siteSettings.HiPOSWXMchId)) ? siteSettings.HiPOSWXMchId : this.GetNodeValue(this.txtWXConfigData.Value, "MCHID").Trim();
                    string text3 = (!string.IsNullOrEmpty(siteSettings.HiPOSWXCertPath)) ? siteSettings.HiPOSWXCertPath : this.GetNodeValue(this.txtWXConfigData.Value, "CertPath").Trim();
                    if (string.IsNullOrEmpty(this.txtWXAppId.Text))
                    {
                        this.txtWXAppId.Text = text;
                    }
                    if (string.IsNullOrEmpty(this.txtWXMchId.Text))
                    {
                        this.txtWXMchId.Text = text2;
                    }
                    if (string.IsNullOrEmpty(this.hdCertPath.Value) && !string.IsNullOrEmpty(text3))
                    {
                        string text4 = text3.Replace("\\", "/").Replace("//", "/").Replace("/", "\\");
                        if (!File.Exists(text4))
                        {
                            text4 = Globals.PhysicalPath(text3).Replace("\\", "/").Replace("//", "/")
                                    .Replace("/", "\\");
                        }
                        this.hdCertPath.Value = text4 + " 删除重传";
                        this.fuWXCertPath.Style.Add("display", "none");
                    }
                }
            });
            this.ooZFB.SelectedValue = siteSettings.EnableHiPOSZFB;
            this.ooWX.SelectedValue  = siteSettings.EnableHiPOSWX;
            if (siteSettings.EnableHiPOSZFB)
            {
                this.txtZFBPID.Text = siteSettings.HiPOSZFBPID;
            }
            else
            {
                this.ulZFB.Style.Add("display", "none");
            }
            if (siteSettings.EnableHiPOSWX)
            {
                this.txtWXAppId.Text  = siteSettings.HiPOSWXAppId;
                this.txtWXMchId.Text  = siteSettings.HiPOSWXMchId;
                this.txtWXAPIKey.Text = siteSettings.HiPOSWXAPIKey;
            }
            else
            {
                this.ulWX.Style.Add("display", "none");
            }
            if (string.IsNullOrEmpty(this.txtZFBKey.Text.Trim()))
            {
                this.txtZFBKey.Text = this.CreatePubKeyContent();
            }
        }
Exemple #39
0
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            bool   selectedValue  = this.ooZFB.SelectedValue;
            bool   selectedValue2 = this.ooWX.SelectedValue;
            string empty          = string.Empty;
            string empty2         = string.Empty;
            string text           = this.txtZFBPID.Text;
            string text2          = this.txtZFBKey.Text;
            string text3          = this.txtWXAppId.Text.Trim();
            string text4          = this.txtWXMchId.Text.Trim();
            string text5          = this.txtWXAPIKey.Text.Trim();
            bool   flag           = false;

            if (string.IsNullOrEmpty(this.hdCertPath.Value))
            {
                flag = true;
            }
            if (selectedValue)
            {
                if (string.IsNullOrEmpty(text))
                {
                    this.ShowMsg("支付宝APPID不能为空", false);
                    return;
                }
                if (string.IsNullOrEmpty(text2))
                {
                    this.ShowMsg("支付宝开发者公钥不能为空", false);
                    return;
                }
            }
            if (selectedValue2)
            {
                if (string.IsNullOrEmpty(text3))
                {
                    this.ShowMsg("微信AppId不能为空", false);
                    return;
                }
                if (string.IsNullOrEmpty(text5))
                {
                    this.ShowMsg("微信API密钥不能为空", false);
                    return;
                }
                if (string.IsNullOrEmpty(text4))
                {
                    this.ShowMsg("微信商户号不能为空", false);
                    return;
                }
                if (flag && this.fuWXCertPath.PostedFile.ContentLength == 0)
                {
                    this.ShowMsg("请上传微信API证书", false);
                    return;
                }
            }
            SiteSettings masterSettings = SettingsManager.GetMasterSettings();

            masterSettings.EnableHiPOSWX  = selectedValue2;
            masterSettings.EnableHiPOSZFB = selectedValue;
            if (masterSettings.EnableHiPOSWX)
            {
                this.ulWX.Style.Add("display", "block");
                masterSettings.HiPOSWXAppId  = text3;
                masterSettings.HiPOSWXAPIKey = text5;
                masterSettings.HiPOSWXMchId  = text4;
                if (this.fuWXCertPath.PostedFile.ContentLength > 0)
                {
                    string text6 = Globals.PhysicalPath("\\Storage\\master\\HiPOS\\");
                    if (!Globals.PathExist(text6, false))
                    {
                        Globals.CreatePath(text6);
                    }
                    if (Globals.ValidateCertFile(this.fuWXCertPath.PostedFile.FileName))
                    {
                        string text7 = text6 + this.fuWXCertPath.FileName;
                        this.fuWXCertPath.PostedFile.SaveAs(text7);
                        masterSettings.HiPOSWXCertPath = text7.Replace("\\", "/").Replace("//", "/").Replace("/", "\\");
                        goto IL_0340;
                    }
                    this.ShowMsg("非法的证书文件", false);
                    return;
                }
                if (!string.IsNullOrEmpty(this.hdCertPath.Value) && string.IsNullOrEmpty(masterSettings.HiPOSWXCertPath))
                {
                    string text9 = masterSettings.HiPOSWXCertPath = this.hdCertPath.Value.Replace("删除重传", string.Empty).Trim();
                }
            }
            else
            {
                masterSettings.HiPOSWXAppId    = string.Empty;
                masterSettings.HiPOSWXCertPath = string.Empty;
                masterSettings.HiPOSWXMchId    = string.Empty;
                masterSettings.HiPOSWXAPIKey   = string.Empty;
            }
            goto IL_0340;
IL_0340:
            if (masterSettings.EnableHiPOSZFB)
            {
                this.ulZFB.Style.Add("display", "block");
                masterSettings.HiPOSZFBKey = text2;
                masterSettings.HiPOSZFBPID = text;
            }
            else
            {
                masterSettings.HiPOSZFBKey = string.Empty;
                masterSettings.HiPOSZFBPID = string.Empty;
            }
            SettingsManager.Save(masterSettings);
            string wxPayCert = string.Empty;

            if (File.Exists(masterSettings.HiPOSWXCertPath))
            {
                FileStream fileStream = File.OpenRead(masterSettings.HiPOSWXCertPath);
                byte[]     array      = new byte[fileStream.Length];
                fileStream.Read(array, 0, (int)fileStream.Length);
                fileStream.Close();
                wxPayCert = Globals.UrlEncode(Convert.ToBase64String(array));
            }
            HiPOSHelper    hiPOSHelper    = new HiPOSHelper();
            string         filename       = base.Server.MapPath("~/config/rsa_private_key.pem");
            PaymentsResult paymentsResult = hiPOSHelper.SetPayments(masterSettings.HiPOSAppId, masterSettings.HiPOSMerchantId, masterSettings.HiPOSZFBPID, masterSettings.HiPOSWXAppId, masterSettings.HiPOSWXMchId, masterSettings.HiPOSWXAPIKey, wxPayCert, filename);

            if (paymentsResult.error == null)
            {
                this.ShowMsg("提交商户支付方式成功", true, "SetHiPOS.aspx");
            }
            else
            {
                this.ShowMsg(paymentsResult.error.message, false);
            }
        }
Exemple #40
0
 public override void Load()
 {
     base.Load();
     _value = SettingsManager.Load <WeatherSettings>().ApiKey;
 }
Exemple #41
0
 public CustomNamingPeople(SettingsManager settingsManager)
 {
     SettingsManager = settingsManager;
 }
Exemple #42
0
        private void BindData(string title)
        {
            DbQueryResult members = MemberHelper.GetMembers(new MemberQuery
            {
                Username   = title,
                PageIndex  = this.pager.PageIndex,
                PageSize   = this.pager.PageSize,
                Stutas     = new UserStatus?(UserStatus.Normal),
                EndTime    = new System.DateTime?(System.DateTime.Now),
                StartTime  = new System.DateTime?(System.DateTime.Now.AddDays((double)(-(double)SettingsManager.GetMasterSettings(false).ActiveDay))),
                CellPhone  = (base.Request.QueryString["phone"] != null) ? base.Request.QueryString["phone"] : "",
                ClientType = (base.Request.QueryString["clientType"] != null) ? base.Request.QueryString["clientType"] : ""
            }, false);
            int totalRecords = members.TotalRecords;

            if (totalRecords > 0)
            {
                this.rptList.DataSource = members.Data;
                this.rptList.DataBind();
                this.pager.TotalRecords = (this.pager.TotalRecords = totalRecords);
                if (this.pager.TotalRecords <= this.pager.PageSize)
                {
                    this.pager.Visible = false;
                    return;
                }
            }
            else
            {
                this.divEmpty.Visible = true;
            }
        }
 private void CloseClick(object sender, RoutedEventArgs e)
 {
     Cursor = Cursors.Wait;
     SettingsManager.SaveSettings();
     Close();
 }
 public static string AddProductNew(ProductInfo product, Dictionary<string, SKUItem> skus, Dictionary<int, IList<int>> attrs, IList<int> tagsId,string wid)
 {
     string str = string.Empty;
     if (product == null)
     {
         return "未知错误";
     }
     Globals.EntityCoding(product, true);
     int decimalLength = SettingsManager.GetMasterSettings(true,wid).DecimalLength;
     if (product.MarketPrice.HasValue)
     {
         product.MarketPrice = new decimal?(Math.Round(product.MarketPrice.Value, decimalLength));
     }
     ProductActionStatus unknowError = ProductActionStatus.UnknowError;
     using (DbConnection connection = DatabaseFactory.CreateDatabase().CreateConnection())
     {
         connection.Open();
         DbTransaction dbTran = connection.BeginTransaction();
         try
         {
             ProductDao dao = new ProductDao();
             int productId = dao.AddProduct(product, dbTran);
             if (productId == 0)
             {
                 dbTran.Rollback();
                 return "货号重复";
             }
             str = productId.ToString();
             product.ProductId = productId;
             if (((skus != null) && (skus.Count > 0)) && !dao.AddProductSKUs(productId, skus, dbTran,wid))
             {
                 dbTran.Rollback();
                 return "添加SUK出错";
             }
             if (((attrs != null) && (attrs.Count > 0)) && !dao.AddProductAttributes(productId, attrs, dbTran))
             {
                 dbTran.Rollback();
                 return "添加商品属性出错";
             }
             if (((tagsId != null) && (tagsId.Count > 0)) && !new TagDao().AddProductTags(productId, tagsId, dbTran))
             {
                 dbTran.Rollback();
                 return "添加商品标签出错";
             }
             dbTran.Commit();
             unknowError = ProductActionStatus.Success;
         }
         catch (Exception)
         {
             dbTran.Rollback();
         }
         finally
         {
             connection.Close();
         }
     }
     if (unknowError == ProductActionStatus.Success)
     {
         EventLogs.WriteOperationLog(Privilege.AddProducts, string.Format(CultureInfo.InvariantCulture, "上架了一个新商品:”{0}”", new object[] { product.ProductName }));
     }
     return str;
 }
 public static List <ThumbnailItem> SaveThumbnails(UserPhotoManager userPhotoManager, SettingsManager settingsManager, int x, int y, int width, int height, Guid userId)
 {
     return(SaveThumbnails(userPhotoManager, settingsManager, new UserPhotoThumbnailSettings(x, y, width, height), userId));
 }
Exemple #46
0
 protected WXConfig() : base("m06", "wxp01")
 {
     this.siteSettings = SettingsManager.GetMasterSettings(false);
 }
Exemple #47
0
        protected override void AttachChildControls()
        {
            this.rptCategories                = (VshopTemplatedRepeater)this.FindControl("rptCategories");
            this.rptProducts                  = (VshopTemplatedRepeater)this.FindControl("rptProducts");
            this.rptProducts.ItemDataBound   += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.rptProducts_ItemDataBound);
            this.rptCategories.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.rptCategories_ItemDataBound);
            this.img            = (System.Web.UI.HtmlControls.HtmlImage) this.FindControl("imgDefaultBg");
            this.pager          = (Pager)this.FindControl("pager");
            this.litstorename   = (System.Web.UI.WebControls.Literal) this.FindControl("litstorename");
            this.litdescription = (System.Web.UI.WebControls.Literal) this.FindControl("litdescription");
            this.litattention   = (System.Web.UI.WebControls.Literal) this.FindControl("litattention");
            this.imglogo        = (HiImage)this.FindControl("imglogo");
            this.litImgae       = (System.Web.UI.WebControls.Literal) this.FindControl("litImgae");
            this.litItemParams  = (System.Web.UI.WebControls.Literal) this.FindControl("litItemParams");
            if (string.IsNullOrEmpty(this.Page.Request.QueryString["ReferralId"]))
            {
                System.Web.HttpCookie httpCookie = System.Web.HttpContext.Current.Request.Cookies["Vshop-ReferralId"];
                if (httpCookie != null && !string.IsNullOrEmpty(httpCookie.Value))
                {
                    this.Page.Response.Redirect("Default.aspx?ReferralId=" + httpCookie.Value);
                }
            }
            if (this.rptCategories.Visible)
            {
                DataTable brandCategories = CategoryBrowser.GetBrandCategories();
                this.itemcount = brandCategories.Rows.Count;
                if (brandCategories.Rows.Count > 0)
                {
                    this.rptCategories.DataSource = brandCategories;
                    this.rptCategories.DataBind();
                }
            }
            this.Page.Session["stylestatus"] = "3";
            SiteSettings masterSettings = SettingsManager.GetMasterSettings(false);

            PageTitle.AddSiteNameTitle(masterSettings.SiteName);
            this.litstorename.Text   = masterSettings.SiteName;
            this.litdescription.Text = masterSettings.ShopIntroduction;
            if (!string.IsNullOrEmpty(masterSettings.DistributorLogoPic))
            {
                this.imglogo.ImageUrl = masterSettings.DistributorLogoPic.Split(new char[]
                {
                    '|'
                })[0];
            }
            if (this.referralId <= 0)
            {
                System.Web.HttpCookie httpCookie2 = System.Web.HttpContext.Current.Request.Cookies["Vshop-ReferralId"];
                if (httpCookie2 != null && !string.IsNullOrEmpty(httpCookie2.Value))
                {
                    this.referralId = int.Parse(httpCookie2.Value);
                    this.Page.Response.Redirect("Default.aspx?ReferralId=" + this.referralId.ToString(), true);
                }
            }
            else
            {
                System.Web.HttpCookie httpCookie2 = System.Web.HttpContext.Current.Request.Cookies["Vshop-ReferralId"];
                if (httpCookie2 != null && !string.IsNullOrEmpty(httpCookie2.Value) && this.referralId.ToString() != httpCookie2.Value)
                {
                    this.Page.Response.Redirect("Default.aspx?ReferralId=" + this.referralId.ToString(), true);
                }
            }
            System.Collections.Generic.IList <BannerInfo> list = new System.Collections.Generic.List <BannerInfo>();
            list = VshopBrowser.GetAllBanners();
            foreach (BannerInfo current in list)
            {
                TplCfgInfo tplCfgInfo = new NavigateInfo();
                tplCfgInfo.LocationType = current.LocationType;
                tplCfgInfo.Url          = current.Url;
                string text = "javascript:";
                if (!string.IsNullOrEmpty(current.Url))
                {
                    text = tplCfgInfo.LoctionUrl;
                }
                System.Web.UI.WebControls.Literal expr_3E2 = this.litImgae;
                string text2 = expr_3E2.Text;
                expr_3E2.Text = string.Concat(new string[]
                {
                    text2,
                    "<a  id=\"ahref\" href='",
                    text,
                    "'><img src=\"",
                    current.ImageUrl,
                    "\" title=\"",
                    current.ShortDesc,
                    "\" alt=\"",
                    current.ShortDesc,
                    "\" /></a>"
                });
            }
            if (list.Count == 0)
            {
                this.litImgae.Text = "<a id=\"ahref\"  href='javascript:'><img src=\"/Utility/pics/default.jpg\" title=\"\"  /></a>";
            }
            DistributorsInfo distributorsInfo = new DistributorsInfo();

            distributorsInfo = DistributorsBrower.GetUserIdDistributors(this.referralId);
            if (distributorsInfo != null && distributorsInfo.UserId > 0)
            {
                PageTitle.AddSiteNameTitle(distributorsInfo.StoreName);
                this.litdescription.Text = distributorsInfo.StoreDescription;
                this.litstorename.Text   = distributorsInfo.StoreName;
                if (!string.IsNullOrEmpty(distributorsInfo.Logo))
                {
                    this.imglogo.ImageUrl = distributorsInfo.Logo;
                }
                else if (!string.IsNullOrEmpty(masterSettings.DistributorLogoPic))
                {
                    this.imglogo.ImageUrl = masterSettings.DistributorLogoPic.Split(new char[]
                    {
                        '|'
                    })[0];
                }
                if (!string.IsNullOrEmpty(distributorsInfo.BackImage))
                {
                    this.litImgae.Text = "";
                    string[] array = distributorsInfo.BackImage.Split(new char[]
                    {
                        '|'
                    });
                    for (int i = 0; i < array.Length; i++)
                    {
                        string text3 = array[i];
                        if (!string.IsNullOrEmpty(text3))
                        {
                            System.Web.UI.WebControls.Literal expr_5D7 = this.litImgae;
                            expr_5D7.Text = expr_5D7.Text + "<a ><img src=\"" + text3 + "\" title=\"\"  /></a>";
                        }
                    }
                }
            }
            this.dtpromotion = ProductBrowser.GetAllFull();
            if (this.rptProducts != null)
            {
                ProductQuery productQuery = new ProductQuery();
                productQuery.PageSize  = this.pager.PageSize;
                productQuery.PageIndex = this.pager.PageIndex;
                productQuery.SortBy    = "DisplaySequence";
                productQuery.SortOrder = SortAction.Desc;
                DbQueryResult homeProduct = ProductBrowser.GetHomeProduct(MemberProcessor.GetCurrentMember(), productQuery);
                this.rptProducts.DataSource = homeProduct.Data;
                this.rptProducts.DataBind();
                this.pager.TotalRecords = homeProduct.TotalRecords;
                if (this.pager.TotalRecords <= this.pager.PageSize)
                {
                    this.pager.Visible = false;
                }
            }
            if (this.img != null)
            {
                this.img.Src = new VTemplateHelper().GetDefaultBg();
            }
            if (!string.IsNullOrEmpty(masterSettings.GuidePageSet))
            {
                this.litattention.Text = masterSettings.GuidePageSet;
            }
            string userAgent = this.Page.Request.UserAgent;

            if (userAgent.ToLower().Contains("alipay") && !string.IsNullOrEmpty(masterSettings.AliPayFuwuGuidePageSet))
            {
                if (!string.IsNullOrEmpty(masterSettings.GuidePageSet))
                {
                    this.litattention.Text = masterSettings.AliPayFuwuGuidePageSet;
                }
            }
            string text4 = "";

            if (!string.IsNullOrEmpty(masterSettings.ShopHomePic))
            {
                text4 = Globals.HostPath(System.Web.HttpContext.Current.Request.Url) + masterSettings.ShopHomePic;
            }
            string text5 = "";
            string text6 = (distributorsInfo == null) ? masterSettings.SiteName : distributorsInfo.StoreName;

            if (!string.IsNullOrEmpty(masterSettings.DistributorBackgroundPic))
            {
                text5 = Globals.HostPath(System.Web.HttpContext.Current.Request.Url) + masterSettings.DistributorBackgroundPic.Split(new char[]
                {
                    '|'
                })[0];
            }
            this.litItemParams.Text = string.Concat(new string[]
            {
                text4,
                "|",
                masterSettings.ShopHomeName,
                "|",
                masterSettings.ShopHomeDescription,
                "$"
            });
            this.litItemParams.Text = string.Concat(new object[]
            {
                this.litItemParams.Text,
                text5,
                "|好店推荐之",
                text6,
                "商城|一个购物赚钱的好去处|",
                System.Web.HttpContext.Current.Request.Url
            });
        }
Exemple #48
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // Parse the command line arguments and store them in the current configuration
            CommandLineManager.Parse();

            // If we have restart our application... wait until it has finished
            if (CommandLineManager.Current.RestartPid != 0)
            {
                var processList = Process.GetProcesses();

                var process = processList.FirstOrDefault(x => x.Id == CommandLineManager.Current.RestartPid);

                process?.WaitForExit();
            }

            // Detect the current configuration
            ConfigurationManager.Detect();

            // Get assembly informations
            AssemblyManager.Load();

            // Load application settings (profiles/Profiles/clients are loaded when needed)
            try
            {
                // Update integrated settings %LocalAppData%\NETworkManager\NETworkManager_GUID (custom settings path)
                if (Settings.Default.UpgradeRequired)
                {
                    Settings.Default.Upgrade();
                    Settings.Default.UpgradeRequired = false;
                }

                SettingsManager.Load();

                // Update settings (Default --> %AppData%\NETworkManager\Settings)
                if (AssemblyManager.Current.Version > new Version(SettingsManager.Current.SettingsVersion))
                {
                    SettingsManager.Update(AssemblyManager.Current.Version, new Version(SettingsManager.Current.SettingsVersion));
                }
            }
            catch (InvalidOperationException)
            {
                SettingsManager.InitDefault();
                ConfigurationManager.Current.ShowSettingsResetNoteOnStartup = true;
            }

            // Load localization (requires settings to be loaded first)
            LocalizationManager.Load();

            NETworkManager.Resources.Localization.Strings.Culture = LocalizationManager.Culture;

            if (CommandLineManager.Current.Help)
            {
                StartupUri = new Uri("/Views/CommandLineHelpWindow.xaml", UriKind.Relative);
                return;
            }

            // Create mutex
            _mutex = new Mutex(true, "{" + GUID + "}");
            var mutexIsAcquired = _mutex.WaitOne(TimeSpan.Zero, true);

            // Release mutex
            if (mutexIsAcquired)
            {
                _mutex.ReleaseMutex();
            }

            if (SettingsManager.Current.Window_MultipleInstances || mutexIsAcquired)
            {
                if (SettingsManager.Current.General_BackgroundJobInterval != 0)
                {
                    _dispatcherTimer = new DispatcherTimer
                    {
                        Interval = TimeSpan.FromMinutes(SettingsManager.Current.General_BackgroundJobInterval)
                    };

                    _dispatcherTimer.Tick += DispatcherTimer_Tick;

                    _dispatcherTimer.Start();
                }

                StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
            }
            else
            {
                // Bring the already running application into the foreground
                SingleInstance.PostMessage((IntPtr)SingleInstance.HWND_BROADCAST, SingleInstance.WM_SHOWME, IntPtr.Zero, IntPtr.Zero);

                _singleInstanceClose = true;
                Shutdown();
            }
        }
Exemple #49
0
 private SiteSettings GetSiteSetting()
 {
     return(SettingsManager.GetMasterSettings(false));
 }
Exemple #50
0
        private void PictureBox2_Click(object sender, EventArgs e)
        {
            foreach (TextBox tb in this.Controls.OfType <TextBox>())
            {
                if (string.IsNullOrEmpty(tb.Text.Trim()))
                {
                    Notification n = new Notification(Classes.Enum.AlertType.WARNING, "Valores por preencher.", 1);
                    n.ShowDialog(); return;
                }
            }

            Double res;
            bool   isDouble = Double.TryParse(textBox3.Text, out res);

            if (!isDouble)
            {
                Notification n = new Notification(Classes.Enum.AlertType.ERROR, "O preço não é um número.", 1);
                n.ShowDialog();
                return;
            }

            int  stockdef = -1;
            int  stock;
            bool valid = Int32.TryParse(textBox1.Text, out stock);

            if (comboBox1.SelectedIndex > -1)
            {
                if (checkBox1.Checked == false)
                {
                    if (string.IsNullOrEmpty(textBox1.Text.Trim()))
                    {
                        if (!valid)
                        {
                            Notification not = new Notification(Classes.Enum.AlertType.ERROR, "A Quantidade não é um número.", 1);
                            not.ShowDialog();
                            return;
                        }
                        Notification n = new Notification(Classes.Enum.AlertType.ERROR, "A Quantidade não é um número.", 1);
                        n.ShowDialog();
                        return;
                    }
                }
                {
                    String ident = Databases.getIdentifier(Classes.Enum.IdentifierType.PRODUCT);

                    if (pictureBox1.Image != null)
                    {
                        Imaging.saveImage(new Bitmap(pictureBox1.Image), 100, 78, 100, SettingsManager.getDataPath() + @"\Images\Products\" + ident + ".jpg");
                    }

                    Product p = new Product();
                    p.NAME           = textBox2.Text;
                    p.PRICE          = res;
                    p.DESCRIPTION    = textBox5.Text;
                    p.CATEGORY       = comboBox1.Text;
                    p.unlimitedSTOCK = checkBox1.Checked;

                    if (valid == true)
                    {
                        p.STOCK = stock;
                    }
                    else
                    {
                        p.STOCK = stockdef;
                    }

                    p.useOverlay = checkBox2.Checked;
                    p.INFO       = textBox4.Text;
                    p.IDENTIFIER = ident;
                    p.DATEADDED  = Time.get();

                    ProductManager.saveProduct(p);
                    this.Close();
                }
            }
            else
            {
                Notification n = new Notification(Classes.Enum.AlertType.ERROR, "Nenhuma categoria selecionada.", 1);
                n.ShowDialog();
            }
        }
Exemple #51
0
 public SettingsViewModel(IEventAggregator eventAggregator, SettingsManager settings)
 {
     this.eventAggregator = eventAggregator;
     this.Settings        = settings;
 }
 public override void Load()
 {
     _value = SettingsManager.Load <SkinBaseSettings>().DateFormat;
 }
Exemple #53
0
        private void settingsManagerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsManager settingsManager = new SettingsManager();

            settingsManager.ShowDialog(this);
        }
Exemple #54
0
 public override void Load()
 {
     Yes = SettingsManager.Load <SlimTvClientSettings>().AutoStartTV;
 }
Exemple #55
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            string     text       = default(string);
            ConfigData configData = default(ConfigData);

            if (this.siteSettings.IsDemoSite)
            {
                this.ShowMsg("演示站点,不允许编辑支付方式", true);
            }
            else if (this.ValidateValues(out text, out configData))
            {
                PaymentModeInfo paymentMode = new PaymentModeInfo
                {
                    ModeId          = this.modeId,
                    Name            = this.txtName.Text.Trim(),
                    Description     = this.fcContent.Text.Replace("\r\n", "").Replace("\r", "").Replace("\n", ""),
                    Gateway         = text,
                    IsUseInpour     = this.radiIsUseInpour.SelectedValue,
                    ApplicationType = PayApplicationType.payOnPC,
                    Settings        = HiCryptographer.Encrypt(configData.SettingsXml)
                };
                if (SalesHelper.UpdatePaymentMode(paymentMode))
                {
                    if (text == "hishop.plugins.payment.wxqrcode.wxqrcoderequest")
                    {
                        PaymentModeInfo paymentMode2 = SalesHelper.GetPaymentMode(this.modeId);
                        if (paymentMode2 != null)
                        {
                            ConfigData configData2   = new ConfigData(HiCryptographer.Decrypt(paymentMode2.Settings));
                            string     settingsXml   = configData2.SettingsXml;
                            string     xmlNodeValue  = Globals.GetXmlNodeValue(settingsXml, "AppId");
                            string     xmlNodeValue2 = Globals.GetXmlNodeValue(settingsXml, "MCHID");
                            string     xmlNodeValue3 = Globals.GetXmlNodeValue(settingsXml, "AppSecret");
                            string     xmlNodeValue4 = Globals.GetXmlNodeValue(settingsXml, "Sub_AppId");
                            string     xmlNodeValue5 = Globals.GetXmlNodeValue(settingsXml, "Sub_mch_Id");
                            string     xmlNodeValue6 = Globals.GetXmlNodeValue(settingsXml, "CertPath");
                            string     xmlNodeValue7 = Globals.GetXmlNodeValue(settingsXml, "MCHID");
                            if (string.IsNullOrEmpty(xmlNodeValue4) && string.IsNullOrEmpty(xmlNodeValue5))
                            {
                                this.siteSettings.WeixinAppId     = xmlNodeValue;
                                this.siteSettings.WeixinPartnerID = xmlNodeValue2;
                                this.siteSettings.Main_AppId      = "";
                                this.siteSettings.Main_Mch_ID     = "";
                            }
                            else
                            {
                                this.siteSettings.WeixinAppId     = xmlNodeValue4;
                                this.siteSettings.WeixinPartnerID = xmlNodeValue5;
                                this.siteSettings.Main_Mch_ID     = xmlNodeValue2;
                                this.siteSettings.Main_AppId      = xmlNodeValue;
                            }
                            this.siteSettings.WeixinPartnerKey   = xmlNodeValue3;
                            this.siteSettings.WeixinCertPath     = xmlNodeValue6;
                            this.siteSettings.WeixinCertPassword = xmlNodeValue7;
                            SettingsManager.Save(this.siteSettings);
                        }
                    }
                    base.Response.Redirect(Globals.GetAdminAbsolutePath("sales/PaymentTypes.aspx"));
                }
                else
                {
                    this.ShowMsg("未知错误", false);
                }
            }
        }
Exemple #56
0
 /// <summary>
 /// Saves the settings to a given file.
 /// </summary>
 /// <param name="file_path">The string containing the path to the file that
 /// settings should be written to.</param>
 /// <returns>Returns true if writing to the file was successful.</returns>
 void Save(string file_path = SettingsManager.DEFAULT_PATH)
 {
     SettingsManager.SaveSettings(file_path);
 }
Exemple #57
0
 public AdvencedMenu(SettingsManager settingsManager)
 {
     this.settingsManager = settingsManager;
 }
        public static List <ThumbnailItem> SaveThumbnails(UserPhotoManager userPhotoManager, SettingsManager settingsManager, UserPhotoThumbnailSettings thumbnailSettings, Guid userId)
        {
            if (thumbnailSettings.Size.IsEmpty)
            {
                return(null);
            }

            var thumbnailsData = new ThumbnailsData(userId, userPhotoManager);

            var resultBitmaps = new List <ThumbnailItem>();

            var img = thumbnailsData.MainImgBitmap();

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

            foreach (var thumbnail in thumbnailsData.ThumbnailList())
            {
                thumbnail.Bitmap = GetBitmap(img, thumbnail.Size, thumbnailSettings);

                resultBitmaps.Add(thumbnail);
            }

            thumbnailsData.Save(resultBitmaps);

            settingsManager.SaveForUser(thumbnailSettings, userId);

            return(thumbnailsData.ThumbnailList());
        }
Exemple #59
0
 public static void ApplySavedServerSettings(this ExceptionlessConfiguration config)
 {
     SettingsManager.ApplySavedServerSettings(config);
 }
Exemple #60
0
        protected void Page_Load(object sender, EventArgs e)
        {
            wid = GetCurWebId();
            if (string.IsNullOrEmpty(wid))
            {
                return;
            }

            string str2;
            string retMsg = string.Empty;

            if (base.IsPostBack)
            {
                goto Label_0D14;
            }
            if (!(this.type == "getarticleinfo"))
            {
                if (!(this.type == "postdata"))
                {
                    if (this.sendID > 0)
                    {
                        this.hdfSendID.Value = this.sendID.ToString();
                        SendAllInfo sendAllInfo = WeiXinHelper.GetSendAllInfo(this.sendID);
                        if (sendAllInfo != null)
                        {
                            MessageType messageType = sendAllInfo.MessageType;
                            this.hdfMessageType.Value = ((int)sendAllInfo.MessageType).ToString();
                            int articleID = sendAllInfo.ArticleID;
                            this.hdfArticleID.Value = articleID.ToString();
                            this.txtTitle.Text      = sendAllInfo.Title;
                            switch (messageType)
                            {
                            case MessageType.Text:
                                this.fkContent.Text = sendAllInfo.Content;
                                break;

                            case MessageType.News:
                                if (articleID <= 0)
                                {
                                    this.hdfIsOldArticle.Value = "1";
                                    NewsReplyInfo reply = ReplyHelper.GetReply(this.sendID) as NewsReplyInfo;
                                    if (((reply != null) && (reply.NewsMsg != null)) && (reply.NewsMsg.Count != 0))
                                    {
                                        this.htmlInfo = "<div class=\"mate-inner\"><h3 id=\"singelTitle\">" + reply.NewsMsg[0].Title + "</h3><span>" + reply.LastEditDate.ToString("M月d日") + "</span><div class=\"mate-img\"><img id=\"img1\" src=\"" + reply.NewsMsg[0].PicUrl + "\" class=\"img-responsive\"></div><div class=\"mate-info\" id=\"Lbmsgdesc\">" + reply.NewsMsg[0].Description + "</div><div class=\"red-all clearfix\"><strong class=\"fl\">查看全文</strong><em class=\"fr\">&gt;</em></div></div>";
                                    }
                                }
                                break;

                            case MessageType.List:
                                if (articleID <= 0)
                                {
                                    this.hdfIsOldArticle.Value = "1";
                                    NewsReplyInfo info6 = ReplyHelper.GetReply(this.sendID) as NewsReplyInfo;
                                    if (info6 != null)
                                    {
                                        StringBuilder builder2 = new StringBuilder();
                                        if ((info6.NewsMsg != null) && (info6.NewsMsg.Count > 0))
                                        {
                                            int num15 = 0;
                                            foreach (NewsMsgInfo info7 in info6.NewsMsg)
                                            {
                                                num15++;
                                                if (num15 == 1)
                                                {
                                                    builder2.Append("<div class=\"mate-inner top\">                 <div class=\"mate-img\" >                     <img id=\"img1\" src=\"" + info7.PicUrl + "\" class=\"img-responsive\">                     <div class=\"title\" id=\"title1\">" + info7.Title + "</div>                 </div>             </div>");
                                                }
                                                else
                                                {
                                                    builder2.Append("             <div class=\"mate-inner\">                 <div class=\"child-mate\">                     <div class=\"child-mate-title clearfix\">                         <div class=\"title\">" + info7.Title + "</div>                         <div class=\"img\">                             <img src=\"" + info7.PicUrl + "\" class=\"img-responsive\">                         </div>                     </div>                 </div>             </div>");
                                                }
                                            }
                                            this.htmlInfo = builder2.ToString();
                                        }
                                    }
                                }
                                break;
                            }
                        }
                        else
                        {
                            base.Response.Redirect("sendalllist.aspx");
                            base.Response.End();
                        }
                    }
                    else if (this.LocalArticleID > 0)
                    {
                        ArticleInfo articleInfo = ArticleHelper.GetArticleInfo(this.LocalArticleID);
                        if (articleInfo != null)
                        {
                            this.hdfArticleID.Value   = this.LocalArticleID.ToString();
                            this.hdfMessageType.Value = ((int)articleInfo.ArticleType).ToString();
                        }
                    }
                    if (string.IsNullOrEmpty(this.htmlInfo))
                    {
                        this.htmlInfo = "<div class=\"exit-shop-info\">内容区</div>";
                    }
                    this.litInfo.Text = this.htmlInfo;
                    goto Label_0D14;
                }
                base.Response.ContentType = "application/json";
                str2        = "{\"type\":\"1\",\"tips\":\"操作成功\"}";
                this.sendID = Globals.RequestFormNum("sendid");
                int    num2         = Globals.RequestFormNum("sendtype");
                int    msgType      = Globals.RequestFormNum("msgtype");
                int    num4         = Globals.RequestFormNum("articleid");
                string title        = Globals.RequestFormStr("title");
                string content      = Globals.RequestFormStr("content");
                int    isoldarticle = Globals.RequestFormNum("isoldarticle");
                string str5         = this.SavePostData(msgType, num4, title, content, isoldarticle, this.sendID, true);
                if (!string.IsNullOrEmpty(str5))
                {
                    str2 = "{\"type\":\"0\",\"tips\":\"" + str5 + "\"}";
                }
                else
                {
                    MessageType  type           = (MessageType)msgType;
                    string       str6           = string.Empty;
                    SiteSettings masterSettings = SettingsManager.GetMasterSettings(false, wid);
                    string       str7           = JsonConvert.DeserializeObject <Token>(TokenApi.GetToken(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret)).access_token;
                    switch (type)
                    {
                    case MessageType.News:
                    case MessageType.List:
                    {
                        bool        flag  = true;
                        ArticleInfo info3 = ArticleHelper.GetArticleInfo(num4);
                        if (info3.MediaId.Length < 1)
                        {
                            //上传media
                            retMsg = NewsApi.GetMedia_IDByPath(str7, info3.ImageUrl);
                            string jsonValue = NewsApi.GetJsonValue(retMsg, "media_id");
                            if (string.IsNullOrEmpty(jsonValue))
                            {
                                StreamWriter writer = File.AppendText(base.Server.MapPath("error.txt"));
                                writer.WriteLine(str7);
                                writer.WriteLine(info3.ImageUrl + "上传图片失败" + retMsg);
                                writer.WriteLine(DateTime.Now);
                                writer.Flush();
                                writer.Close();
                                flag = false;
                                str2 = "{\"type\":\"2\",\"tips\":\"" + NewsApi.GetErrorCodeMsg(NewsApi.GetJsonValue(retMsg, "errcode")) + "\"}";
                            }
                            else
                            {
                                ArticleHelper.UpdateMedia_Id(0, info3.ArticleId, jsonValue);
                            }
                        }
                        if (type == MessageType.List)
                        {
                            foreach (ArticleItemsInfo info4 in info3.ItemsInfo)
                            {
                                if ((info4.MediaId == null) || (info4.MediaId.Length < 1))
                                {
                                    string msg     = NewsApi.GetMedia_IDByPath(str7, info4.ImageUrl);
                                    string mediaid = NewsApi.GetJsonValue(msg, "media_id");
                                    if (mediaid.Length == 0)
                                    {
                                        this.errcode = NewsApi.GetJsonValue(msg, "errcode");
                                        msg          = "";
                                        flag         = false;
                                        str2         = "{\"type\":\"2\",\"tips\":\"" + NewsApi.GetErrorCodeMsg(this.errcode) + "\"}";
                                        break;
                                    }
                                    ArticleHelper.UpdateMedia_Id(1, info4.Id, mediaid);
                                }
                            }
                        }
                        if (flag)
                        {
                            string articlesJsonStr = this.GetArticlesJsonStr(info3);
                            string str12           = NewsApi.UploadNews(str7, articlesJsonStr);
                            this.sendID = Globals.ToNum(this.SavePostData(msgType, num4, title, content, isoldarticle, this.sendID, false));
                            string str13 = NewsApi.GetJsonValue(str12, "media_id");
                            if (str13.Length > 0)
                            {
                                if (num2 == 1)
                                {
                                    str6 = NewsApi.SendAll(str7, NewsApi.CreateImageNewsJson(str13));
                                    if (!string.IsNullOrWhiteSpace(str6))
                                    {
                                        string str14 = NewsApi.GetJsonValue(str6, "msg_id");
                                        if (!string.IsNullOrEmpty(str14))
                                        {
                                            WeiXinHelper.UpdateMsgId(this.sendID, str14, 0, 0, 0, "");
                                        }
                                        else
                                        {
                                            this.errcode = NewsApi.GetJsonValue(str6, "errcode");
                                            string errorCodeMsg = NewsApi.GetErrorCodeMsg(this.errcode);
                                            WeiXinHelper.UpdateMsgId(this.sendID, str14, 2, 0, 0, errorCodeMsg);
                                            str2 = "{\"type\":\"2\",\"tips\":\"" + errorCodeMsg + "!!\"}";
                                        }
                                    }
                                    else
                                    {
                                        str2 = "{\"type\":\"2\",\"tips\":\"type参数错误\"}";
                                    }
                                }
                                else
                                {
                                    DataTable rencentOpenID  = WeiXinHelper.GetRencentOpenID(100, this.wid);
                                    int       count          = rencentOpenID.Rows.Count;
                                    int       sendcount      = 0;
                                    string    returnjsondata = string.Empty;
                                    for (int i = 0; i < rencentOpenID.Rows.Count; i++)
                                    {
                                        string str17 = NewsApi.KFSend(str7, this.GetKFSendImageJson(rencentOpenID.Rows[i][0].ToString(), info3));
                                        this.errcode = NewsApi.GetJsonValue(str17, "errcode");
                                        if (this.errcode == "0")
                                        {
                                            sendcount++;
                                        }
                                        else
                                        {
                                            returnjsondata = NewsApi.GetErrorCodeMsg(this.errcode);
                                        }
                                    }
                                    int sendstate = (sendcount > 0) ? 1 : 2;
                                    WeiXinHelper.UpdateMsgId(this.sendID, "", sendstate, sendcount, count, returnjsondata);
                                }
                            }
                            else
                            {
                                this.errcode = NewsApi.GetJsonValue(str12, "errcode");
                                str2         = "{\"type\":\"2\",\"tips\":\"" + NewsApi.GetErrorCodeMsg(this.errcode) + "!\"}";
                            }
                        }
                        goto Label_097D;
                    }
                    }
                    this.sendID = Globals.ToNum(this.SavePostData(msgType, num4, title, content, isoldarticle, this.sendID, false));
                    if (num2 == 1)
                    {
                        str6 = NewsApi.SendAll(str7, this.CreateTxtNewsJson(content));
                        if (!string.IsNullOrWhiteSpace(str6))
                        {
                            string msgid = NewsApi.GetJsonValue(str6, "msg_id");
                            if (msgid.Length == 0)
                            {
                                this.errcode = NewsApi.GetJsonValue(str6, "errcode");
                                string str19 = NewsApi.GetErrorCodeMsg(this.errcode);
                                WeiXinHelper.UpdateMsgId(this.sendID, msgid, 2, 0, 0, str19);
                                str2 = "{\"type\":\"2\",\"tips\":\"" + str19 + "\"}";
                            }
                            else
                            {
                                WeiXinHelper.UpdateMsgId(this.sendID, msgid, 0, 0, 0, "");
                            }
                        }
                        else
                        {
                            str2 = "{\"type\":\"2\",\"tips\":\"type参数错误\"}";
                        }
                    }
                    else
                    {
                        DataTable table2     = WeiXinHelper.GetRencentOpenID(100, this.wid);
                        int       totalcount = table2.Rows.Count;
                        int       num11      = 0;
                        string    str20      = string.Empty;
                        for (int j = 0; j < table2.Rows.Count; j++)
                        {
                            string str21 = NewsApi.KFSend(str7, NewsApi.CreateKFTxtNewsJson(table2.Rows[j][0].ToString(), this.String2Json(this.FormatSendContent(content))));
                            this.errcode = NewsApi.GetJsonValue(str21, "errcode");
                            if (this.errcode == "0")
                            {
                                num11++;
                            }
                            else
                            {
                                str20 = NewsApi.GetErrorCodeMsg(this.errcode);
                            }
                        }
                        int num13 = (num11 > 0) ? 1 : 2;
                        WeiXinHelper.UpdateMsgId(this.sendID, "", num13, num11, totalcount, str20);
                        if (num11 == 0)
                        {
                            str2 = "{\"type\":\"0\",\"tips\":\"发送失败\"}";
                        }
                    }
                }
                goto Label_097D;
            }
            base.Response.ContentType = "application/json";
            string s         = "{\"type\":\"0\",\"tips\":\"操作失败\"}";
            int    articleid = Globals.RequestFormNum("articleid");

            if (articleid > 0)
            {
                ArticleInfo info = ArticleHelper.GetArticleInfo(articleid);
                if (info != null)
                {
                    StringBuilder builder = new StringBuilder();
                    switch (info.ArticleType)
                    {
                    case ArticleType.News:
                        s = string.Concat(new object[] { "{\"type\":\"1\",\"articletype\":", (int)info.ArticleType, ",\"title\":\"", this.String2Json(info.Title), "\",\"date\":\"", this.String2Json(info.PubTime.ToString("M月d日")), "\",\"imgurl\":\"", this.String2Json(info.ImageUrl), "\",\"memo\":\"", this.String2Json(info.Memo), "\"}" });
                        goto Label_030E;

                    case ArticleType.List:
                        foreach (ArticleItemsInfo info2 in info.ItemsInfo)
                        {
                            builder.Append("{\"title\":\"" + this.String2Json(info2.Title) + "\",\"imgurl\":\"" + this.String2Json(info2.ImageUrl) + "\"},");
                        }
                        s = string.Concat(new object[] { "{\"type\":\"1\",\"articletype\":", (int)info.ArticleType, ",\"title\":\"", this.String2Json(info.Title), "\",\"date\":\"", this.String2Json(info.PubTime.ToString("M月d日")), "\",\"imgurl\":\"", this.String2Json(info.ImageUrl), "\",\"items\":[", builder.ToString().Trim(new char[] { ',' }), "]}" });
                        goto Label_030E;
                    }
                    s = string.Concat(new object[] { "{\"type\":\"1\",\"articletype\":", (int)info.ArticleType, ",\"title\":\"", this.String2Json(info.Title), "\",\"date\":\"", this.String2Json(info.PubTime.ToString("M月d日")), "\",\"imgurl\":\"", this.String2Json(info.ImageUrl), "\",\"memo\":\"", this.String2Json(info.Content), "\"}" });
                }
            }
Label_030E:
            base.Response.Write(s);
            base.Response.End();
            goto Label_0D14;
Label_097D:
            base.Response.Write(str2);
            base.Response.End();
Label_0D14:
            PageTitle.AddSiteNameTitle("微信群发");
        }