Esempio n. 1
0
        private void StartBenchmarkButton_Click(object sender, RoutedEventArgs e)
        {
            DisplayConfiguration.PHYSICAL_MONITOR Handle = DisplayConfiguration.GetPhysicalMonitors(DisplayConfiguration.GetCurrentMonitor())[0];
            var    GetBrightnessWatch = System.Diagnostics.Stopwatch.StartNew();
            double Brightness         = DisplayConfiguration.GetMonitorBrightness(Handle);

            GetBrightnessWatch.Stop();

            var SetBrightnessWatchExtrems = System.Diagnostics.Stopwatch.StartNew();

            DisplayConfiguration.MonitorExtremums MonExtems = DisplayConfiguration.GetMonitorExtremums(Handle);
            uint dwMinimumBrightness = MonExtems.Min;
            uint dwMaximumBrightness = MonExtems.Max;

            DisplayConfiguration.SetMonitorBrightness(Handle, 1, dwMinimumBrightness, dwMaximumBrightness);
            SetBrightnessWatchExtrems.Stop();

            var SetBrightnessWatch = System.Diagnostics.Stopwatch.StartNew();

            DisplayConfiguration.SetMonitorBrightness(Handle, Brightness, dwMinimumBrightness, dwMaximumBrightness);
            SetBrightnessWatch.Stop();

            MessageBox.Show($"GetBrightness: {GetBrightnessWatch.ElapsedMilliseconds} ms.\n" +
                            $"SetBrightnessExtrems: {SetBrightnessWatchExtrems.ElapsedMilliseconds} ms.\n" +
                            $"SetBrightness: {SetBrightnessWatch.ElapsedMilliseconds} ms.\n\n" +
                            $"Total: {GetBrightnessWatch.ElapsedMilliseconds + SetBrightnessWatchExtrems.ElapsedMilliseconds + SetBrightnessWatch.ElapsedMilliseconds} ms.", "Benchmark Results");
        }
Esempio n. 2
0
        bool IJob.Initialize(IServiceProvider serviceProvider)
        {
            _settings = serviceProvider.GetService <ISettingsServiceInternal>();

            string settingString = _settings.GetSetting("DisplayWakeUpJob", "DisplayConfiguration").GetValue <string>();

            _configurations.AddRange(DisplayConfiguration.ParseSettingString(settingString));

            if (_configurations.Count == 0)
            {
                Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.NoConfigurationsFoundError);
                return(false);
            }

            _autoSleepAfterMinutes = _settings.GetSetting("DisplayWakeUpJob", "TurnOffTimeout").GetValue <int>();
            if (_autoSleepAfterMinutes > 0)
            {
                _autoSleepTimerThread              = new Thread(AutoSleepTimerThread);
                _autoSleepTimerThread.Name         = "Auto-sleep timer thread";
                _autoSleepTimerThread.Priority     = ThreadPriority.BelowNormal;
                _autoSleepTimerThread.IsBackground = true;
                _autoSleepTimerThread.Start();
            }

            _ignoreErrorInResponse = _settings.GetSetting("DisplayWakeUpJob", "IgnoreErrorInResponse").GetValue <bool>();

            return(true);
        }
Esempio n. 3
0
        /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Title:          SET BRIGHTNESS
        /// Description:    this function gets the list of handles to all monitors and sets their brightness to the value NewBrightness.
        /// </summary>
        ///
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///
        private void SetBrightness(object sender, EventArgs e)
        {
            if (NewBrightness != CurrentBrightness)
            {
                try
                {
                    physicalMonitors = DisplayConfiguration.GetPhysicalMonitors(DisplayConfiguration.GetCurrentMonitor());

                    foreach (DisplayConfiguration.PHYSICAL_MONITOR physicalMonitor in physicalMonitors)
                    {
                        try
                        {
                            DisplayConfiguration.SetMonitorBrightness(physicalMonitor, NewBrightness);
                            DisplayConfiguration.SetMonitorContrast(physicalMonitor, NewBrightness);
                            CurrentBrightness = NewBrightness;
                        }
                        catch
                        {
                            System.Diagnostics.Debug.WriteLine("ERROR: cannot set brightness!");
                            labelStatus.Text = "could not set brightness!";
                        }
                    }
                }
                catch
                {
                    System.Diagnostics.Debug.WriteLine("ERROR: cannot find monitors!");
                    labelStatus.Text = "could not find monitors!";
                }
            }

            UpdateObjects(sender, e);
        }
Esempio n. 4
0
        /// <summary/>
        public override DisplayThemeStateValue GetValue()
        {
            string themeFilename = DisplayConfiguration.GetThemeFilename();
            //If we query on a backed up theme, the BACKUP words will show up
            //API returns Windows Classic if no theme is found (Server 2003 for example)
            string themeName = DisplayConfiguration.GetTheme().Replace(BackupStr, string.Empty);

            //If the theme manager is disabled or there's no theme selected, return windows classic
            if (!DisplayConfiguration.IsThemeEnabled || themeFilename == null)
            {
                return(new DisplayThemeStateValue(themeName, null));
            }

            //If the theme has been customized, make sure we back it up
            string modifiedThemeName = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\LastTheme", "DisplayName of Modified", null) as string;

            if (!String.IsNullOrEmpty(modifiedThemeName))
            {
                //Need to save theme
                themeFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), String.Format("{0}{1}.theme", themeName, BackupStr));
                DisplayConfiguration.SaveCurrentTheme(themeFilename);
            }

            return(new DisplayThemeStateValue(themeName, themeFilename));
        }
        public ActionResult DeleteConfirmed(int id)
        {
            DisplayConfiguration displayConfiguration = db.DisplayConfigurations.Find(id);

            db.DisplayConfigurations.Remove(displayConfiguration);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public ActionResult Edit([Bind(Include = "Id,DeviceName,SpeedAvg,SpeedMax")] DisplayConfiguration displayConfiguration)
 {
     if (ModelState.IsValid)
     {
         db.Entry(displayConfiguration).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(displayConfiguration));
 }
        public ActionResult Create([Bind(Include = "Id,DeviceName,SpeedAvg,SpeedMax")] DisplayConfiguration displayConfiguration)
        {
            if (ModelState.IsValid)
            {
                db.DisplayConfigurations.Add(displayConfiguration);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(displayConfiguration));
        }
Esempio n. 8
0
    //  create a display config with a little more information filled.
    private DisplayConfiguration CreateDisplayConfig()
    {
        Database    db    = Application.DocumentManager.MdiActiveDocument.Database;
        Transaction trans = db.TransactionManager.StartTransaction();

        DisplayRepresentationManager drm      = new DisplayRepresentationManager(db);
        ObjectId             currentDisConfId = drm.DisplayConfigurationIdForCurrentViewport;
        DisplayConfiguration currentDisConf   = trans.GetObject(currentDisConfId, OpenMode.ForRead) as DisplayConfiguration;

        DisplayConfiguration dc = new DisplayConfiguration();

        try
        {
            DisplaySet ds = new DisplaySet();
            ds.SetToStandard(db);
            ds.SubSetDatabaseDefaults(db);

            //  top
            dc.ViewDependentCombinations.Add(new ViewDependentCombination(new Vector3d(0, 0, 1), DictionaryDisplaySet.GetStandardPlanId(db)));
            //  for bottom. No DictionaryDisplaySet.GetStandardXxxId for Plan Diagnostic, so get it from the name.
            ObjectId id = DictionaryDisplaySet.GetStandardSet("Plan Diagnostic", db);
            if (id != ObjectId.Null)
            {
                dc.ViewDependentCombinations.Add(new ViewDependentCombination(new Vector3d(0, 0, -1), id));
            }
            else  // if not found, let's use Reflected.
            {
                dc.ViewDependentCombinations.Add(new ViewDependentCombination(new Vector3d(0, 0, -1), DictionaryDisplaySet.GetStandardReflectedId(db)));  //buttom
            }
            dc.ViewDependentCombinations.Add(new ViewDependentCombination(new Vector3d(-1, 0, 0), DictionaryDisplaySet.GetStandardSectionElevId(db))); // left
            dc.ViewDependentCombinations.Add(new ViewDependentCombination(new Vector3d(1, 0, 0), DictionaryDisplaySet.GetStandardSectionElevId(db)));  // right
            dc.ViewDependentCombinations.Add(new ViewDependentCombination(new Vector3d(0, -1, 0), DictionaryDisplaySet.GetStandardSectionElevId(db))); //  front
            dc.ViewDependentCombinations.Add(new ViewDependentCombination(new Vector3d(0, 1, 0), DictionaryDisplaySet.GetStandardSectionElevId(db)));  // back

            //  try adding DefaultViewDependentViewSet here.
            dc.DefaultViewDependentViewSet = DictionaryDisplaySet.GetStandardModelId(db);

            DictionaryDisplayConfiguration dictDisplayConfigs = new DictionaryDisplayConfiguration(db);
            string newName = GetNewName();
            dictDisplayConfigs.AddNewRecord(newName, dc);
            trans.AddNewlyCreatedDBObject(dc, true);
            trans.Commit();
        }
        catch (System.Exception)
        {
            trans.Abort();
        }
        finally
        {
            trans.Dispose();
        }
        return(dc);
    }
        // GET: DisplayConfigurations/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DisplayConfiguration displayConfiguration = db.DisplayConfigurations.Find(id);

            if (displayConfiguration == null)
            {
                return(HttpNotFound());
            }
            return(View(displayConfiguration));
        }
Esempio n. 10
0
 /// <summary>
 /// コンストラクタ
 /// </summary>
 public ApplicationConfiguration()
 {
     //
     // ここにはファイル読み込みできなかったときのために各構成情報のデフォルト値を設定します。
     //
     NotifyConfiguration = new NotifyConfiguration
                           {
                               TargetUri           = "ws://mc-tfserver:8081/jenkins",
                               PopupAnimationType  = PopupAnimation.Slide,
                               PopupTimeout        = TimeSpan.FromSeconds(10),
                               DisplayHistoryCount = 100,
                               IsNotifySuccess     = false
                           };
     DisplayConfiguration = new DisplayConfiguration();
 }
Esempio n. 11
0
 /// <summary>
 /// コンストラクタ
 /// </summary>
 public ApplicationConfiguration()
 {
     //
     // ここにはファイル読み込みできなかったときのために各構成情報のデフォルト値を設定します。
     //
     NotifyConfiguration = new NotifyConfiguration
     {
         TargetUri           = "ws://mc-tfserver:8081/jenkins",
         PopupAnimationType  = PopupAnimation.Slide,
         PopupTimeout        = TimeSpan.FromSeconds(10),
         DisplayHistoryCount = 100,
         IsNotifySuccess     = false
     };
     DisplayConfiguration = new DisplayConfiguration();
 }
        // GET: DisplayConfiguration/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            DisplayConfiguration displayConfig = this._repository.Get(id);

            if (displayConfig == null)
            {
                return(HttpNotFound());
            }
            return(View(displayConfig.Map <DisplayConfigurationViewModel>()));
        }
Esempio n. 13
0
        public static DisplayConfigurationModel ToModel(this DisplayConfiguration bo)
        {
            if (bo == null)
            {
                return(null);
            }

            return(new DisplayConfigurationModel
            {
                Id = bo.Id,
                PersonneId = bo.PersonneId,
                DeviceName = bo.DeviceName,
                SpeedAvg = bo.SpeedAvg,
                SpeedMax = bo.SpeedMax,
                UnitDistance = bo.UnitDistance.ToModel(),

                Person = bo.Person.ToModel()
            });
        }
Esempio n. 14
0
    //  show the information of the given display configuration.
    private void ListDisplayConfig(DisplayConfiguration dc)
    {
        Database    db    = Application.DocumentManager.MdiActiveDocument.Database;
        Transaction trans = db.TransactionManager.StartTransaction();

        try
        {
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n");
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Name: " + dc.Name + "\n");
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Description: " + dc.Description + "\n");
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Cut Plane Display Above: " + dc.CutPlaneAboveRange + "\n");
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Cut Plane Display Below: " + dc.CutPlaneBelowRange + "\n");

            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Use View Port View Direction: " + dc.UseViewportViewDirection.ToString() + "\n");
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Is View Dependent: " + dc.IsViewDependent.ToString() + "\n");
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Hard View Direction: " + dc.HardViewDirection.ToString() + "\n");


            Vector3d   v;
            DisplaySet ds;
            foreach (ViewDependentCombination vd in dc.ViewDependentCombinations)
            {
                v = vd.Direction;

                ds = trans.GetObject(vd.SetId, OpenMode.ForRead) as DisplaySet;
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(v.ToString() + " " + ds.Name + "\n");
            }

            // added.  Default view set
            ds = trans.GetObject(dc.DefaultViewDependentViewSet, OpenMode.ForRead) as DisplaySet;
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Default View Dependent View Set: " + ds.Name + "\n");
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n");
            trans.Commit();
        }
        catch (System.Exception)
        {
            trans.Abort();
        }
        finally
        {
            trans.Dispose();
        }
    }
Esempio n. 15
0
        /// <summary/>
        public override bool SetValue(DisplayThemeStateValue value, object action)
        {
            if (!String.IsNullOrEmpty(value.ThemeFilename))
            {
                if (!string.Equals(DisplayConfiguration.GetThemeFilename(), value.ThemeFilename, StringComparison.InvariantCultureIgnoreCase))
                {
                    DisplayConfiguration.SetCustomTheme(value.ThemeFilename);
                }

                return(String.Equals(DisplayConfiguration.GetThemeFilename(), value.ThemeFilename, StringComparison.InvariantCultureIgnoreCase));
            }
            else if (!String.IsNullOrEmpty(value.Theme))
            {
                //If we have no theme file information, we need to ensure we are using the right theme by switching
                //

                DisplayConfiguration.SetTheme(value.Theme);
                return(DisplayConfiguration.GetTheme().Equals(value.Theme, StringComparison.InvariantCultureIgnoreCase));
            }
            return(false);
        }
Esempio n. 16
0
        bool IJob.Initialize()
        {
            string settingString = SettingsManager.Instance.GetSetting("DisplayWakeUpJob", "DisplayConfiguration").GetString();

            _configurations.AddRange(DisplayConfiguration.ParseSettingString(settingString));

            if (_configurations.Count == 0)
            {
                Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.NoConfigurationsFoundError);
                return(false);
            }

            int turnOffTimeout = SettingsManager.Instance.GetSetting("DisplayWakeUpJob", "TurnOffTimeout").GetInt32();

            if (turnOffTimeout > 0)
            {
                // TODO: Start background thread which checks all 60 seconds for automatically turning
            }

            return(true);
        }
		//private TargetPreferredModeInformation preferredMode;



		internal DisplayConfigMonitorInfo( DisplayConfiguration displayConfiguration, PathTargetInfo info, TargetDeviceInformation targetDeviceName, bool supportsVirtualMode )
			: base( info.AdapterId, info.Id, displayConfiguration.Topology )
		{
			this.info = info;

			int modeInfoIndex;
			if( supportsVirtualMode )
			{
				modeInfoIndex = info.ModeInfoIndex2;
				if( modeInfoIndex == PathTargetInfo.InvalidModeInfoIndex2 )
					modeInfoIndex = PathTargetInfo.InvalidModeInfoIndex;
			}
			else
				modeInfoIndex = info.ModeInfoIndex;

			if( modeInfoIndex > PathTargetInfo.InvalidModeInfoIndex && modeInfoIndex < displayConfiguration.ModeInfo.Count )
				mode = displayConfiguration.ModeInfo[ modeInfoIndex ].VideoSignalInformation;

			displayName = targetDeviceName.FriendlyName;
			connectorInstance = targetDeviceName.ConnectorInstance;
			devicePath = targetDeviceName.DevicePath;
		}
        public ActionResult Edit(DisplayConfigurationViewModel displayConfigVm)
        {
            if (!ModelState.IsValid)
            {
                return(View(displayConfigVm));
            }
            try
            {
                DisplayConfiguration disConfig = this._repository.Get(displayConfigVm.Id);
                displayConfigVm.Map(disConfig);

                this._repository.Commit();

                return(RedirectToAction(nameof(this.Index)));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
            }

            return(View(displayConfigVm));
        }
Esempio n. 19
0
        private static readonly byte[] CMD_RESETPAGEADDR = { 0x22, 0x00, 0x07 }; /* Reset the page address pointer                           */


        /* Initialize GPIO, I2C, and the display
         * The device may not respond to multiple Init calls without being power cycled
         * so we allow an optional boolean to excuse failures which is useful while debugging
         * without power cycling the display */
        public void Init(DisplayConfiguration configuration)
        {
            Debug.WriteLine("SSD1306::Initialize");

            try
            {
                SSD1306_Custom_Address = configuration.DisplayAddress;
                //Instantiate the I2CConnectionSettings using the device address

                I2cConnectionSettings settings = new I2cConnectionSettings(I2C_Default_Address, SSD1306_Default_Address);
                //Set the I2C bus speed of connection to fast mode
                //settings.BusSpeed = I2cBusSpeed.FastMode;
                ////Use the I2CBus device selector to create an advanced query syntax string
                //string aqs = I2cDevice.GetDeviceSelector(I2CControllerName);
                ////Use the Windows.Devices.Enumeration.DeviceInformation class to create a collection using the advanced query syntax string
                //DeviceInformationCollection dis = await DeviceInformation.FindAllAsync(aqs);
                ////Instantiate the the I2C device using the device id of the I2CBus and the I2CConnectionSettings
                //displayI2c = await I2cDevice.FromIdAsync(dis[0].Id, settings);

                displayI2c = I2cDevice.Create(settings);

                //Check if device was found
                if (displayI2c == null)
                {
                    Debug.WriteLine("Device not found");
                }
                else
                {
                    InitDisplay(configuration.ProceedOnFail);
                    configuration.FuncToCall?.Invoke();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace);
                throw;
            }
        }
		internal DisplayConfigAdapterInfo( DisplayConfiguration displayConfiguration, PathSourceInfo source, bool supportsVirtualMode )
			: base( source.AdapterId, source.Id, displayConfiguration.Topology )
		{
			int modeInfoIndex;
			if( supportsVirtualMode )
			{
				modeInfoIndex = source.ModeInfoIndex2;
				if( modeInfoIndex == PathSourceInfo.InvalidModeInfoIndex2 )
					modeInfoIndex = PathSourceInfo.InvalidModeInfoIndex;
			}
			else
				modeInfoIndex = source.ModeInfoIndex;

			if( modeInfoIndex > PathSourceInfo.InvalidModeInfoIndex && modeInfoIndex < displayConfiguration.ModeInfo.Count )
			{
				var mode = displayConfiguration.ModeInfo[ modeInfoIndex ];
				size = mode.Size;
				format = mode.Format;
				position = mode.Position;
			}

			isInUse = source.InUse;
		}
Esempio n. 21
0
            internal static IEnumerable <DisplayConfiguration> ParseSettingString(string value)
            {
                using (StringReader reader = new StringReader(value))
                {
                    string line = null;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line.Trim().Length == 0 ||
                            line.StartsWith("-"))
                        {
                            continue;
                        }

                        string[] tokens = line.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        if (tokens.Length != 2)
                        {
                            // TODO: Log warning
                            continue;
                        }

                        DisplayConfiguration dc = new DisplayConfiguration();
                        try
                        {
                            dc.TurnOnMonitorUri  = new Uri(tokens[0]);
                            dc.TurnOffMonitorUri = new Uri(tokens[1]);
                        }
                        catch (UriFormatException)
                        {
                            Logger.Instance.LogFormat(LogType.Warning, null, Properties.Resources.ParseConfigFileUriFormatError, line);
                            continue;
                        }

                        yield return(dc);
                    }
                }
            }
		public static DisplayConfigAdapterInfo GetDisplayConfigInfo( this DisplayAdapter adapter )
		{
			if( adapter == null )
				throw new ArgumentNullException( "adapter" );

			if( DisplayConfiguration.IsSupported )
			{
				if( currentConfiguration == null )
					currentConfiguration = DisplayConfiguration.Query( DisplayConfigRequest );
				else
					currentConfiguration.Refresh();

				var paths = currentConfiguration.PathInfo;
				for( var p = 0; p < paths.Count; ++p )
				{
					var path = paths[ p ];
					var source = path.SourceInfo;
					
					var sourceDeviceName = DisplayConfiguration.GetSourceGdiDeviceName( source );
					if( sourceDeviceName == adapter.DeviceIdentifier )
						return new DisplayConfigAdapterInfo( currentConfiguration, source, path.SupportsVirtualMode );
				}
			}

			return null;
		}
Esempio n. 23
0
        /// <summary>
        /// Pases command line arguments and store properties in attributes and display object
        /// </summary>
        /// <param name="args">Command line arguments</param>
        /// <param name="attributes">PingAttributes object to store propterties from arguments</param>
        /// <returns>bool based on if parsing was successful or not</returns>
        public static bool Parse(string[] args, ref PingAttributes attributes, ref DisplayConfiguration displayConfig)
        {
            int curArg = 0;

            // Loop through arguments
            try
            {
                // Check for any input arguments first because some of the arguments can early out the program before the
                // arguments get set.
                if (args.Contains("/ri") || args.Contains("-ri") || args.Contains("--ri") ||
                    args.Contains("/requireinput") || args.Contains("-requireinput") || args.Contains("--requireinput"))
                {
                    displayConfig.RequireInput = true;
                }

                checked
                {
                    // Loop through and parse all other arguments
                    for (int count = 0; count < args.Length; count++)
                    {
                        curArg = count;

                        switch (args[count])
                        {
                        case "/version":
                        case "-version":
                        case "--version":
                        case "/v":
                        case "-v":
                        case "--v":
                            ConsoleDisplay.Version();
                            Helper.CheckRecentVersion();
                            if (displayConfig.RequireInput)
                            {
                                Helper.WaitForUserInput();
                            }
                            Environment.Exit(0);
                            break;

                        case "/beep":
                        case "-beep":
                        case "--beep":
                        case "/b":
                        case "-b":
                        case "--b":
                            attributes.BeepMode = 1;

                            // ignore proceeding argument or if is last argument
                            if (args.Length < count + 1 || count + 1 == args.Length)
                            {
                                continue;
                            }
                            if (IsArgument(args[count + 1]) ||
                                args[count + 1].Contains("."))
                            {
                                continue;
                            }

                            int level = Convert.ToInt32(args[count + 1]);

                            if (level > 2 || level < 1)
                            {
                                ConsoleDisplay.Message("Invalid beep level, please use a number between 0 & 2");
                                throw new ArgumentFormatException();
                            }
                            attributes.BeepMode = level;
                            break;

                        case "/count":
                        case "-count":
                        case "--count":
                        case "/c":
                        case "-c":
                        case "--c":     // Ping count
                            attributes.Count = Convert.ToInt32(args[count + 1]);
                            break;

                        case "/infiite":
                        case "-infinite":
                        case "--infinite":
                        case "/t":
                        case "-t":
                        case "--t":     // Infinitely send
                            attributes.Continous = true;
                            break;

                        case "/timeout":
                        case "-timeout":
                        case "--timeout":
                        case "/w":
                        case "-w":
                        case "--w":     // Timeout
                            attributes.Timeout = Convert.ToInt32(args[count + 1]);
                            break;

                        case "/message":
                        case "-message":
                        case "--message":
                        case "/m":
                        case "-m":
                        case "--m":     // Message
                            if (args[count + 1].Contains("--") || args[count + 1].Contains('/') || args[count + 1].Contains("-"))
                            {
                                throw new ArgumentFormatException();
                            }
                            attributes.Message = args[count + 1];
                            break;

                        case "/ttl":
                        case "-ttl":
                        case "--ttl":
                        case "/i":
                        case "-i":
                        case "--i":     // Time To Live
                            int ttl = Convert.ToInt16(args[count + 1]);
                            if (ttl > 255)
                            {
                                ConsoleDisplay.Message("TTL has to be between 0 and 255");
                                throw new ArgumentFormatException();
                            }
                            attributes.Ttl = ttl;
                            break;

                        case "/interval":
                        case "-interval":
                        case "--interval":
                        case "/in":
                        case "-in":
                        case "--in":     // Interval
                            attributes.Interval = Convert.ToInt32(args[count + 1]);
                            if (attributes.Interval < 1)
                            {
                                ConsoleDisplay.Message("Ping interval cannot be less than 1ms");
                                throw new ArgumentFormatException();
                            }
                            break;

                        case "/type":
                        case "-type":
                        case "--type":
                        case "/pt":
                        case "-pt":
                        case "--pt":     // Ping type
                            var type = Convert.ToByte(args[count + 1]);
                            if (type > 255)
                            {
                                throw new ArgumentFormatException();
                            }
                            attributes.Type = type;
                            break;

                        case "/code":
                        case "-code":
                        case "--code":
                        case "/pc":
                        case "-pc":
                        case "--pc":     // Ping code
                            attributes.Code = Convert.ToByte(args[count + 1]);
                            break;

                        case "/displayConfigmsg":
                        case "-displayConfigmsg":
                        case "--displayConfigmsg":
                        case "/dm":
                        case "-dm":
                        case "--dm":     // displayConfig packet message
                            displayConfig.ShowMessages = true;
                            break;

                        case "/ipv4":
                        case "-ipv4":
                        case "--ipv4":
                        case "/4":
                        case "-4":
                        case "--4":     // Force ping with IPv4
                            if (attributes.UseICMPv6)
                            {
                                // Reset IPv6 force if already set
                                attributes.UseICMPv6 = false;
                            }
                            attributes.UseICMPv4 = true;
                            break;

                        case "/ipv6":
                        case "-ipv6":
                        case "--ipv6":
                        case "/6":
                        case "-6":
                        case "--6":     // Force ping with IPv6
                            if (attributes.UseICMPv4)
                            {
                                // Reset IPv4 force if already set
                                attributes.UseICMPv4 = false;
                            }
                            attributes.UseICMPv6 = true;
                            break;

                        case "/help":
                        case "-help":
                        case "--help":
                        case "/?":
                        case "-?":
                        case "--?":     // displayConfig help message
                            ConsoleDisplay.Help();

                            if (displayConfig.RequireInput)
                            {
                                Helper.WaitForUserInput();
                            }

                            Environment.Exit(0);
                            break;

                        case "/shorthand":
                        case "-shorthand":
                        case "--shorthand":
                        case "/sh":
                        case "-sh":
                        case "--sh":     // Use short hand messages
                            displayConfig.Short = true;
                            break;

                        case "/nocolor":
                        case "-nocolor":
                        case "--nocolor":
                        case "/nc":
                        case "-nc":
                        case "--nc":     // No color mode
                            displayConfig.NoColor = true;
                            break;

                        case "/decimals":
                        case "-decimals":
                        case "--decimals":
                        case "/dp":
                        case "-dp":
                        case "--dp":     // Decimal places
                            if (Convert.ToInt32(args[count + 1]) > 3 || Convert.ToInt32(args[count + 1]) < 0)
                            {
                                throw new ArgumentFormatException();
                            }
                            displayConfig.DecimalPlaces = Convert.ToInt32(args[count + 1]);
                            break;

                        case "/symbols":
                        case "-symbols":
                        case "--symbols":
                        case "/sym":
                        case "-sym":
                        case "--sym":
                            displayConfig.UseSymbols = true;
                            ConsoleDisplay.SetAsciiReplySymbolsTheme(0);

                            // ignore proceeding argument or if is last argument
                            if (args.Length < count + 1 || count + 1 == args.Length)
                            {
                                continue;
                            }
                            if (IsArgument(args[count + 1]) ||
                                args[count + 1].Contains("."))
                            {
                                continue;
                            }

                            // Change symbols theme if an argument is present
                            int theme = Convert.ToInt32(args[count + 1]);
                            ConsoleDisplay.SetAsciiReplySymbolsTheme(theme);
                            break;

                        case "/random":
                        case "-random":
                        case "--random":
                        case "/rng":
                        case "-rng":
                        case "--rng":
                            attributes.RandomMessage = true;
                            break;

                        case "/limit":
                        case "-limit":
                        case "--limit":
                        case "/l":
                        case "-l":
                        case "--l":
                            if (Convert.ToInt32(args[count + 1]) == 1)
                            {
                                displayConfig.ShowSummary = false;
                                displayConfig.ShowIntro   = false;
                            }
                            else if (Convert.ToInt32(args[count + 1]) == 2)
                            {
                                displayConfig.ShowSummary  = false;
                                displayConfig.ShowIntro    = false;
                                displayConfig.ShowReplies  = false;
                                displayConfig.ShowRequests = true;
                            }
                            else if (Convert.ToInt32(args[count + 1]) == 3)
                            {
                                displayConfig.ShowReplies  = false;
                                displayConfig.ShowRequests = false;
                            }
                            else
                            {
                                throw new ArgumentFormatException();
                            }
                            break;

                        case "/notimeout":
                        case "-notimeout":
                        case "--notimeout":
                        case "/nt":
                        case "-nt":
                        case "--nt":
                            displayConfig.ShowTimeouts = false;
                            break;

                        case "/timestamp":
                        case "-timestamp":
                        case "--timestamp":
                        case "/ts":
                        case "-ts":
                        case "--ts":     // displayConfig timestamp
                            if (count + 1 >= args.Length ||
                                IsArgument(args[count + 1]))
                            {
                                displayConfig.ShowFullTimeStamp = true;
                            }
                            else if (args[count + 1].ToLower() == "utc")
                            {
                                displayConfig.ShowtimeStampUTC = true;
                            }
                            else
                            {
                                displayConfig.ShowTimeStamp = true;
                            }
                            break;

                        case "/fulltimestamp":
                        case "-fulltimestamp":
                        case "--fulltimestamp":
                        case "/fts":
                        case "-fts":
                        case "--fts":     // displayConfig timestamp with date
                            if (count + 1 >= args.Length ||
                                IsArgument(args[count + 1]))
                            {
                                displayConfig.ShowFullTimeStamp = true;
                            }
                            else if (args[count + 1].ToLower() == "utc")
                            {
                                displayConfig.ShowFullTimeStampUTC = true;
                            }
                            else
                            {
                                displayConfig.ShowFullTimeStamp = true;
                            }
                            break;

                        case "/timing":
                        case "-timing":
                        case "--timing":
                        case "/ti":
                        case "-ti":
                        case "--ti":     // Timing option
                            switch (args[count + 1].ToLowerInvariant())
                            {
                            case "0":
                            case "paranoid":
                                attributes.Timeout  = 10000;
                                attributes.Interval = 300000;
                                break;

                            case "1":
                            case "sneaky":
                                attributes.Timeout  = 5000;
                                attributes.Interval = 120000;
                                break;

                            case "2":
                            case "quiet":
                                attributes.Timeout  = 5000;
                                attributes.Interval = 30000;
                                break;

                            case "3":
                            case "polite":
                                attributes.Timeout  = 3000;
                                attributes.Interval = 3000;
                                break;

                            case "4":
                            case "rimble":
                                attributes.Timeout  = 2000;
                                attributes.Interval = 750;
                                break;

                            case "5":
                            case "speedy":
                                attributes.Timeout  = 1500;
                                attributes.Interval = 500;
                                break;

                            case "6":
                            case "insane":
                                attributes.Timeout  = 750;
                                attributes.Interval = 100;
                                break;

                            case "7":
                            case "random":
                                attributes.RandomTiming  = true;
                                attributes.RandomMessage = true;
                                attributes.Interval      = Helper.RandomInt(5000, 100000);
                                attributes.Timeout       = 15000;
                                break;

                            default:         // Unknown timing type
                                throw new ArgumentFormatException();
                            }
                            break;

                        case "/request":
                        case "-request":
                        case "--request":
                        case "/requests":
                        case "-requests":
                        case "--requests":
                        case "/r":
                        case "-r":
                        case "--r":
                            displayConfig.ShowRequests = true;
                            break;

                        case "/quiet":
                        case "-quiet":
                        case "--quiet":
                        case "/q":
                        case "-q":
                        case "--q":
                            displayConfig.ShowOutput = false;
                            break;

                        case "/resolve":
                        case "-resolve":
                        case "--resolve":
                        case "/res":
                        case "-res":
                        case "--res":
                            displayConfig.UseResolvedAddress = true;
                            break;

                        case "/inputaddr":
                        case "-inputaddr":
                        case "--inputaddr":
                        case "/ia":
                        case "-ia":
                        case "--ia":
                            displayConfig.UseInputtedAddress = true;
                            break;

                        case "/buffer":
                        case "-buffer":
                        case "--buffer":
                        case "/rb":
                        case "-rb":
                        case "--rb":
                            int recvbuff = Convert.ToInt32(args[count + 1]);
                            if (recvbuff < 65000)
                            {
                                attributes.ReceiveBufferSize = recvbuff;
                            }
                            else
                            {
                                throw new ArgumentFormatException();
                            }
                            break;

                        case "/checksum":
                        case "-checksum":
                        case "--checksum":
                        case "/chk":
                        case "-chk":
                        case "--chk":
                            displayConfig.ShowChecksum = true;
                            break;

                        case "/dontfrag":
                        case "-dontfrag":
                        case "--dontfrag":
                        case "/df":
                        case "-df":
                        case "--df":
                            attributes.DontFragment = true;
                            break;

                        case "/log":
                        case "-log":
                        case "--log":
                        case "/f":
                        case "-f":
                        case "--f":
                            attributes.EnableLogging = true;

                            if (count + 1 >= args.Length ||
                                IsArgument(args[count + 1]))
                            {
                                attributes.LogFilePath = "";
                            }
                            else
                            {
                                attributes.LogFilePath = args[count + 1];
                            }

                            break;

                        case "/size":
                        case "-size":
                        case "--size":
                        case "/s":
                        case "-s":
                        case "--s":
                            int size = Convert.ToInt32(args[count + 1]);
                            if (size < 100000)
                            {
                                attributes.ArtificalMessageSize = size;
                            }
                            else
                            {
                                throw new ArgumentFormatException();
                            }
                            break;

                        case "/whois":
                        case "-whois":
                        case "--whois":     // Whois lookup
                            attributes.Operation = PingOperation.Whois;
                            break;

                        case "/whoami":
                        case "-whoami":
                        case "--whoami":     // Current computer location
                            attributes.Operation = PingOperation.Whoami;
                            break;

                        case "/location":
                        case "-location":
                        case "--location":
                        case "/loc":
                        case "-loc":
                        case "--loc":     // Location lookup
                            attributes.Operation = PingOperation.Location;
                            break;

                        case "/listen":
                        case "-listen":
                        case "--listen":
                        case "/li":
                        case "-li":
                        case "--li":     // Listen for ICMP packets
                            attributes.Operation = PingOperation.Listen;
                            break;

                        case "/graph":
                        case "-graph":
                        case "--graph":
                        case "/g":
                        case "-g":
                        case "--g":     // Graph view
                            attributes.Operation = PingOperation.Graph;
                            break;

                        case "/flood":
                        case "-flood":
                        case "--flood":
                        case "/fl":
                        case "-fl":
                        case "--fl":     // Flood
                            attributes.Operation = PingOperation.Flood;
                            break;

                        case "/scan":
                        case "-scan":
                        case "--scan":
                        case "/sc":
                        case "-sc":
                        case "--sc":     // Scan
                            attributes.Operation = PingOperation.Scan;
                            break;

                        default:
                            // Check for invalid argument
                            if (IsArgument(args[count]) &&
                                attributes.Operation != PingOperation.Scan &&     // (ignore if scanring) // TODO: Change this
                                (!Helper.IsURL(args[count]) && !Helper.IsIPv4Address(args[count])))
                            {
                                throw new InvalidArgumentException();
                            }
                            break;
                        }
                    }
                }
            }
            catch (IndexOutOfRangeException)
            {
                ConsoleDisplay.Error($"Missing argument parameter @ \"PowerPing >>>{args[curArg]}<<<\"");
                return(false);
            }
            catch (OverflowException)
            {
                ConsoleDisplay.Error($"Overflow while converting @ \"PowerPing {args[curArg]} >>>{args[curArg + 1]}<<<\"");
                return(false);
            }
            catch (InvalidArgumentException)
            {
                ConsoleDisplay.Error($"Invalid argument @ \"PowerPing >>>{args[curArg]}<<<\"");
                return(false);
            }
            catch (ArgumentFormatException)
            {
                ConsoleDisplay.Error($"Incorrect parameter for [{args[curArg]}] @ \"PowerPing {args[curArg]} >>>{args[curArg + 1]}<<<\"");
                return(false);
            }
            catch (Exception e)
            {
                ConsoleDisplay.Error($"An {e.GetType().ToString().Split('.').Last()} exception occured @ \"PowerPing >>>{args[curArg]}<<<\"");
                return(false);
            }
            return(true);
        }
Esempio n. 24
0
            internal static IEnumerable<DisplayConfiguration> ParseSettingString(string value)
            {
                using (StringReader reader = new StringReader(value))
                {
                    string line = null;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line.Trim().Length == 0
                            || line.StartsWith("-"))
                        {
                            continue;
                        }

                        string[] tokens = line.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        if (tokens.Length != 2)
                        {
                            // TODO: Log warning
                            continue;
                        }

                        DisplayConfiguration dc = new DisplayConfiguration();
                        try
                        {
                            dc.TurnOnMonitorUri = new Uri(tokens[0]);
                            dc.TurnOffMonitorUri = new Uri(tokens[1]);
                        }
                        catch (UriFormatException)
                        {
                            Logger.Instance.LogFormat(LogType.Warning, null, Properties.Resources.ParseConfigFileUriFormatError, line);
                            continue;
                        }

                        yield return dc;
                    }
                }
            }
		public static DisplayConfigMonitorInfo GetDisplayConfigInfo( this DisplayMonitor monitor )
		{
			if( monitor == null )
				throw new ArgumentNullException( "monitor" );

			if( DisplayConfiguration.IsSupported )
			{
				if( currentConfiguration == null )
					currentConfiguration = DisplayConfiguration.Query( DisplayConfigRequest );
				else
					currentConfiguration.Refresh();

				var paths = currentConfiguration.PathInfo;
				for( var p = 0; p < paths.Count; ++p )
				{
					var path = paths[ p ];
					var target = path.TargetInfo;
					var targetDeviceName = DisplayConfiguration.GetTargetDeviceName( target );
					if( monitor == GetMonitorByDevicePath( targetDeviceName.DevicePath ) )
					{
						if( !string.IsNullOrWhiteSpace( targetDeviceName.FriendlyName ) )
							monitor.DisplayName = targetDeviceName.FriendlyName;

						//var preferredMode = DisplayConfiguration.GetPreferredModeInfo( target );

						return new DisplayConfigMonitorInfo( currentConfiguration, target, targetDeviceName, path.SupportsVirtualMode );
					}
				}
			}

			return null;
		}
        public MainWindow()
        {
            InitializeComponent();

            MapEntity mapEntityGhost = new MapEntity
            {
                Description        = "Ghost",
                Icon               = null,
                DisplayText        = "G",
                ScoringWeight      = -100,
                DistributionWeight = 1
            };
            MapEntity mapEntityZombie = new MapEntity
            {
                Description        = "Zombie",
                Icon               = null,
                DisplayText        = "Z",
                ScoringWeight      = -10,
                DistributionWeight = 3
            };
            MapEntity mapEntityWall = new MapEntity
            {
                Description        = "Wall",
                Icon               = null,
                DisplayText        = "W",
                ScoringWeight      = 10,
                DistributionWeight = 2
            };
            MapEntity mapEntityExit = new MapEntity
            {
                Description   = "Exit",
                Icon          = null,
                DisplayText   = "Ex",
                ScoringWeight = 0,
                Multiplicity  = MapEntityMultiplicity.Single
            };


            DisplayConfiguration displayConfiguration = new DisplayConfiguration
            {
                Columns     = 5,
                GameTitle   = "Haunted House",
                MapEntities = new System.Collections.Generic.List <IMapEntity> {
                    mapEntityGhost, mapEntityExit, mapEntityWall, mapEntityZombie
                },
                Rows          = 5,
                MaxScore      = 100,
                MoveScore     = -5,
                ParentControl = myCanvas
            };

            IGameContext gameContext = new GameContext
            {
                DisplayConfiguration = displayConfiguration,
                InputConfiguration   = new InputConfiguration {
                    InputElement = this
                },
                IsTwoPlayer   = false,
                ParentControl = this.myCanvas,
            };

            myGameHost = GameFactory.CreateGameController(gameContext);

            IGameViewModel viewModel = myGameHost.GetGameViewModel();

            this.DataContext = viewModel;
        }
Esempio n. 27
0
        public MainWindow()
        {
            InitializeComponent();

            MapEntity mapEntityMine = new MapEntity
            {
                Description        = "Mine",
                Icon               = null,
                DisplayText        = "X",
                ScoringWeight      = -100,
                DistributionWeight = 1
            };
            MapEntity mapEntityTrench = new MapEntity
            {
                Description        = "Trench",
                Icon               = null,
                DisplayText        = "T",
                ScoringWeight      = -10,
                DistributionWeight = 3
            };
            MapEntity mapEntityEnemy = new MapEntity
            {
                Description        = "Enemy Soldier",
                Icon               = null,
                DisplayText        = "ES",
                ScoringWeight      = 10,
                DistributionWeight = 2
            };
            MapEntity mapEntityExit = new MapEntity
            {
                Description   = "Exit",
                Icon          = null,
                DisplayText   = "Ex",
                ScoringWeight = 0,
                Multiplicity  = MapEntityMultiplicity.Single
            };
            MapEntity mapEntityHill = new MapEntity
            {
                Description         = "Hill",
                Icon                = null,
                DisplayText         = "H",
                ScoringWeight       = -5,
                DistributionWeight  = 1,
                IsMoveAllowedOnThis = false
            };

            DisplayConfiguration displayConfiguration = new DisplayConfiguration
            {
                Columns     = 5,
                GameTitle   = "Tank Buster",
                MapEntities = new System.Collections.Generic.List <IMapEntity> {
                    mapEntityMine, mapEntityHill, mapEntityExit, mapEntityEnemy, mapEntityTrench
                },
                Rows          = 5,
                MaxScore      = 100,
                MoveScore     = -5,
                ParentControl = myCanvas
            };

            IGameContext gameContext = new GameContext
            {
                DisplayConfiguration = displayConfiguration,
                InputConfiguration   = new InputConfiguration {
                    InputElement = this
                },
                IsTwoPlayer   = false,
                ParentControl = this.myCanvas,
            };

            myGameHost = GameFactory.CreateGameController(gameContext);

            IGameViewModel viewModel = myGameHost.GetGameViewModel();

            this.DataContext = viewModel;
        }
Esempio n. 28
0
 public ConsoleMessageHandler(DisplayConfiguration config, CancellationToken token)
 {
     DisplayConfig = config;
     Token         = token;
 }
Esempio n. 29
0
        private static void GetDisplayConfigInfo(DisplayAdapter adapter)
        {
            var                     paths = configuration.Paths;
            var                     pMax  = paths.Count;
            PathInfo                path;
            PathSourceInfo          source;
            PathTargetInfo          target;
            TargetDeviceDescription desc;
            DisplayMonitor          monitor;
            int                     index;

            for (var p = 0; p < pMax; ++p)
            {
                path   = paths[p];
                source = path.SourceInfo;

                if (source == PathSourceInfo.Empty)
                {
                    continue;
                }

                if (adapter.DeviceName.Equals(DisplayConfiguration.GetSourceGDIDeviceName(source), StringComparison.OrdinalIgnoreCase))
                {
                    adapter.identifier = source.Identifier;
                    if (path.SupportsVirtualMode)
                    {
                        adapter.cloneGroupId = source.CloneGroupId;
                        index = source.ModeInfoIndex2;
                    }
                    else
                    {
                        adapter.cloneGroupId = -1;
                        index = source.ModeInfoIndex;
                    }
                    //if( index == PathSourceInfo.InvalidModeInfoIndex )
                    //	adapter.currentModeFormat = PixelFormat.Undefined;
                    //else
                    //	adapter.currentModeFormat = configuration.DisplayModes[ index ].Format;

                    target = path.TargetInfo;
                    if (target == PathTargetInfo.Empty)
                    {
                        continue;
                    }

                    desc    = DisplayConfiguration.GetTargetDeviceDescription(target);
                    monitor = adapter.GetMonitorByDevicePath(desc.DevicePath);
                    if (monitor != null)
                    {
                        monitor.identifier = target.Identifier;
                        if (!string.IsNullOrWhiteSpace(desc.FriendlyName))
                        {
                            monitor.DisplayName = desc.FriendlyName;
                        }

                        monitor.videoOutputTechnology = target.OutputTechnology;
                        monitor.scaling          = target.Scaling;
                        monitor.refreshRate      = target.RefreshRate;
                        monitor.scanlineOrdering = target.ScanlineOrdering;
                        index = path.SupportsVirtualMode ? target.ModeInfoIndex2 : target.ModeInfoIndex;
                        if (index != PathTargetInfo.InvalidModeInfoIndex)
                        {
                            monitor.videoSignalInfo = configuration.DisplayModes[index].VideoSignalInformation;
                        }
                        else
                        {
                            monitor.videoSignalInfo = VideoSignalInfo.Empty;
                        }
                        monitor.Orientation = target.Rotation;

                        monitor.connectorInstance = desc.ConnectorInstance;
                    }
                }
            }
        }
Esempio n. 30
0
    ////////////////////////////
    //// Display Configuration
    ////////////////////////////

    private void DisplayConfigs()
    {
        //' access the display system from the database object

        Database    db    = Application.DocumentManager.MdiActiveDocument.Database;
        Transaction trans = db.TransactionManager.StartTransaction();

        try
        {
            // Access the display system from the document object
            DictionaryDisplayConfiguration dictDisplayConfigs = new DictionaryDisplayConfiguration(db);

            // The total number of display configurations registered.
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("There are " + dictDisplayConfigs.Records.Count + " display configs:\n");

            // List them
            foreach (ObjectId dcId in dictDisplayConfigs.Records)
            {
                DisplayConfiguration dc = trans.GetObject(dcId, OpenMode.ForWrite) as DisplayConfiguration;
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Name : " + dc.Name + "\n" +
                                                                                  "Description :  " + dc.Description + "\n");
            }

            // Add a new config with the name "MyConfig" with a description in it.
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\nLet's add a new DisplayConfiguration:\n");
            DisplayConfiguration displayconfig = new DisplayConfiguration();
            displayconfig.Description = "This is MyConfig";
            if (!dictDisplayConfigs.Has("MyConfig", trans))
            {
                dictDisplayConfigs.AddNewRecord("MyConfig", displayconfig);
                trans.AddNewlyCreatedDBObject(displayconfig, true);
            }

            // Add another one "FORUSE1"
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(displayconfig.Name + " : " + displayconfig.Description + "\n");
            DisplayConfiguration displayconfig1 = new DisplayConfiguration();
            displayconfig1.Description = "This is for use";
            if (!dictDisplayConfigs.Has("FORUSE1", trans))
            {
                dictDisplayConfigs.AddNewRecord("FORUSE1", displayconfig1);
                trans.AddNewlyCreatedDBObject(displayconfig1, true);
            }

            //    rename MyConfig to a new name MyNewConfigureXxx
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\nLet's rename this new DisplayConfiguration:\n");
            string newName = GetNewName();
            dictDisplayConfigs.Rename("MyConfig", newName, trans);
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("After Renamed:\nName: " + displayconfig.Name + "\nDescription: " + displayconfig.Description + "\n");


            //    report the total number of display config again.
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("There are " + dictDisplayConfigs.Records.Count + " display configurations now.\n");

            //    the ObjectId of the new disp config?
            ObjectId nid = dictDisplayConfigs.GetAt(newName);
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("The current ObjectId for new display configuration is:" + nid.ToString() + "\n");

            //    the current active config?
            DisplayRepresentationManager drm      = new DisplayRepresentationManager(db);
            ObjectId             currentDisConfId = drm.DisplayConfigurationIdForCurrentViewport;
            DisplayConfiguration currentDisConf   = trans.GetObject(currentDisConfId, OpenMode.ForRead) as DisplayConfiguration;
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("The Current DisplayConfiguration is " + currentDisConf.Name + "\n");
            ListDisplayConfig(currentDisConf);

            //    create a new disp config with more detailed information.
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Let's create a new DisplayConfiguration for detail:\n");
            DisplayConfiguration newDc = CreateDisplayConfig();

            //    print it out
            ListDisplayConfig(newDc);

            trans.Commit();
        }
        catch (System.Exception e)
        {
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Exception: " + e.Message + "\n");
            trans.Abort();
        }
        finally
        {
            trans.Dispose();
        }
    }
Esempio n. 31
0
        /// <summary>
        /// 获取系统信息
        /// </summary>
        /// <returns>系统信息</returns>
        public static string GetSystemInformation()
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                sb.AppendLine("ClickOnce应用程序部署版本:" + ApplicationDeployment.CurrentDeployment.CurrentVersion);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                sb.AppendLine(string.Format("非ClickOnce应用程序。应用程序版本:{0}", App.AppVersion));
            }

            sb.AppendLine("DoubanFM.exe版本:" + GetAssemblyVersion(typeof(App)));
            sb.AppendLine("DoubanFM.Core.dll版本:" + GetAssemblyVersion(typeof(Player)));
            sb.AppendLine("DoubanFM.Bass.dll版本:" + GetAssemblyVersion(typeof(Bass.BassEngine)));
            sb.AppendLine("NotifyIconWpf.dll版本:" + GetAssemblyVersion(typeof(Hardcodet.Wpf.TaskbarNotification.TaskbarIcon)));
            sb.AppendLine("DwmHelper.dll版本:" + GetAssemblyVersion(typeof(Kfstorm.DwmHelper.DwmHelper)));

            try
            {
                var os = DoubanFM.Wmi.OperatingSystem.GetInstance();
                sb.AppendLine("操作系统:" + string.Format("{0} ({1})", os.Caption, Environment.OSVersion));
            }
            catch
            {
                try { sb.AppendLine("操作系统:" + Environment.OSVersion); }
                catch { }
            }
            try
            {
                sb.AppendLine("工作目录:" + Environment.CurrentDirectory);
            }
            catch { }
            try
            {
                sb.AppendLine("命令行:" + Environment.CommandLine);
            }
            catch { }
            try
            {
                sb.AppendLine("Temp文件夹:" + System.IO.Path.GetTempPath());
            }
            catch { }
            try
            {
                sb.AppendLine("是否是64位操作系统:" + (Environment.Is64BitOperatingSystem ? "是" : "否"));
            }
            catch { }
            try
            {
                sb.AppendLine("是否是64位进程:" + (Environment.Is64BitProcess ? "是" : "否"));
            }
            catch { }
            try
            {
                sb.AppendLine("处理器数:" + Environment.ProcessorCount);
            }
            catch { }
            try
            {
                sb.AppendLine("系统目录:" + Environment.SystemDirectory);
            }
            catch { }
            try
            {
                sb.AppendLine("CLR版本:" + Environment.Version);
            }
            catch { }
            try
            {
                sb.AppendLine("工作集大小:" + Environment.WorkingSet);
            }
            catch { }
            try
            {
                sb.AppendLine("屏幕分辨率:" + SystemParameters.PrimaryScreenWidth + "x" + SystemParameters.PrimaryScreenHeight);
            }
            catch { }
            try
            {
                sb.AppendLine("工作区大小:" + SystemParameters.WorkArea.Width + "x" + SystemParameters.WorkArea.Height);
            }
            catch { }
            try
            {
                Processor[] processors = Processor.GetInstances();
                foreach (var processor in processors)
                {
                    sb.AppendLine("处理器:" + processor.Name);
                }
            }
            catch { }
            try
            {
                PhysicalMemory[] memories   = PhysicalMemory.GetInstances();
                ulong            memorySize = 0;
                foreach (var memory in memories)
                {
                    memorySize += memory.Capacity;
                }
                sb.AppendLine("内存:" + PhysicalMemory.FormatBytes(memorySize));
            }
            catch { }
            try
            {
                DisplayConfiguration[] displayes = DisplayConfiguration.GetInstances();
                foreach (var display in displayes)
                {
                    sb.AppendLine("显卡:" + display.DeviceName);
                }
            }
            catch { }
            try
            {
                SoundDevice[] devices = SoundDevice.GetInstances();
                foreach (var device in devices)
                {
                    sb.AppendLine("声卡:" + device.Name);
                }
            }
            catch { }

            return(sb.ToString());
        }
		//private static DisplayConfiguration registryConfiguration;



		/// <summary>Refreshes the device list and states, and raises events.</summary>
		public static void Refresh()
		{
			var removedAdapters = new List<string>( adaptersByDeviceName.Keys );
			var addedAdapters = new List<string>();
			var adaptersToRefresh = new List<DisplayDevice>( removedAdapters.Count );
			var primaryAdapterChanged = false;

			DisplayAdapter adapter;
			var displayDevices = DisplayAdapter.EnumDisplayDevices( null, false );
			for( var a = 0; a < displayDevices.Count; a++ )
			{
				var displayDevice = displayDevices[ a ];

				if( adaptersByDeviceName.TryGetValue( displayDevice.DeviceName, out adapter ) )
				{
					adaptersToRefresh.Add( displayDevice );
					removedAdapters.Remove( adapter.DeviceIdentifier );
				}
				else
				{
					adapter = new DisplayAdapter( displayDevice );
					adaptersByDeviceName.Add( adapter.DeviceIdentifier, adapter );
					addedAdapters.Add( adapter.DeviceIdentifier );
				}

				if( adapter.State.HasFlag( AdapterStateIndicators.PrimaryDevice ) && ( primaryAdapterDeviceName != adapter.DeviceIdentifier ) )
				{
					primaryAdapterChanged = ( primaryAdapterDeviceName != null );
					primaryAdapterDeviceName = displayDevice.DeviceName;
				}
			}


			if( DisplayConfiguration.IsSupported )
			{
				if( currentConfiguration == null )
					currentConfiguration = DisplayConfiguration.Query( DisplayConfigRequest );
				else
					currentConfiguration.Refresh();
			}


			if( removedAdapters.Count > 0 )
			{
				var adapterRemovedEvent = AdapterRemoved;
				while( removedAdapters.Count > 0 )
				{
					var s = removedAdapters[ 0 ];
					removedAdapters.RemoveAt( 0 );

					adapter = adaptersByDeviceName[ s ];
					adaptersByDeviceName.Remove( s );

					adapter.OnRemoved();
					if( adapterRemovedEvent != null )
						adapterRemovedEvent.Invoke( null, new DisplayDeviceEventArgs( adapter.DeviceIdentifier ) );
				}
			}

			if( addedAdapters.Count > 0 )
			{
				var adapterAddedEvent = AdapterAdded;
				while( addedAdapters.Count > 0 )
				{
					if( adapterAddedEvent != null )
						adapterAddedEvent.Invoke( null, new DisplayDeviceEventArgs( addedAdapters[ 0 ] ) );
					addedAdapters.RemoveAt( 0 );
				}
			}


			while( adaptersToRefresh.Count > 0 )
			{
				var device = adaptersToRefresh[ 0 ];
				if( adaptersByDeviceName.TryGetValue( device.DeviceName, out adapter ) )
					adapter.Refresh( device );
				adaptersToRefresh.RemoveAt( 0 );
			}


			if( primaryAdapterChanged && PrimaryAdapterChanged != null )
				PrimaryAdapterChanged.Invoke( null, EventArgs.Empty );

			isInitialized = true;
		}