string TestEmail(Settings settings)
    {
        string email = settings.Email;
        string smtpServer = settings.SmtpServer;
        string smtpServerPort = settings.SmtpServerPort.ToString();
        string smtpUserName = settings.SmtpUserName;
        string smtpPassword = settings.SmtpPassword;
        string enableSsl = settings.EnableSsl.ToString();

        var mail = new MailMessage
        {
            From = new MailAddress(email, smtpUserName),
            Subject = string.Format("Test mail from {0}", smtpUserName),
            IsBodyHtml = true
        };
        mail.To.Add(mail.From);
        var body = new StringBuilder();
        body.Append("<div style=\"font: 11px verdana, arial\">");
        body.Append("Success");
        if (HttpContext.Current != null)
        {
            body.Append(
                "<br /><br />_______________________________________________________________________________<br /><br />");
            body.AppendFormat("<strong>IP address:</strong> {0}<br />", Utils.GetClientIP());
            body.AppendFormat("<strong>User-agent:</strong> {0}", HttpContext.Current.Request.UserAgent);
        }

        body.Append("</div>");
        mail.Body = body.ToString();

        return Utils.SendMailMessage(mail, smtpServer, smtpServerPort, smtpUserName, smtpPassword, enableSsl.ToString());
    }
Example #2
1
 public static H3.Cell[] CalcCells2( Sphere[] mirrors, H3.Cell[] cells, Settings settings )
 {
     HashSet<Vector3D> completedCellIds = new HashSet<Vector3D>( cells.Select( c => c.ID ).ToArray() );
     List<H3.Cell> completedCells = new List<H3.Cell>( cells );
     ReflectCellsRecursive2( mirrors, cells, settings, completedCells, completedCellIds );
     return completedCells.ToArray();
 }
Example #3
0
        public MainViewModel(Settings settings)
        {
            _saved = false;
            _queryTextBeforeLoadContextMenu = "";
            _queryText = "";
            _lastQuery = new Query();

            _settings = settings;

            // happlebao todo temp fix for instance code logic
            HttpProxy.Instance.Settings = _settings;
            InternationalizationManager.Instance.Settings = _settings;
            InternationalizationManager.Instance.ChangeLanguage(_settings.Language);
            ThemeManager.Instance.Settings = _settings;

            _queryHistoryStorage = new JsonStrorage<QueryHistory>();
            _userSelectedRecordStorage = new JsonStrorage<UserSelectedRecord>();
            _topMostRecordStorage = new JsonStrorage<TopMostRecord>();
            _queryHistory = _queryHistoryStorage.Load();
            _userSelectedRecord = _userSelectedRecordStorage.Load();
            _topMostRecord = _topMostRecordStorage.Load();

            InitializeResultListBox();
            InitializeContextMenu();
            InitializeKeyCommands();
            RegisterResultsUpdatedEvent();

            SetHotkey(_settings.Hotkey, OnHotkey);
            SetCustomPluginHotkey();
        }
        /// <summary>
        /// Initialises this component
        /// </summary>
        /// <param name="settings">The settings collection.</param>
        public void Initialise(string name, Settings settings)
        {
            FileLogger.Logger.LogInformation("Initialising Monitor: {0}", name);
            if (settings == null || settings.Setting.Count == 0) throw new ApplicationException("No settings provided. This is required to Initialise the component.");
            Name = name;

            // Get the parameters for the TeamCity Connection
            // --------------------------------------------------------------------------------------
            var hostName = settings["Host"] as string;
            if (string.IsNullOrEmpty(hostName)) throw new ApplicationException("Host setting must be specified.");

            var username = settings.Get("User","guest");
            var password = settings.Get("Password","guest");
            var isGuest  = settings.Get("UseGuest",true);

            // Attempt to connect to TeamCity
            // --------------------------------------------------------------------------------------
            try {
                _client = new TeamCityClient(hostName);
                _client.Connect(username, password, isGuest);
            } catch (Exception ex) {
                throw new ApplicationException("Could not connect to TeamCity using the provided credentials.", ex);
            }

            // Build the list of Builds/Projects that we will be monitoring for THIS monitor
            // -----------------------------------------------------------------------------
            _builds = BuildMonitorProjects(settings);
            if (_builds == null || _builds.Count == 0) throw new ApplicationException("No Builds specified to Monitor.");

            IsInitialised = true;
        }
		public Settings(Settings source) {
			projectile = source.projectile;
			
			uniformDirection = source.uniformDirection;
			uniformPosition = source.uniformPosition;
			spins = source.spins;
			offset = source.offset;
			mirrorOffset = source.mirrorOffset;
			pellets = source.pellets;
			spread = source.spread;
			
			minRecoil = source.minRecoil;
			maxRecoil = source.maxRecoil;
			spin = source.spin;
			repeatAngle = source.repeatAngle;
			recoilAbsorb = source.recoilAbsorb;
			
			bursts = source.bursts;
			burstTime = source.burstTime;
			
			fireTimeHold = source.fireTimeHold;
			fireTimeDown = source.fireTimeDown;
			reloadStart = source.reloadStart;
			reloadTick = source.reloadTick;
			reloadRounds = source.reloadRounds;
			
			ammoUse = source.ammoUse;
			maxAmmo = source.maxAmmo;
			maxExtra = source.maxExtra;
		}
 public ConnectionsViewModel(Settings settings)
     : base()
 {
     _settings = settings;
     foreach (Connection connection in _settings.GetConnections())
     {
         ConnectionViewModel model = new ConnectionViewModel(connection);
         this.Add(model);
         model.PropertyChanged += _itemChanged;
     }
     this.CollectionChanged += (s, e) =>
         {
             ConnectionViewModel connection;
             switch (e.Action)
             {
                 case NotifyCollectionChangedAction.Add:
                     connection = (ConnectionViewModel)e.NewItems[0];
                     connection.PropertyChanged += _itemChanged;
                     _settings.AddConnection(connection.Connection);
                     break;
                 case NotifyCollectionChangedAction.Remove:
                     connection = (ConnectionViewModel)e.OldItems[0];
                     connection.PropertyChanged -= _itemChanged;
                     _settings.RemoveConnection(connection.Connection);
                     break;
             }
         };
 }
Example #7
0
			public FieldMapping(Settings settings, string name, string displayName, string description, Type type, Action<dynamic, dynamic> apply)
			{
				if (settings == null)
					throw new ArgumentNullException(nameof(settings));

				if (name.IsEmpty())
					throw new ArgumentNullException(nameof(name));
				
				if (displayName.IsEmpty())
					throw new ArgumentNullException(nameof(displayName));

				if (type == null)
					throw new ArgumentNullException(nameof(type));

				if (apply == null)
					throw new ArgumentNullException(nameof(apply));

				if (description.IsEmpty())
					description = displayName;

				_settings = settings;
				Name = name;
				DisplayName = displayName;
				Description = description;
				Type = type;
				_apply = apply;

				Values = new ObservableCollection<ImportEnumMappingWindow.MappingValue>();
				Number = -1;

				if (Type == typeof(DateTimeOffset))
					Format = "yyyy/MM/dd";
				else if (Type == typeof(TimeSpan))
					Format = "hh\\:mm\\:ss";
			}
Example #8
0
 internal static void Delete(IEnumerable<Container> storages, Settings settings)
 {
     foreach (var storage in storages)
     {
         settings.Endpoint.Delete(storage.Identity);
     }
 }
 public QuadMeshFactory(IHeightfieldGenerator generator, ITerrainColorizer terrainColorizer, IQuadMeshRendererFactory rendererFactory, Settings settings)
 {
     _generator = generator;
     _terrainColorizer = terrainColorizer;
     _rendererFactory = rendererFactory;
     _settings = settings;
 }
        const int WM_USER = 0x0400; //http://msdn.microsoft.com/en-us/library/windows/desktop/ms644931(v=vs.85).aspx

        public async Task UpgradeOrInstall(IAbsoluteDirectoryPath destination, Settings settings,
            params IAbsoluteFilePath[] files) {
            var theShell = GetTheShell(destination, files);
            if (theShell.Exists)
                await Uninstall(destination, settings, files).ConfigureAwait(false);
            await Install(destination, settings, files).ConfigureAwait(false);
        }
Example #11
0
        public void AddMinersToDataGridViews(bool isRefresh = false)
        {
            string strError = string.Empty;

            settings = settingsCall.GetSettings(ref strError);

            if (!string.IsNullOrEmpty(strError))
                UserMessage.ShowMessage(this, UserMessage.MessageType.Error, "An error occurred while trying to read the settings.dat file. Error: " + strError);
            else
            {
                if (isRefresh)
                    dgvMiners.Rows.Clear();

                if (settings.GpuMiners.Count > 0)
                {
                    foreach (var miner in settings.GpuMiners)
                        if (!DoesMinerExist(Miner.GPU, miner.MinerGUID.ToString()))
                            dgvMiners.Rows.Add(miner.MinerGUID.ToString(), "GPU",
                                miner.Name, miner.CommandLine, miner.WorkerName, miner.Active.ToString(), miner.Failover.ToString(), miner.Retries.ToString());
                }

                if (settings.CpuMiners.Count > 0)
                {
                    foreach (var miner in settings.CpuMiners)
                        if (!DoesMinerExist(Miner.CPU, miner.MinerGUID.ToString()))
                            dgvMiners.Rows.Add(miner.MinerGUID.ToString(), "CPU",
                                miner.Name, miner.CommandLine, miner.WorkerName, miner.Active.ToString(), miner.Failover.ToString(), miner.Retries.ToString());
                }
            }
        }
Example #12
0
 public void ShouldTakePasswordFromServerUri()
 {
     var settings = new Settings(new Uri("http://*****:*****@example.com:4242"), "testdb");
     Assert.Equal("user1", settings.Credentials.UserName);
     Assert.Equal("passw0rd", settings.Credentials.Password);
     Assert.Equal("http://example.com:4242/", settings.ServerUri.ToString());
 }
Example #13
0
        private bool vueMode = false; // false = ortho, true = orbite

        #endregion Fields

        #region Constructors

        internal Editor(EditorController _controller)
        {
            InitializeComponent();
            controller = _controller;

            // Ne pas enlever Forms : c'est pour éviter l'ambiguïté.
            KeyDown += controller.KeyPressed;
            KeyUp += controller.KeyUnPressed;
            GamePanel.MouseDown += new Forms.MouseEventHandler(controller.MouseButtonDown);
            GamePanel.MouseUp += new Forms.MouseEventHandler(controller.MouseButtonUp);
            GamePanel.MouseEnter += new EventHandler(GamePanel_MouseEnter);
            GamePanel.MouseLeave -= new EventHandler(GamePanel_MouseExit);
            GamePanel.MouseWheel += new Forms.MouseEventHandler(controller.RouletteSouris);
            GamePanel.MouseMove += new Forms.MouseEventHandler(controller.MouseMove);
            /// Resize on resize only
            Application.Current.MainWindow.SizeChanged += new SizeChangedEventHandler(ResizeGamePanel);

            settings = (new ConfigPanelData()).LoadSettings();
            profiles = (new ConfigPanelData()).LoadProfiles();

            var defaultProfile = profiles.Where(x => settings != null && x.CompareTo(settings.DefaultProfile) == 0);

            if (defaultProfile.Count() > 0)
            {
                selectedProfile = defaultProfile.First();
                controller.ChangeProfile(selectedProfile);
            }
            else
            {
                selectedProfile = profiles[0];
                controller.ChangeProfile(selectedProfile);
            }
        }
Example #14
0
        public SettingForm(IMEStatusMonitor monitor, Settings settings)
        {
            InitializeComponent();

            _settings = settings;
            _monitor = monitor;

            // デザイナでレイアウトするとなぜかぶっ壊されるので自力で配置する
            Control parent = lblImeOff.Parent;
            int left = lblImeOff.Right + 5;
            int width = parent.ClientRectangle.Right - left - 10;
            ImeOffBorderStylePanel.SetBounds(left, lblImeOff.Top - 25, width, 45);
            ImeOnBorderStylePanel.SetBounds(left, lblImeOn.Top - 25, width, 45);
            parent.Controls.Add(ImeOffBorderStylePanel);
            parent.Controls.Add(ImeOnBorderStylePanel);

            ImeOffBorderStylePanel.StyleObject = _settings.ImeOffBorderStyle;
            ImeOnBorderStylePanel.StyleObject = _settings.ImeOnBorderStyle;
            IgnoreList.Text = string.Join("\r\n", _settings.IgnoreList);

            lblProductName.Text = Application.ProductName;
            lblVersion.Text = "Version " +
                System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            lblCopyright.Text =
                ((System.Reflection.AssemblyCopyrightAttribute)
                Attribute.GetCustomAttribute(
                System.Reflection.Assembly.GetExecutingAssembly(),
                typeof(System.Reflection.AssemblyCopyrightAttribute))).Copyright;

            this.FormClosed += SettingForm_FormClosed;
            _monitor.Updated += _monitor_Updated;
        }
 private void CopySettingsValuesToUI(Settings settings)
 {
     txtShortcutKey.Text = Enum.GetName(typeof(Keys), settings.ShortcutKey);
     chkShortcutKeyAlt.Checked = settings.ShortcutKeyUseAlt;
     chkShortcutKeyCtrl.Checked = settings.ShortcutKeyUseCtrl;
     chkShortcutKeyShift.Checked = settings.ShortcutKeyUseShift;
 }
Example #16
0
        bool tray; // булевая переменная для закрития из трея

        #endregion Fields

        #region Constructors

        public SettingsForm()
        {
            InitializeComponent();
            tray = true;
            Lock = new locker();
            s = new Settings();
        }
Example #17
0
 public LayeredWorker(SourceImage sourceImage, Settings settings)
 {
     this.settings = settings;
     CurrentDrawing = GetNewInitializedDrawing(settings);
     CurrentDrawing.SourceImage = sourceImage;
     CurrentErrorLevel = double.MaxValue;
 }
Example #18
0
        public void TestFixtureSetUp()
        {
            SingletonProvider<TestSetup>.Instance.Authenticate();

             _application = SingletonProvider<TestSetup>.Instance.GetApp();
             _settings = _application.Settings;
        }
        public static void LoadSettings()
        {
            Stream Read = null;

            try
            {
                FileInfo FI = new FileInfo(GetConfigFilePath());

                Read = FI.OpenRead();

                BinaryFormatter BF = new BinaryFormatter();

                Settings Tmp = (Settings) BF.Deserialize(Read);
                m_Settings = Tmp;
            }
            catch(Exception)
            {
            }
            finally
            {
                if (Read != null)
                {
                    Read.Close();
                }
            }
        }
Example #20
0
        public Shell()
        {
            this.InitializeComponent();

            this.Loaded += (sender, args) =>
            {
                Current = this;

                this.TogglePaneButton.Focus(FocusState.Programmatic);
            };

            this.ShellSplitView.RegisterPropertyChangedCallback(
                SplitView.DisplayModeProperty,
                (s, a) =>
                {
                    // Ensure that we update the reported size of the TogglePaneButton when the SplitView's
                    // DisplayMode changes.
                    this.CheckTogglePaneButtonSizeChanged();
                });


            SystemNavigationManager.GetForCurrentView().BackRequested += SystemNavigationManager_BackRequested;

            // Check the availability of a physical back button
            hasPhysicalBackButton = ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons");

            // Getting a pointer to the Settings
            settings = Settings.Instance;

            NavMenuList.ItemsSource = menu.MenuItems;

            this.InitializeVisualState();
        }
Example #21
0
        public bool TryBuild()
        {
            // Ensure at least one argument for the path
            if (Args.Count == 0 ||
                Args.First().TrimStart().StartsWith("-"))
            {
                return false;
            }

            var settings = Args.Joined(" ")
                .Split(
                    new[] { " -" },
                    StringSplitOptions.RemoveEmptyEntries);

            RulePath = settings.First().Trim();
            Settings = new Settings();

            var restSettings = settings.Skip(1);
            foreach (var item in restSettings)
            {
                var separatorIndex = item.IndexOf(" ");
                var key = item.Substring(0, separatorIndex).Trim();
                var value = item.Substring(separatorIndex + 1).Trim();
                Settings[key] = value;
            }


            return true;
        }
        /// <summary>
        /// Initializes a new instance of the class RubyCodeGenerator.
        /// </summary>
        /// <param name="settings">The settings.</param>
        public RubyCodeGenerator(Settings settings) : base(settings)
        {
            CodeNamer = new RubyCodeNamer();
            this.packageVersion = Settings.PackageVersion;
            this.packageName = Settings.PackageName;

            if (Settings.CustomSettings.ContainsKey("Name"))
            {
                this.sdkName = Settings.CustomSettings["Name"].ToString();
            }

            if (sdkName == null)
            {
                this.sdkName = Path.GetFileNameWithoutExtension(Settings.Input);
            }

            if (sdkName == null)
            {
                sdkName = "client";
            }

            this.sdkName = RubyCodeNamer.UnderscoreCase(CodeNamer.RubyRemoveInvalidCharacters(this.sdkName));
            this.sdkPath = this.packageName ?? this.sdkName;
            this.modelsPath = Path.Combine(this.sdkPath, "models");

            // AutoRest generated code for Ruby and Azure.Ruby generator will live inside "generated" sub-folder
            settings.OutputDirectory = Path.Combine(settings.OutputDirectory, GeneratedFolderName);
        }
Example #23
0
		internal AsyncEffectRenderer (Settings settings)
		{
			if (settings.ThreadCount < 1)
				settings.ThreadCount = 1;
			
			if (settings.TileWidth < 1)
				throw new ArgumentException ("EffectRenderSettings.TileWidth");
			
			if (settings.TileHeight < 1)
				throw new ArgumentException ("EffectRenderSettings.TileHeight");			
			
			if (settings.UpdateMillis <= 0)
				settings.UpdateMillis = 100;
			
			effect = null;
			source_surface = null;
			dest_surface = null;
			this.settings = settings;
			
			is_rendering = false;
			render_id = 0;
			updated_lock = new object ();
			is_updated = false;
			render_exceptions = new List<Exception> ();	
			
			timer_tick_id = 0;
		}		
Example #24
0
        public MainForm()
        {
            library = Library.Load();
            if (library == null)
            {
                library = new Library();
                library.Save();
            }
            library.Changed += library_LibraryChanged;

            settings = Settings.Load(SettingsPath) ?? new Settings();

            musicPlayer.OpenCompleted += equalizerSettings_ShouldSet;
            musicPlayer.OpenCompleted += musicPlayer_ShouldPlay;
            musicPlayer.DeviceVolume = settings.DeviceVolume;

            equalizerSettings = EqualizerSettings.Load(EqualizerPath);
            if (equalizerSettings == null)
            {
                equalizerSettings = new EqualizerSettings();
                equalizerSettings.Save(EqualizerPath);
            }
            equalizerSettings.ValueChanged += equalizerSettings_ShouldSet;

            SetUpGlobalHotkeys();

            lfmHandler = new LastfmHandler();
            if (settings.ScrobblingEnabled)
                lfmHandler.ResumeSessionAsync();

            InitializeComponent();
            SetControlReferences();
        }
        public void LoadSettingsFileHasCorrectAmountOfItems()
        {
            var settings = new Settings();
            settings.Load(_reader);

            Assert.AreEqual(3, settings.Collection.Count);
        }
Example #26
0
 public XsollaJsonGenerator(string userId, long projectId)
 {
     user = new User ();
     settings = new Settings ();
     user.id = userId;
     settings.id = projectId;
 }
Example #27
0
        public GiveawaysWindow(IExtension sender)
        {
            InitializeComponent();

            ini = new Settings(sender, "Settings.ini", "[Default]");

            UI.CenterSpacer(GiveawayTypeLabel, GiveawayTypeSpacer);
            UI.CenterSpacer(GiveawaySettingsLabel, GiveawaySettingsSpacer, false, true);
            UI.CenterSpacer(GiveawayBansLabel, GiveawayBansSpacer);
            UI.CenterSpacer(GiveawayUsersLabel, GiveawayUsersSpacer);

            Panel panel = new Panel();
            panel.Size = new Size(1, 1);
            panel.Location = new Point(GiveawayTypeSpacer.Location.X + GiveawayTypeSpacer.Size.Width - 1, GiveawayTypeSpacer.Location.Y + 9);
            Controls.Add(panel);
            panel.BringToFront();
            panel = new Panel();
            panel.Size = new Size(1, 1);
            panel.Location = new Point(GiveawayBansSpacer.Location.X + GiveawayBansSpacer.Size.Width - 1, GiveawayBansSpacer.Location.Y + 9);
            Controls.Add(panel);
            panel.BringToFront();
            /*panel.BackColor = Color.Black;
            panel.Size = new Size(Giveaway_AddPresent.Size.Width + Giveaway_RemovePresent.Size.Width, 1);
            panel.Location = new Point(Giveaway_AddPresent.Location.X, Giveaway_AddPresent.Location.Y + 1);
            Controls.Add(panel);
            panel.BringToFront();*/
        }
        public void LoadData(List<DictionaryRecord> items)
        {
            ClearData();
            this.NetworkAvailable = NetworkInterface.GetIsNetworkAvailable();

            Settings settings = new Settings();
            bool trad = settings.TraditionalChineseSetting;

            foreach (DictionaryRecord r in items)
            {
                // determine what Hanzi to show to the user
                string chinese = (!trad || r.Chinese.Simplified.Equals(r.Chinese.Traditional))
                    ? r.Chinese.Simplified                                                     // show only simplified
                    : String.Format("{0} ({1})", r.Chinese.Simplified, r.Chinese.Traditional); // else "simple (trad)"

                this.Items.Add(new ItemViewModel()
                {
                    Record = r,
                    Pinyin = r.Chinese.Pinyin,
                    English = String.Join("; ", r.English),
                    EnglishWithNewlines = String.Join("\n", r.English),
                    Chinese = chinese,
                    Index = r.Index
                });
            }
            this.IsDataLoaded = true;
        }
Example #29
0
        public void Start()
        {
            Settings settings = null;

            var infobase = _manager.Infobases.FirstOrDefault(val => val.IsAutorun);
            if (infobase == null)
            {
                Activity.FlipScreen(Resource.Layout.Infobases);

                using (var tv = Activity.FindViewById<TextView>(Resource.Id.infobasesCaption))
                using (var btn = Activity.FindViewById<Button>(Resource.Id.buttonCustomerCode))
                {
                    tv.Text = D.INFOBASES;
                    btn.Text = D.ENTER_CUSTOMER_CODE;
                    btn.Click += OpenCustomerCodeMenu;
                }

                LoadList();
            }
            else
            {
                settings = new Settings(_prefs, Activity.Resources.Configuration.Locale.Language, infobase);
            }

            if (settings != null)
                _resultCallback(settings);
        }
Example #30
0
 public EnemyRotationHandler(
     EnemyModel model,
     Settings settings)
 {
     _settings = settings;
     _model = model;
 }
        protected override void BeforeRun()
        {
            try
            {
                Console.Clear();
                Encoding.RegisterProvider(CosmosEncodingProvider.Instance);
                Console.InputEncoding   = Encoding.GetEncoding(437);
                Console.OutputEncoding  = Encoding.GetEncoding(437);
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                Console.Write("Booting Aura...\n");
                Console.ForegroundColor = ConsoleColor.White;

                #region Register Filesystem
                Sys.FileSystem.VFS.VFSManager.RegisterVFS(vFS);
                if (ContainsVolumes())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write("[OK]");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write(" ");
                    Console.ForegroundColor = ConsoleColor.DarkMagenta;
                    Console.Write("FileSystem Registration\n");
                    Console.ForegroundColor = ConsoleColor.White;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.Write("[Error]");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write(" ");
                    Console.ForegroundColor = ConsoleColor.DarkMagenta;
                    Console.Write("FileSystem Registration\n");
                    Console.ForegroundColor = ConsoleColor.White;
                }
                #endregion

                setup.InitSetup();

                if (SystemExists)
                {
                    if (!JustInstalled)
                    {
                        Settings.LoadValues();
                        langSelected = Settings.GetValue("language");

                        #region Language

                        Lang.Keyboard.Init();

                        #endregion

                        Info.getComputerName();

                        running = true;
                    }
                }
                else
                {
                    running = true;
                }
            }
            catch (Exception ex)
            {
                running = false;
                Crash.StopKernel(ex);
            }
        }
        /// <summary>
        /// Called when the GUI should be rendered.
        /// </summary>
        public void OnGUI()
        {
            GUI.skin.label.wordWrap = true;
            GUILayout.BeginVertical();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Prebuild With Gradle (Experimental)", EditorStyles.boldLabel);
            settings.prebuildWithGradle = EditorGUILayout.Toggle(settings.prebuildWithGradle);
            GUILayout.EndHorizontal();

            EditorGUI.BeginDisabledGroup(settings.prebuildWithGradle == true);
            GUILayout.BeginHorizontal();
            GUILayout.Label("Use Gradle Daemon", EditorStyles.boldLabel);
            settings.useGradleDaemon = EditorGUILayout.Toggle(settings.useGradleDaemon);
            GUILayout.EndHorizontal();
            GUILayout.Label(
                settings.useGradleDaemon ?
                ("Gradle Daemon will be used to fetch dependencies.  " +
                 "This is faster but can be flakey in some environments.") :
                ("Gradle Daemon will not be used.  This is slow but reliable."));
            EditorGUI.EndDisabledGroup();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Enable Auto-Resolution", EditorStyles.boldLabel);
            settings.enableAutoResolution = EditorGUILayout.Toggle(settings.enableAutoResolution);
            GUILayout.EndHorizontal();

            EditorGUI.BeginDisabledGroup(settings.prebuildWithGradle == true);
            GUILayout.BeginHorizontal();
            GUILayout.Label("Install Android Packages", EditorStyles.boldLabel);
            settings.installAndroidPackages =
                EditorGUILayout.Toggle(settings.installAndroidPackages);
            GUILayout.EndHorizontal();

            if (ConfigurablePackageDir)
            {
                GUILayout.BeginHorizontal();
                string previousPackageDir = settings.packageDir;
                GUILayout.Label("Package Directory", EditorStyles.boldLabel);
                if (GUILayout.Button("Browse"))
                {
                    string path = EditorUtility.OpenFolderPanel("Set Package Directory",
                                                                PackageDir, "");
                    int startOfPath = path.IndexOf(AndroidPluginsDir);
                    settings.packageDir = startOfPath < 0 ? "" :
                                          path.Substring(startOfPath, path.Length - startOfPath);;
                }
                if (!previousPackageDir.Equals(settings.packageDir))
                {
                    settings.packageDir = ValidatePackageDir(settings.packageDir);
                }
                GUILayout.EndHorizontal();
                settings.packageDir = EditorGUILayout.TextField(settings.packageDir);
            }

            GUILayout.BeginHorizontal();
            GUILayout.Label("Explode AARs", EditorStyles.boldLabel);
            settings.explodeAars = EditorGUILayout.Toggle(settings.explodeAars);
            GUILayout.EndHorizontal();
            if (settings.explodeAars)
            {
                GUILayout.Label("AARs will be exploded (unpacked) when ${applicationId} " +
                                "variable replacement is required in an AAR's " +
                                "AndroidManifest.xml or a single target ABI is selected " +
                                "without a compatible build system.");
            }
            else
            {
                GUILayout.Label("AAR explosion will be disabled in exported Gradle builds " +
                                "(Unity 5.5 and above). You will need to set " +
                                "android.defaultConfig.applicationId to your bundle ID in your " +
                                "build.gradle to generate a functional APK.");
            }
            EditorGUI.EndDisabledGroup();

            EditorGUI.BeginDisabledGroup(settings.enableAutoResolution);
            GUILayout.BeginHorizontal();
            GUILayout.Label("Auto-Resolution Disabled Warning", EditorStyles.boldLabel);
            settings.autoResolutionDisabledWarning =
                EditorGUILayout.Toggle(settings.autoResolutionDisabledWarning);
            GUILayout.EndHorizontal();
            EditorGUI.EndDisabledGroup();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Verbose Logging", EditorStyles.boldLabel);
            settings.verboseLogging = EditorGUILayout.Toggle(settings.verboseLogging);
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Use project settings", EditorStyles.boldLabel);
            settings.useProjectSettings = EditorGUILayout.Toggle(settings.useProjectSettings);
            GUILayout.EndHorizontal();

            GUILayout.Space(10);

            if (GUILayout.Button("Reset to Defaults"))
            {
                // Load default settings into the dialog but preserve the state in the user's
                // saved preferences.
                var backupSettings = new Settings();
                RestoreDefaultSettings();
                LoadSettings();
                backupSettings.Save();
            }

            GUILayout.BeginHorizontal();
            bool closeWindow = GUILayout.Button("Cancel");
            bool ok          = GUILayout.Button("OK");

            closeWindow |= ok;
            if (ok)
            {
                settings.Save();
                PlayServicesResolver.OnSettingsChanged();
            }
            if (closeWindow)
            {
                Close();
            }
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();
        }
Example #33
0
        public static PostViewModel CreatePostViewModel(Post post, List <Vote> votes, PermissionSet permission,
                                                        Topic topic, MembershipUser loggedOnUser, Settings settings, List <Favourite> favourites)
        {
            var allowedToVote = loggedOnUser != null && loggedOnUser.Id != post.User.Id;

            if (allowedToVote && settings.EnablePoints)
            {
                // We need to check if points are enabled that they have enough points to vote
                allowedToVote = loggedOnUser.TotalPoints >= settings.PointsAllowedToVoteAmount;
            }

            // Remove votes where no VotedBy has been recorded
            votes.RemoveAll(x => x.VotedByMembershipUser == null);

            var hasVotedUp    = false;
            var hasVotedDown  = false;
            var hasFavourited = false;

            if (loggedOnUser != null && loggedOnUser.Id != post.User.Id)
            {
                hasFavourited = favourites.Any(x => x.Member.Id == loggedOnUser.Id);
                hasVotedUp    = votes.Count(x => x.Amount > 0 && x.VotedByMembershipUser.Id == loggedOnUser.Id) > 0;
                hasVotedDown  = votes.Count(x => x.Amount < 0 && x.VotedByMembershipUser.Id == loggedOnUser.Id) > 0;
            }

            // Check for online status
            var date = DateTime.UtcNow.AddMinutes(-Constants.TimeSpanInMinutesToShowMembers);

            return(new PostViewModel
            {
                Permissions = permission,
                Votes = votes,
                Post = post,
                ParentTopic = topic,
                AllowedToVote = allowedToVote,
                MemberHasFavourited = hasFavourited,
                Favourites = favourites,
                PermaLink = string.Concat(topic.NiceUrl, "?", Constants.PostOrderBy, "=", Constants.AllPosts,
                                          "#comment-", post.Id),
                MemberIsOnline = post.User.LastActivityDate > date,
                HasVotedDown = hasVotedDown,
                HasVotedUp = hasVotedUp,
                IsTrustedUser = post.User.IsTrustedUser
            });
        }
Example #34
0
        public static TopicViewModel CreateTopicViewModel(Topic topic,
                                                          PermissionSet permission,
                                                          List <Post> posts,
                                                          List <Guid> postIds,
                                                          Post starterPost,
                                                          int?pageIndex,
                                                          int?totalCount,
                                                          int?totalPages,
                                                          MembershipUser loggedOnUser,
                                                          Settings settings,
                                                          INotificationService topicNotificationService,
                                                          IPollService pollService,
                                                          Dictionary <Guid, List <Vote> > votes,
                                                          Dictionary <Guid, List <Favourite> > favourites,
                                                          bool getExtendedData = false)
        {
            var userIsAuthenticated = loggedOnUser != null;

            // Check for online status
            var date = DateTime.UtcNow.AddMinutes(-Constants.TimeSpanInMinutesToShowMembers);

            var viewModel = new TopicViewModel
            {
                Permissions       = permission,
                Topic             = topic,
                Views             = topic.Views,
                DisablePosting    = loggedOnUser != null && loggedOnUser.DisablePosting == true,
                PageIndex         = pageIndex,
                TotalCount        = totalCount,
                TotalPages        = totalPages,
                LastPostPermaLink = string.Concat(topic.NiceUrl, "?", Constants.PostOrderBy, "=",
                                                  Constants.AllPosts, "#comment-", topic.LastPost.Id),
                MemberIsOnline = topic.User.LastActivityDate > date
            };

            if (starterPost == null)
            {
                starterPost = posts.FirstOrDefault(x => x.IsTopicStarter);
            }

            // Get votes for all posts
            postIds.Add(starterPost.Id);

            // Map the votes
            // Get Votes start Post
            var startPostVotes = new List <Vote>();

            if (votes.ContainsKey(starterPost.Id))
            {
                startPostVotes = votes[starterPost.Id];
            }

            // Map the favourites
            var startPostFavs = new List <Favourite>();

            if (favourites.ContainsKey(starterPost.Id))
            {
                startPostFavs = favourites[starterPost.Id];
            }

            // Create the starter post viewmodel
            viewModel.StarterPost = CreatePostViewModel(starterPost, startPostVotes, permission, topic, loggedOnUser,
                                                        settings, startPostFavs);

            // Map data from the starter post viewmodel
            viewModel.VotesUp   = votes.Select(x => x.Value.Count(y => y.Amount > 0)).Count(); //startPostVotes.Count(x => x.Amount > 0);
            viewModel.VotesDown = votes.Select(x => x.Value.Count(y => y.Amount < 0)).Count(); //startPostVotes.Count(x => x.Amount < 0);
            viewModel.Answers   = totalCount ?? posts.Count - 1;

            // Create the ALL POSTS view models
            viewModel.Posts =
                CreatePostViewModels(posts, votes, permission, topic, loggedOnUser, settings, favourites);

            // ########### Full topic need everything

            if (getExtendedData)
            {
                // See if the user has subscribed to this topic or not
                var isSubscribed = userIsAuthenticated &&
                                   topicNotificationService.GetTopicNotificationsByUserAndTopic(loggedOnUser, topic).Any();
                viewModel.IsSubscribed = isSubscribed;

                // See if the topic has a poll, and if so see if this user viewing has already voted
                if (topic.Poll != null)
                {
                    // There is a poll and a user
                    // see if the user has voted or not

                    viewModel.Poll = new PollViewModel
                    {
                        Poll = topic.Poll,
                        UserAllowedToVote = permission[ForumConfiguration.Instance.PermissionVoteInPolls].IsTicked
                    };

                    var answers = pollService.GetAllPollAnswersByPoll(topic.Poll);
                    if (answers.Any())
                    {
                        var pollvotes = answers.SelectMany(x => x.PollVotes).ToList();
                        if (userIsAuthenticated)
                        {
                            viewModel.Poll.UserHasAlreadyVoted = pollvotes.Count(x => x.User.Id == loggedOnUser.Id) > 0;
                        }
                        viewModel.Poll.TotalVotesInPoll = pollvotes.Count();
                    }
                }
            }

            return(viewModel);
        }
Example #35
0
        public static EditSettingsViewModel SettingsToSettingsViewModel(Settings currentSettings)
        {
            var settingViewModel = new EditSettingsViewModel
            {
                Id                              = currentSettings.Id,
                ForumName                       = currentSettings.ForumName,
                ForumUrl                        = currentSettings.ForumUrl,
                IsClosed                        = currentSettings.IsClosed,
                EnableRSSFeeds                  = currentSettings.EnableRSSFeeds,
                DisplayEditedBy                 = currentSettings.DisplayEditedBy,
                EnableMarkAsSolution            = currentSettings.EnableMarkAsSolution,
                MarkAsSolutionReminderTimeFrame = currentSettings.MarkAsSolutionReminderTimeFrame ?? 0,
                //EnableSpamReporting = currentSettings.EnableSpamReporting,
                //EnableMemberReporting = currentSettings.EnableMemberReporting,
                EnableEmailSubscriptions    = currentSettings.EnableEmailSubscriptions,
                ManuallyAuthoriseNewMembers = currentSettings.ManuallyAuthoriseNewMembers,
                EmailAdminOnNewMemberSignUp = currentSettings.EmailAdminOnNewMemberSignUp,
                TopicsPerPage                   = currentSettings.TopicsPerPage,
                PostsPerPage                    = currentSettings.PostsPerPage,
                ActivitiesPerPage               = currentSettings.ActivitiesPerPage,
                EnablePrivateMessages           = currentSettings.EnablePrivateMessages,
                MaxPrivateMessagesPerMember     = currentSettings.MaxPrivateMessagesPerMember,
                PrivateMessageFloodControl      = currentSettings.PrivateMessageFloodControl,
                EnableSignatures                = currentSettings.EnableSignatures,
                EnablePoints                    = currentSettings.EnablePoints,
                PointsAllowedToVoteAmount       = currentSettings.PointsAllowedToVoteAmount,
                PointsAllowedForExtendedProfile = currentSettings.PointsAllowedForExtendedProfile ?? 0,
                PointsAddedPerPost              = currentSettings.PointsAddedPerPost,
                PointsAddedPostiveVote          = currentSettings.PointsAddedPostiveVote,
                PointsDeductedNagativeVote      = currentSettings.PointsDeductedNagativeVote,
                PointsAddedForSolution          = currentSettings.PointsAddedForSolution,
                AdminEmailAddress               = currentSettings.AdminEmailAddress,
                NotificationReplyEmail          = currentSettings.NotificationReplyEmail,
                SMTP         = currentSettings.SMTP,
                SMTPUsername = currentSettings.SMTPUsername,
                SMTPPassword = currentSettings.SMTPPassword,
                //AkismentKey = currentSettings.AkismentKey,
                //EnableAkisment = currentSettings.EnableAkisment != null && (bool)currentSettings.EnableAkisment,
                NewMemberEmailConfirmation = currentSettings.NewMemberEmailConfirmation != null &&
                                             (bool)currentSettings.NewMemberEmailConfirmation,
                Theme    = currentSettings.Theme,
                SMTPPort = string.IsNullOrWhiteSpace(currentSettings.SMTPPort)
                    ? null
                    : (int?)Convert.ToInt32(currentSettings.SMTPPort),
                //SpamQuestion = currentSettings.SpamQuestion,
                //SpamAnswer = currentSettings.SpamAnswer,
                Themes        = AppHelpers.GetThemeFolders(),
                SMTPEnableSSL = currentSettings.SMTPEnableSSL ?? false,
                //EnableSocialLogins = currentSettings.EnableSocialLogins ?? false,
                EnablePolls                 = currentSettings.EnablePolls ?? false,
                SuspendRegistration         = currentSettings.SuspendRegistration ?? false,
                PageTitle                   = currentSettings.PageTitle,
                MetaDesc                    = currentSettings.MetaDesc,
                EnableEmoticons             = currentSettings.EnableEmoticons == true,
                DisableDislikeButton        = currentSettings.DisableDislikeButton,
                TermsAndConditions          = currentSettings.TermsAndConditions,
                AgreeToTermsAndConditions   = currentSettings.AgreeToTermsAndConditions ?? false,
                DisableStandardRegistration = currentSettings.DisableStandardRegistration ?? false
            };

            return(settingViewModel);
        }
Example #36
0
 protected bool Has(Settings setting)
 {
     return((Options & setting) == setting);
 }
        protected void OnUpdateClick(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    var moduleController = new ModuleController();
                    var allTabsChanged = false;
                    //TODO: REMOVE IF UNUSED
                    //var allowIndexChanged = false;

                    //tab administrators can only manage their own tab
                    if (!TabPermissionController.CanAdminPage())
                    {
                        chkAllTabs.Enabled = false;
                        chkNewTabs.Enabled = false;
                        chkDefault.Enabled = false;
                        chkAllModules.Enabled = false;
                        chkAllowIndex.Enabled = false;
                        cboTab.Enabled = false;
                    }
                    Module.ModuleID = _moduleId;
                    Module.ModuleTitle = txtTitle.Text;
                    Module.Alignment = cboAlign.SelectedItem.Value;
                    Module.Color = txtColor.Text;
                    Module.Border = txtBorder.Text;
                    Module.IconFile = ctlIcon.Url;
                    Module.CacheTime = !String.IsNullOrEmpty(txtCacheDuration.Text)
                                            ? Int32.Parse(txtCacheDuration.Text)
                                            : 0;
                    Module.CacheMethod = cboCacheProvider.SelectedValue;
                    Module.TabID = TabId;
                    if (Module.AllTabs != chkAllTabs.Checked)
                    {
                        allTabsChanged = true;
                    }
                    Module.AllTabs = chkAllTabs.Checked;
                    moduleController.UpdateTabModuleSetting(Module.TabModuleID, "hideadminborder", chkAdminBorder.Checked.ToString());

                    //check whether allow index value is changed
                    var allowIndex = Settings.ContainsKey("AllowIndex") && Convert.ToBoolean(Settings["AllowIndex"]);
                    if (allowIndex != chkAllowIndex.Checked)
                    {
                        moduleController.UpdateTabModuleSetting(Module.TabModuleID, "AllowIndex", chkAllowIndex.Checked ? "True" : "False");
                    }
                    moduleController.UpdateTabModuleSetting(Module.TabModuleID, "AllowIndex", chkAllowIndex.Checked.ToString());


                    switch (Int32.Parse(cboVisibility.SelectedItem.Value))
                    {
                        case 0:
                            Module.Visibility = VisibilityState.Maximized;
                            break;
                        case 1:
                            Module.Visibility = VisibilityState.Minimized;
                            break;
                        case 2:
                            Module.Visibility = VisibilityState.None;
                            break;
                    }
                    Module.IsDeleted = false;
                    Module.Header = txtHeader.Text;
                    Module.Footer = txtFooter.Text;

                    Module.StartDate = startDatePicker.SelectedDate != null
                                        ? startDatePicker.SelectedDate.Value
                                        : Null.NullDate;

                    Module.EndDate = endDatePicker.SelectedDate != null
                                        ? endDatePicker.SelectedDate.Value
                                        : Null.NullDate;

                    Module.ContainerSrc = moduleContainerCombo.SelectedValue;
                    Module.ModulePermissions.Clear();
                    Module.ModulePermissions.AddRange(dgPermissions.Permissions);
                    Module.Terms.Clear();
                    Module.Terms.AddRange(termsSelector.Terms);

                    if (!Module.IsShared)
                    {
                        Module.InheritViewPermissions = chkInheritPermissions.Checked;
                        Module.IsShareable = isShareableCheckBox.Checked;
                        Module.IsShareableViewOnly = isShareableViewOnlyCheckBox.Checked;
                    }

                    Module.DisplayTitle = chkDisplayTitle.Checked;
                    Module.DisplayPrint = chkDisplayPrint.Checked;
                    Module.DisplaySyndicate = chkDisplaySyndicate.Checked;
                    Module.IsWebSlice = chkWebSlice.Checked;
                    Module.WebSliceTitle = txtWebSliceTitle.Text;

                    Module.WebSliceExpiryDate = diWebSliceExpiry.SelectedDate != null
                                                ? diWebSliceExpiry.SelectedDate.Value
                                                : Null.NullDate;

                    if (!string.IsNullOrEmpty(txtWebSliceTTL.Text))
                    {
                        Module.WebSliceTTL = Convert.ToInt32(txtWebSliceTTL.Text);
                    }
                    Module.IsDefaultModule = chkDefault.Checked;
                    Module.AllModules = chkAllModules.Checked;
                    moduleController.UpdateModule(Module);

                    //Update Custom Settings
                    if (SettingsControl != null)
                    {
                        try
                        {
                            SettingsControl.UpdateSettings();
                        }
                        catch (ThreadAbortException exc)
                        {
                            Logger.Debug(exc);

                            Thread.ResetAbort(); //necessary
                        }
                        catch (Exception ex)
                        {
                            Exceptions.LogException(ex);
                        }
                    }

                    //These Module Copy/Move statements must be 
                    //at the end of the Update as the Controller code assumes all the 
                    //Updates to the Module have been carried out.

                    //Check if the Module is to be Moved to a new Tab
                    if (!chkAllTabs.Checked)
                    {
                        var newTabId = Int32.Parse(cboTab.SelectedItem.Value);
                        if (TabId != newTabId)
                        {
                            //First check if there already is an instance of the module on the target page
                            var tmpModule = moduleController.GetModule(_moduleId, newTabId);
                            if (tmpModule == null)
                            {
                                //Move module
                                moduleController.MoveModule(_moduleId, TabId, newTabId, Globals.glbDefaultPane);
                            }
                            else
                            {
                                //Warn user
                                Skin.AddModuleMessage(this, Localization.GetString("ModuleExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                                return;
                            }
                        }
                    }

                    //Check if Module is to be Added/Removed from all Tabs
                    if (allTabsChanged)
                    {
                        var listTabs = TabController.GetPortalTabs(PortalSettings.PortalId, Null.NullInteger, false, true);
                        if (chkAllTabs.Checked)
                        {
                            if (!chkNewTabs.Checked)
                            {
                                foreach (var destinationTab in listTabs)
                                {
                                    var module = moduleController.GetModule(_moduleId, destinationTab.TabID);
                                    if (module != null)
                                    {
                                        if (module.IsDeleted)
                                        {
                                            moduleController.RestoreModule(module);
                                        }
                                    }
                                    else
                                    {
                                        if (!PortalSettings.ContentLocalizationEnabled || (Module.CultureCode == destinationTab.CultureCode))
                                        {
                                            moduleController.CopyModule(Module, destinationTab, Module.PaneName, true);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            moduleController.DeleteAllModules(_moduleId, TabId, listTabs);
                        }
                    }

                    //Navigate back to admin page
                    Response.Redirect(ReturnURL, true);
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Example #38
0
        public static void Make(ExtUITabstrip tabStrip)
        {
            UIHelper panelHelper = tabStrip.AddTabPage("Subscriptions");

            UIButton   button;
            UICheckBox checkBox;

            //g.AddButton("Perform All", OnPerformAllClicked);

            button         = panelHelper.AddButton("Refresh workshop items (checks for bad items)", RequestItemDetails) as UIButton;
            button.tooltip = "checks for missing/partially downloaded/outdated items";

            button         = panelHelper.AddButton("unsubscribe from deprecated workshop items [EXPERIMENTAL] ", () => CheckSubsUtil.Instance.UnsubDepricated()) as UIButton;
            button.tooltip = "if steam does not return item path, i assume its deprecated.";

            button           = panelHelper.AddButton("Resubscribe to all broken downloads (exits game) [EXPERIMENTAL]", CheckSubsUtil.ResubcribeExternally) as UIButton;
            button.tooltip   = "less steam can hide problems. if you use less steam please click 'Refresh workshop items' to get all broken downloads";
            button.isVisible = false; //hide for now.

            checkBox = panelHelper.AddCheckbox(
                "Delete unsubscribed items on startup",
                Config.DeleteUnsubscribedItemsOnLoad,
                val => {
                ConfigUtil.Config.DeleteUnsubscribedItemsOnLoad = val;
                ConfigUtil.SaveConfig();
            }) as UICheckBox;

            button = panelHelper.AddButton("Delete Now", () => CheckSubsUtil.Instance.DeleteUnsubbed()) as UIButton;
            Settings.Pairup(checkBox, button);

            {
                var g = panelHelper.AddGroup("Broken downloads") as UIHelper;

                tfSteamPath_ = g.AddTextfield(
                    text: "Steam Path: ",
                    defaultContent: ConfigUtil.Config.SteamPath ?? "",
                    eventChangedCallback: _ => { },
                    eventSubmittedCallback : delegate(string text) {
                    if (CheckSteamPath(text))
                    {
                        ConfigUtil.Config.SteamPath = text;
                        ConfigUtil.SaveConfig();
                    }
                }) as UITextField;
                tfSteamPath_.width   = 650;
                tfSteamPath_.tooltip = "Path to steam.exe";
                g.AddButton("Redownload broken downloads [EXPERIMENTAL]", delegate() {
                    try {
                        var path = tfSteamPath_.text;
                        if (CheckSteamPath(path))
                        {
                            CheckSubsUtil.ReDownload(path);
                            Prompt.Warning("Exit",
                                           "Please exit to desktop, wait for steam download to finish, and then start Cities skylines again.\n" +
                                           "Should this not work the first time, please try again.");
                        }
                    } catch (Exception ex) {
                        ex.Log();
                    }
                });
            }

            //b = g.AddButton("delete duplicates", OnPerformAllClicked) as UIButton;
            //b.tooltip = "when excluded mod is updated, and included duplicate of it is created";
        }
        public void ShowSettings()
        {
            Settings objSettings = new Settings(this);

            objSettings.ShowDialog();
        }
 public void LoadSettings()
 {
     settings = new Settings();
 }
 public TestInitialize(Settings settings)
 {
     _settings = settings;
 }
Example #42
0
 public void DisposeRunspace()
 {
     Settings.CleanUpRecordingCollection();
 }
Example #43
0
        public void Test_NewSettingsIsValid()
        {
            Settings audset = new Settings();

            Assert.True(audset != null);
        }
Example #44
0
        static void Main(string[] args)
        {
            try
            {
                var configuration = Settings.LoadSettings();

                Watcher watcher = new Watcher(configuration);
                watcher.Start();
                log.Info("FileSystemWatcher started");
                Console.WriteLine("FileSystemWatcher started");

                AutoPoster poster = new AutoPoster(configuration);
                poster.Start();
                log.Info("Autoposter started");
                Console.WriteLine("Autoposter started");

                IndexerNotifierBase notifier = IndexerNotifierBase.GetActiveNotifier(configuration);
                if (notifier != null)
                {
                    notifier.Start();
                    log.Info("Notifier started");
                    Console.WriteLine("Notifier started");
                }
                else
                {
                    log.Info("No notifier");
                    Console.WriteLine("No notifier");
                }

                IndexerVerifierBase verifier = IndexerVerifierBase.GetActiveVerifier(configuration);
                if (verifier != null)
                {
                    verifier.Start();
                    log.Info("Verifier started");
                    Console.WriteLine("Verifier started");
                }
                else
                {
                    log.Info("No verifier");
                    Console.WriteLine("No verifier");
                }

                DatabaseCleaner cleaner = new DatabaseCleaner(configuration);
                cleaner.Start();
                log.Info("DB Cleaner started");
                Console.WriteLine("DB Cleaner started");

                Console.WriteLine("Press the \"s\" key to stop after the current operations have finished.");

                Boolean stop = false;
                while (!stop)
                {
                    var keyInfo = Console.ReadKey();
                    stop = keyInfo.KeyChar == 's' || keyInfo.KeyChar == 'S';
                }

                cleaner.Stop();
                log.Info("DB Cleaner stopped");
                Console.WriteLine("DB Cleaner stopped");

                watcher.Stop();
                log.Info("FileSystemWatcher stopped");
                Console.WriteLine("FileSystemWatcher stopped");

                if (verifier != null)
                {
                    verifier.Stop();
                    log.Info("Verifier stopped");
                    Console.WriteLine("Verifier stopped");
                }

                if (notifier != null)
                {
                    notifier.Stop();
                    log.Info("Notifier stopped");
                    Console.WriteLine("Notifier stopped");
                }

                poster.Stop();
                log.Info("Autoposter stopped");
                Console.WriteLine("Autoposter stopped");
            }
            catch (Exception ex)
            {
                log.Fatal("Fatal exception when starting the autoposter.", ex);
                throw;
            }
        }
Example #45
0
        public IList <Shape> Execute(StyleOption option, EffectsDesigner designer, ImageItem source, Shape imageShape, Settings settings)
        {
            List <Shape> result = new List <Shape>();

            if (option.IsUseOverlayStyle)
            {
                Shape backgroundOverlayShape = designer.ApplyOverlayEffect(option.OverlayColor, option.OverlayTransparency);
                result.Add(backgroundOverlayShape);
            }
            return(result);
        }
 public PostUserSteps(Settings settings)
 {
     _settings = settings;
 }
Example #47
0
 public override void VisitSettings(Settings n)
 {
     VisitDeclarationClass(n);
 }
 public SpeedTestRunner(RegionInfo location)
 {
     _client   = new SpeedTestClient();
     _settings = _client.GetSettings();
     _location = location;
 }
Example #49
0
 /// <summary>
 /// Starts a new MiniProfiler based on the current <see cref="IProfilerProvider"/>. This new profiler can be accessed by
 /// <see cref="MiniProfiler.Current"/>
 /// </summary>
 /// <param name="level">The level.</param>
 /// <returns>the mini profiler.</returns>
 public static MiniProfiler Start(ProfileLevel level = ProfileLevel.Info)
 {
     Settings.EnsureProfilerProvider();
     return(Settings.ProfilerProvider.Start(level));
 }
Example #50
0
 /// <summary>
 /// Ends the current profiling session, if one exists.
 /// </summary>
 /// <param name="discardResults">
 /// When true, clears the <see cref="MiniProfiler.Current"/> for this HttpContext, allowing profiling to
 /// be prematurely stopped and discarded. Useful for when a specific route does not need to be profiled.
 /// </param>
 public static void Stop(bool discardResults = false)
 {
     Settings.EnsureProfilerProvider();
     Settings.ProfilerProvider.Stop(discardResults);
 }
Example #51
0
 private TaxService(Settings settings)
 {
     this.Settings = settings;
 }
Example #52
0
 public static TaxService Create(Settings settings)
 {
     return(new TaxService(settings));
 }
Example #53
0
        public void InitializeScheduler()
        {
            string publishingInstance = Settings.GetSetting("Publishing.PublishingInstance").ToLower();
            string instanceName       = Settings.InstanceName.ToLower();
            string contextDbName      = Settings.GetSetting(SitecronConstants.SettingsNames.SiteCronContextDB);

            if (!string.IsNullOrEmpty(publishingInstance) && !string.IsNullOrEmpty(instanceName) && publishingInstance != instanceName)
            {
                Log.Info(string.Format("Sitecron - Exit without initialization, this server is not the primary in the load balanced environment. PublishingInstance: {0} != InstanceName: {1}", publishingInstance, instanceName), this);
                return;
            }
            else
            {
                Log.Info("Initialize Sitecron", this);

                try
                {
                    //currently we are restricting this module to run using Master
                    Database contextDb = Factory.GetDatabase(contextDbName);

                    if (contextDb != null)
                    {
                        IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
                        scheduler.Start();

                        scheduler.Clear();

                        //attach Job listener to pickup status on all jobs in all groups
                        scheduler.ListenerManager.AddJobListener(new CustomJobListener(), GroupMatcher <JobKey> .AnyGroup());

                        //get a list of all items in Sitecron folder and iterate through them
                        //add them to the schedule

                        Item[] sitecronJobs = contextDb.SelectItems(SitecronConstants.Queries.QueryRetriveJobs);

                        Log.Info("Loading Sitecron Jobs", this);

                        if (sitecronJobs != null && sitecronJobs.Count() > 0)
                        {
                            foreach (Item i in sitecronJobs)
                            {
                                if (string.IsNullOrEmpty(i[SitecronConstants.FieldNames.Type]))
                                {
                                    Log.Info(string.Format("Sitecron - Job Not Loaded - {0} Invalid Type: {1}", i.Name, i[SitecronConstants.FieldNames.Type]), this);
                                    continue;
                                }

                                if (string.IsNullOrEmpty(i[SitecronConstants.FieldNames.ExecuteExactlyAtDateTime]) && string.IsNullOrEmpty(i[SitecronConstants.FieldNames.CronExpression]))
                                {
                                    Log.Info(string.Format("Sitecron - Job Not Loaded - Invalid ExecuteExactlyAtDateTime or Cron Expression: {0} ExecuteExactlyAtDateTime: {1} Cron Expression: {2}", i.Name, i[SitecronConstants.FieldNames.ExecuteExactlyAtDateTime], i[SitecronConstants.FieldNames.CronExpression]), this);
                                    continue;
                                }

                                if (!string.IsNullOrEmpty(i[SitecronConstants.FieldNames.ExecuteExactlyAtDateTime]) && !string.IsNullOrEmpty(i[SitecronConstants.FieldNames.CronExpression]))
                                {
                                    Log.Info(string.Format("Sitecron - Job Not Loaded - Both ExecuteExactlyAtDateTime and Cron Expression specified: {0} ExecuteExactlyAtDateTime: {1} Cron Expression: {2}", i.Name, i[SitecronConstants.FieldNames.ExecuteExactlyAtDateTime], i[SitecronConstants.FieldNames.CronExpression]), this);
                                    continue;
                                }

                                Type jobType = Type.GetType(i[SitecronConstants.FieldNames.Type]);
                                if (jobType == null)
                                {
                                    Log.Info(string.Format("Sitecron - Job Not Loaded - Could not load Type: {0} Type: {1} Cron Expression: {2}", i.Name, i[SitecronConstants.FieldNames.Type], i[SitecronConstants.FieldNames.CronExpression]), this);
                                    continue;
                                }

                                if (!string.IsNullOrEmpty(i[SitecronConstants.FieldNames.Disable]) && i[SitecronConstants.FieldNames.Disable] == "1")
                                {
                                    Log.Info(string.Format("Sitecron - Job Not Loaded - Job Disabled: {0} Type: {1} Cron Expression: {2}", i.Name, i[SitecronConstants.FieldNames.Type], i[SitecronConstants.FieldNames.CronExpression]), this);
                                    continue;
                                }

                                IJobDetail jobDetail = JobBuilder.Create(jobType).Build();
                                string     jobParams = i[SitecronConstants.FieldNames.Parameters];
                                if (string.IsNullOrEmpty(jobParams))
                                {
                                    jobParams = string.Concat(SitecronConstants.ParamNames.zSiteCronItemID, "=", i.ID.ToString());
                                }
                                else
                                {
                                    jobParams += string.Concat("&", SitecronConstants.ParamNames.zSiteCronItemID, "=", i.ID.ToString());
                                }

                                jobDetail.JobDataMap.Add(SitecronConstants.FieldNames.Parameters, jobParams);

                                if (!string.IsNullOrEmpty(i[SitecronConstants.FieldNames.Items]))
                                {
                                    jobDetail.JobDataMap.Add(SitecronConstants.FieldNames.Items, i[SitecronConstants.FieldNames.Items]);
                                }

                                jobDetail.JobDataMap.Add(SitecronConstants.FieldNames.ArchiveAfterExecution, i[SitecronConstants.FieldNames.ArchiveAfterExecution]);
                                jobDetail.JobDataMap.Add(SitecronConstants.FieldNames.ItemID, i.ID.ToString());

                                if (!string.IsNullOrEmpty(i[SitecronConstants.FieldNames.CronExpression]))
                                {
                                    Log.Info(string.Format("Sitecron - Job Loaded - {0} using CronExpression: {1}", i.Name, i[SitecronConstants.FieldNames.CronExpression]), this);
                                    ITrigger trigger = TriggerBuilder.Create()
                                                       .WithIdentity(i.ID.ToString())
                                                       .WithCronSchedule(i[SitecronConstants.FieldNames.CronExpression])
                                                       .ForJob(jobDetail)
                                                       .Build();
                                    scheduler.ScheduleJob(jobDetail, trigger);
                                }

                                if (!string.IsNullOrEmpty(i[SitecronConstants.FieldNames.ExecuteExactlyAtDateTime]))
                                {
                                    var startDateField = (DateField)i.Fields[SitecronConstants.FieldNames.ExecuteExactlyAtDateTime];
                                    if (startDateField != null)
                                    {
                                        Log.Info(string.Format("Sitecron - Job Loaded - {0} using ExecuteExactlyAtDateTime: {1}", i.Name, i[SitecronConstants.FieldNames.ExecuteExactlyAtDateTime]), this);
                                        DateTimeOffset startDateTime = new DateTimeOffset(startDateField.DateTime.ToUniversalTime());
                                        ITrigger       trigger       = TriggerBuilder.Create()
                                                                       .WithIdentity(i.ID.ToString())
                                                                       .StartAt(startDateTime)
                                                                       .ForJob(jobDetail)
                                                                       .Build();
                                        scheduler.ScheduleJob(jobDetail, trigger);
                                    }
                                }


                                Log.Info(string.Format("Sitecron - Loaded Job: {0} Type: {1} Cron Expression: {2} ExecuteExactlyAtDateTime: {3} Parameters: {4}", i.Name, i[SitecronConstants.FieldNames.Type], i[SitecronConstants.FieldNames.CronExpression], i[SitecronConstants.FieldNames.ArchiveAfterExecution], i[SitecronConstants.FieldNames.Parameters]), this);
                            }
                        }
                    }
                    else
                    {
                        Log.Warn("Sitecron - Exit, context db not found.", this);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("Sitecron ERROR: " + ex.Message, ex, this);
                }
            }
        }
 //--- Constructors ---
 public ModelFilesPackager(Settings settings, string sourceFilename) : base(settings, sourceFilename)
 {
 }
Example #55
0
        /// <summary>
        ///     Maps the posts for a specific topic
        /// </summary>
        /// <param name="posts"></param>
        /// <param name="votes"></param>
        /// <param name="permission"></param>
        /// <param name="topic"></param>
        /// <param name="loggedOnUser"></param>
        /// <param name="settings"></param>
        /// <param name="favourites"></param>
        /// <returns></returns>
        public static List <PostViewModel> CreatePostViewModels(IEnumerable <Post> posts, Dictionary <Guid, List <Vote> > votes,
                                                                PermissionSet permission, Topic topic, MembershipUser loggedOnUser, Settings settings,
                                                                Dictionary <Guid, List <Favourite> > favourites)
        {
            var viewModels = new List <PostViewModel>();

            foreach (var post in posts)
            {
                var id        = post.Id;
                var postVotes = votes.ContainsKey(id) ? votes[id] : new List <Vote>();
                var postFavs  = favourites.ContainsKey(id) ? favourites[id] : new List <Favourite>();
                viewModels.Add(
                    CreatePostViewModel(post, postVotes, permission, topic, loggedOnUser, settings, postFavs));
            }
            return(viewModels);
        }
Example #56
0
 public AppleII(CoreComm comm, IEnumerable <GameInfo> gameInfoSet, IEnumerable <byte[]> romSet, Settings settings)
     : this(comm, gameInfoSet.First(), romSet.First(), settings)
 {
     GameInfoSet = gameInfoSet.ToList();
     RomSet      = romSet.ToList();
 }
    public void DoBuild(Tile t)
    {
        if (buildMode == BuildMode.FURNITURE)
        {
            // Create the Furniture and assign it to the tile
            // Can we build the furniture in the selected tile?
            // Run the ValidPlacement function!
            string furnitureType = buildModeObjectType;

            if (
                WorldController.Instance.World.IsFurniturePlacementValid(furnitureType, t) &&
                DoesBuildJobOverlapExistingBuildJob(t, furnitureType) == false)
            {
                // This tile position is valid for this furniture

                // Check if there is existing furniture in this tile. If so delete it.
                // TODO Possibly return resources. Will the Deconstruct() method handle that? If so what will happen if resources drop ontop of new non-passable structure.
                if (t.Furniture != null)
                {
                    t.Furniture.Deconstruct();
                }

                // Create a job for it to be build
                Job j;

                if (PrototypeManager.FurnitureJob.HasPrototype(furnitureType))
                {
                    // Make a clone of the job prototype
                    j = PrototypeManager.FurnitureJob.GetPrototype(furnitureType).Clone();

                    // Assign the correct tile.
                    j.tile = t;
                }
                else
                {
                    Debug.ULogErrorChannel("BuildModeController", "There is no furniture job prototype for '" + furnitureType + "'");
                    j = new Job(t, furnitureType, FurnitureActions.JobComplete_FurnitureBuilding, 0.1f, null, Job.JobPriority.High);
                    j.JobDescription = "job_build_" + furnitureType + "_desc";
                }

                j.furniturePrototype = PrototypeManager.Furniture.GetPrototype(furnitureType);

                // Add the job to the queue or build immediately if in dev mode
                if (Settings.GetSetting("DialogBoxSettings_developerModeToggle", false))
                {
                    WorldController.Instance.World.PlaceFurniture(j.JobObjectType, j.tile);
                }
                else
                {
                    for (int x_off = t.X; x_off < (t.X + j.furniturePrototype.Width); x_off++)
                    {
                        for (int y_off = t.Y; y_off < (t.Y + j.furniturePrototype.Height); y_off++)
                        {
                            // FIXME: I don't like having to manually and explicitly set
                            // flags that preven conflicts. It's too easy to forget to set/clear them!
                            Tile offsetTile = WorldController.Instance.World.GetTileAt(x_off, y_off, t.Z);
                            offsetTile.PendingBuildJob = j;
                            j.OnJobStopped            += (theJob) =>
                            {
                                offsetTile.PendingBuildJob = null;
                            };
                        }
                    }

                    WorldController.Instance.World.jobQueue.Enqueue(j);
                }
            }
        }
        else if (buildMode == BuildMode.FLOOR)
        {
            // We are in tile-changing mode.
            ////t.Type = buildModeTile;

            TileType tileType = buildModeTile;

            if (
                t.Type != tileType &&
                t.Furniture == null &&
                t.PendingBuildJob == null &&
                CanBuildTileTypeHere(t, tileType))
            {
                // This tile position is valid tile type

                // Create a job for it to be build
                Job j = TileType.GetConstructionJobPrototype(tileType);

                j.tile = t;

                // Add the job to the queue or build immediately if in dev mode
                if (Settings.GetSetting("DialogBoxSettings_developerModeToggle", false))
                {
                    j.tile.Type = j.JobTileType;
                }
                else
                {
                    // FIXME: I don't like having to manually and explicitly set
                    // flags that preven conflicts. It's too easy to forget to set/clear them!
                    t.PendingBuildJob = j;
                    j.OnJobStopped   += (theJob) =>
                    {
                        theJob.tile.PendingBuildJob = null;
                    };

                    WorldController.Instance.World.jobQueue.Enqueue(j);
                }
            }
        }
        else if (buildMode == BuildMode.DECONSTRUCT)
        {
            // TODO
            if (t.Furniture != null)
            {
                // check if this is a WALL neighbouring a pressured and pressureless environ & if so bail
                if (t.Furniture.HasTypeTag("Wall"))
                {
                    Tile[] neighbors          = t.GetNeighbours(); // diagOkay??
                    int    pressuredNeighbors = 0;
                    int    vacuumNeighbors    = 0;
                    foreach (Tile neighbor in neighbors)
                    {
                        if (neighbor != null && neighbor.Room != null)
                        {
                            if ((neighbor.Room == World.Current.GetOutsideRoom()) || MathUtilities.IsZero(neighbor.Room.GetTotalGasPressure()))
                            {
                                vacuumNeighbors++;
                            }
                            else
                            {
                                pressuredNeighbors++;
                            }
                        }
                    }

                    if (vacuumNeighbors > 0 && pressuredNeighbors > 0)
                    {
                        Debug.ULogChannel("BuildModeController", "Someone tried to deconstruct a wall between a pressurised room and vacuum!");
                        return;
                    }
                }

                t.Furniture.Deconstruct();
            }
            else if (t.PendingBuildJob != null)
            {
                t.PendingBuildJob.CancelJob();
            }
        }
        else
        {
            Debug.ULogErrorChannel("BuildModeController", "UNIMPLEMENTED BUILD MODE");
        }
    }
Example #58
0
        public void Current()
        {
            Settings settings = Application.Current.Host.Settings;

            Check(settings);
        }
Example #59
0
        public void New()
        {
            Settings settings = new Settings();

            Check(settings);
        }
Example #60
0
 public FinishTaskDeletion(
     IMessagingHubSender sender, IStateManager stateManager,
     Settings settings, RoutineRepository routineRepository, ReschedulerTask reschedulerTask)
     : base(sender, stateManager, settings, routineRepository, reschedulerTask)
 {
 }