コード例 #1
0
ファイル: Main.cs プロジェクト: forksnd/Blam_BSP
        private void tscbPluginSet_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tscbPluginSet.Focused)
            {
                RegistryAccess.setValue(Registry.CurrentUser,
                                        RegistryAccess.RegPaths.Halo2 + "PluginSets\\",
                                        "",
                                        tscbPluginSet.SelectedItem);
            }
            Prefs.pathPluginsFolder = Globals.PluginSetSelector.getPath(tscbPluginSet.SelectedItem.ToString());

            // Make sure to reload all plugins!
            HaloMap.Plugins.IFPHashMap.H1IFPHash.Clear();
            HaloMap.Plugins.IFPHashMap.H2IFPHash.Clear();

            foreach (MapForm mf in this.MdiChildren)
            {
                if (mf.map.SelectedMeta != null)
                {
                    mf.map.SelectedMeta.type = string.Empty;
                    mf.LoadMeta(mf.map.SelectedMeta.TagIndex);
                    // Reload meta tag type
                }
            }
        }
コード例 #2
0
ファイル: JUDGE_STATUS.cs プロジェクト: oneshadab/UVA-Arena
        private void submissionStatus_HyperlinkClicked(object sender, BrightIdeasSoftware.HyperlinkClickedEventArgs e)
        {
            JudgeStatus list = (JudgeStatus)e.Model;

            if (e.Column == pnumSUB || e.Column == ptitleSUB)
            {
                Interactivity.ShowProblem(list.pnum);
            }
            else if (e.Column == unameSUB)
            {
                if (LocalDatabase.ContainsUser(list.uname))
                {
                    Interactivity.ShowUserStat(list.uname);
                }
                else
                {
                    if (MessageBox.Show("Add \"" + list.uname + "\" to your favorite list?", "Add User",
                                        MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        return;
                    }
                    RegistryAccess.AddUserid(list.uname, list.uid.ToString());
                    Interactivity.ShowUserStat(list.uname);
                }
            }
        }
コード例 #3
0
        public void SetRegistryPermissionsBySIDTest()
        {
            string builtInUsersSID = "S-1-5-32-545";

            if (Registry.LocalMachine.OpenSubKey("Software\\TestKey") != null)
            {
                Registry.LocalMachine.DeleteSubKeyTree("Software\\TestKey");
            }

            try
            {
                RegistryKey registryKey    = Registry.LocalMachine.CreateSubKey("Software\\TestKey");
                RegistryKey subRegistryKey = registryKey.CreateSubKey("TestSubKey");
                subRegistryKey.SetValue("TestValue", "Pork Muffins!");

                Assert.IsFalse(RegistryAccess.DoesUserHaveAccess(registryKey, builtInUsersSID, RegistryRights.FullControl));
                Assert.IsFalse(RegistryAccess.DoesUserHaveAccess(subRegistryKey, builtInUsersSID, RegistryRights.FullControl));

                RegistryAccess.SetUserAccessBySID(registryKey, builtInUsersSID, RegistryRights.FullControl);

                Assert.IsTrue(RegistryAccess.DoesUserHaveAccess(registryKey, builtInUsersSID, RegistryRights.FullControl));
                Assert.IsTrue(RegistryAccess.DoesUserHaveAccess(subRegistryKey, builtInUsersSID, RegistryRights.FullControl));
            }
            finally
            {
                if (Registry.LocalMachine.OpenSubKey("Software\\TestKey") != null)
                {
                    Registry.LocalMachine.DeleteSubKeyTree("Software\\TestKey");
                }
            }
        }
コード例 #4
0
        /// <summary>
        /// Attempt to pick up possible application serial numbers from the remote system registry
        /// </summary>
        /// <param name="remoteHost">Name of the computer to connect to, NULL if the local computer</param>
        /// <returns></returns>
        public int Detect(String remoteHost)
        {
            // Try and open the (remote) registry.
            RegistryKey rootKey;
            int         status = new RegistryAccess().OpenRegistry(Registry.LocalMachine, remoteHost, out rootKey);

            // Pre-populate the dictionary of product GUIDs / serial numbers with the data recovered above
            this.FillGuidDictionary(rootKey);

            // ...now do the actual detection by scanning various rgeistry keys
            try
            {
                RegistryKey softwareKey;
                this._currentDepth = 0;
                softwareKey        = rootKey.OpenSubKey("Software");
                if (softwareKey != null)
                {
                    this.FindAllProductSerials(softwareKey);
                    softwareKey.Close();
                }
            }
            catch (Exception)
            {
            }

            this.ReadSerials(rootKey);
            rootKey.Close();
            return(base.Count);
        }
コード例 #5
0
ファイル: MareRegHandler.cs プロジェクト: Q-Sharp/MARE
        public void LoadReg()
        {
            AllGFX?.Clear();

            int i  = 0;
            var sk = RegistryAccess.OpenSubKey(sMainReg);

            var cfs = sk.GetSubKeyNames();

            foreach (var cf in cfs)
            {
                try
                {
                    int.Parse(cf);

                    var cr = sk.OpenSubKey(cf, false);
                    var a  = cr.GetValue("KMD_EnableInternalLargePage", null) as int?;
                    var b  = cr.GetValue("EnableCrossFireAutoLink", null) as int?;
                    var c  = cr.GetValue("EnableUlps", null) as int?;
                    var d  = cr.GetValue("DriverDesc", null) as string;

                    AllGFX.Add(new GFX(i, a, b, c, d));
                    i++;
                }
                catch (SecurityException)
                {
                    MessageBox.Show("This tool needs admin rights!");
                    break;
                }
                catch (Exception)
                {
                    continue;
                }
            }
        }
コード例 #6
0
ファイル: Internet.cs プロジェクト: maestrofx/UVA-Arena
        private static void __DownloadUseridCompleted(DownloadTask task)
        {
            string uid  = (string)task.Result;
            string name = (string)task.Token;

            task.Status = ProgressStatus.Failed;
            if (string.IsNullOrEmpty(uid))
            {
                task.Error = new Exception("Connection error. Retry please.");
            }
            else if (uid.Trim() == "0")
            {
                task.Error = new Exception(name + " doesn't exist.");
            }
            else if (task.Error == null)
            {
                task.Status = ProgressStatus.Completed;
            }

            if (task.Status == ProgressStatus.Completed)
            {
                RegistryAccess.SetUserid(name, uid);
                string msg = "Username downloaded : {0} = {1}";
                Interactivity.SetStatus(string.Format(msg, name, uid));
            }
        }
コード例 #7
0
ファイル: Profile.cs プロジェクト: xplusplus/ASCOMPlatform
        /// <summary>
        ///     ''' Disposes of resources used by the profile object - called by IDisposable interface
        ///     ''' </summary>
        ///     ''' <param name="disposing"></param>
        ///     ''' <remarks></remarks>
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposedValue)
            {
                if (disposing)
                {
                }

                if (!(ProfileStore == null))
                {
                    ProfileStore.Dispose();
                    ProfileStore = null;
                }
                if (!(TL == null))
                {
                    try
                    {
                        TL.LogMessage("Dispose", "Profile Dispose has been Called.");
                    }
                    catch
                    {
                    } // Clean up the logger
                    TL.Enabled = false;
                    TL.Dispose();
                    TL = null;
                }
            }
            this.disposedValue = true;
        }
コード例 #8
0
        public void SetRegistryPermissionsTest()
        {
            if (Registry.LocalMachine.OpenSubKey("Software\\TestKey") != null)
            {
                Registry.LocalMachine.DeleteSubKeyTree("Software\\TestKey");
            }

            try
            {
                RegistryKey registryKey    = Registry.LocalMachine.CreateSubKey("Software\\TestKey");
                RegistryKey subRegistryKey = registryKey.CreateSubKey("TestSubKey");
                subRegistryKey.SetValue("TestValue", "Pork Muffins!");

                Assert.IsFalse(RegistryAccess.DoesUserHaveAccess(registryKey, "BUILTIN\\Users", RegistryRights.FullControl));
                Assert.IsFalse(RegistryAccess.DoesUserHaveAccess(subRegistryKey, "BUILTIN\\Users", RegistryRights.FullControl));

                RegistryAccess.SetUserAccessByUserName(registryKey, "BUILTIN\\Users", RegistryRights.FullControl);

                Assert.IsTrue(RegistryAccess.DoesUserHaveAccess(registryKey, "BUILTIN\\Users", RegistryRights.FullControl));
                Assert.IsTrue(RegistryAccess.DoesUserHaveAccess(subRegistryKey, "BUILTIN\\Users", RegistryRights.FullControl));
            }
            finally
            {
                if (Registry.LocalMachine.OpenSubKey("Software\\TestKey") != null)
                {
                    Registry.LocalMachine.DeleteSubKeyTree("Software\\TestKey");
                }
            }
        }
コード例 #9
0
ファイル: USER_STAT.cs プロジェクト: oneshadab/UVA-Arena
        void webClient2_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (this.IsDisposed)
            {
                return;
            }
            if (e.Cancelled)
            {
                return;
            }

            UserRanklist currentRank = null;

            try
            {
                if (e.Error != null)
                {
                    throw e.Error;
                }

                string result = System.Text.Encoding.UTF8.GetString(e.Result);

                if (worldRanks != null)
                {
                    worldRanks.Clear();
                }
                worldRanks = JsonConvert.DeserializeObject <List <UserRanklist> >(result);

                foreach (UserRanklist usub in worldRanks)
                {
                    if (LocalDatabase.ContainsUser(usub.username))
                    {
                        RegistryAccess.SetUserRank(usub);
                        if (usub.username == currentUser.uname)
                        {
                            currentRank = usub;
                        }
                    }
                }

                worldRanklist.SetObjects(worldRanks);
                worldRanklist.Sort(rankRANK, SortOrder.Ascending);


                Interactivity.SetStatus(currentUser.uname + "'s rank-list downloaded.");
                Logger.Add("World rank downloaded - " + currentUser.uname, "World Rank | webClient2_DownloadDataCompleted");
            }
            catch (Exception ex)
            {
                TaskQueue.AddTask(new TaskQueue.Function2(ShowWorldRank), e.UserState, 500);
                Interactivity.SetStatus("Rank-list download failed due to an error. Please try again.");
                Logger.Add(ex.Message, "World Rank | webClient2_DownloadDataCompleted");
            }

            if ((int)e.UserState == -1)
            {
                BringUserToMiddle(currentRank);
            }
        }
コード例 #10
0
ファイル: Profile.cs プロジェクト: xplusplus/ASCOMPlatform
 /// <summary>
 ///     ''' Create a new profile object ignoring profile not found exceptions if generated
 ///     ''' </summary>
 ///     ''' <param name="IgnoreExceptions">Ignore ProfileNotFound exceptions</param>
 ///     ''' <remarks></remarks>
 public Profile(bool IgnoreExceptions) : base()
 {
     ProfileStore  = new RegistryAccess(IgnoreExceptions); // Get access to the profile store
     m_sDeviceType = "Telescope";
     TL            = new TraceLogger("", "Profile");
     TL.Enabled    = GetBool(TRACE_PROFILE, TRACE_PROFILE_DEFAULT); // Get enabled / disabled state from the user registry
     TL.LogMessage("New", "Trace logger created OK - Ignoring any ProfileNotFound exceptions");
 }
コード例 #11
0
 /// <summary>
 /// For those who wish to not have settings stored in their registry, allow them to remove it.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnClearRegistry_Click(object sender, EventArgs e)
 {
     if (MessageBox.Show("This will remove all Halo 2 entires from the registry. Are you sure you wish to continue?",
                         "Remove Halo 2 Registry Entries?",
                         MessageBoxButtons.YesNo) == DialogResult.Yes)
     {
         RegistryAccess.removeKey(Registry.CurrentUser, RegistryAccess.RegPaths.Halo2);
     }
 }
コード例 #12
0
ファイル: Profile.cs プロジェクト: xplusplus/ASCOMPlatform
        private bool disposedValue = false;        // To detect redundant calls

        /// <summary>
        ///     ''' Create a new Profile object
        ///     ''' </summary>
        ///     ''' <remarks></remarks>
        public Profile() : base()
        {
            ProfileStore  = new RegistryAccess(ERR_SOURCE_PROFILE); // Get access to the profile store
            m_sDeviceType = "Telescope";
            TL            = new TraceLogger("", "Profile");
            // Profile trace logging disabled because it has not been required for many years
            TL.Enabled = GetBool(TRACE_PROFILE, TRACE_PROFILE_DEFAULT); // Get enabled / disabled state from the user registry
            TL.LogMessage("New", "Trace logger created OK");
        }
コード例 #13
0
        public static void Main()
        {
            // Enable nice styles in XP/Vista/7.
            Application.EnableVisualStyles();

            // Store title which can be shown in all message boxes etc.
            AppGlobals.AppName = $"{Application.ProductName} {AppGlobals.AppVersion()}";

            // Test for existence of database.
            bool   databaseExists = false;
            string databasePath   = $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\\RoadMusic\\RoadMusic.db";

            // Set database connection string across whole app.
            DatabaseSettings.DatabasePath     = databasePath;
            DatabaseSettings.ConnectionString = $"Data Source={databasePath}";

            // If database not found...
            if (!File.Exists(databasePath))
            {
                // Try to create a blank database.
                try
                {
                    DbCreate.CreateDatabase(databasePath);

                    // Database now exists.
                    databaseExists = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"{ex.Message}  The program cannot start.", AppGlobals.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                // Database already exists.
                databaseExists = true;
            }

            // Only start the app if the database exists...
            if (databaseExists)
            {
                // Set where registry access happens across whole app.
                RegistryAccess.SetSoftwareKey($"Software\\{Application.ProductName}");

                // Show the main form.
                try
                {
                    Application.Run(new MainForm());
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Sorry, a fatal error occurred : {ex.Message}", AppGlobals.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
コード例 #14
0
        public void Process()
        {
            LastSID = 0;
            uid     = LocalDatabase.GetUserid(uname);

            submissions = new List <UserSubmission>();
            TryList     = new Dictionary <long, UserSubmission>();
            sidToSub    = new Dictionary <long, UserSubmission>();

            ProcessListData(subs);
            RegistryAccess.SetUserid(uname, uid);
        }
コード例 #15
0
        /// <summary>
        /// Load from app config; override with command line if present
        /// </summary>
        /// <returns></returns>
        private Boolean LoadParameters()
        {
            Boolean returnValue = default(Boolean);

#if USE_CONFIG_FILEPATH
            String _settingsFilename = default(String);
#endif

            try
            {
                if ((Program.Filename != null) && (Program.Filename != SettingsController <MVCSettings> .FILE_NEW))
                {
                    //got filename from command line
                    //DEBUG:filename coming in is being converted/passed as DOS 8.3 format equivalent
                    if (!RegistryAccess.ValidateFileAssociation(Application.ExecutablePath, "." + MVCSettings.FileTypeExtension))
                    {
                        throw new ApplicationException(String.Format("Settings filename not associated: '{0}'.\nCheck filename on command line.", Program.Filename));
                    }
                    //it passed; use value from command line
                }
                else
                {
#if USE_CONFIG_FILEPATH
                    //get filename from app.config
                    if (!Configuration.ReadString("SettingsFilename", out _settingsFilename))
                    {
                        throw new ApplicationException(String.Format("Unable to load SettingsFilename: {0}", "SettingsFilename"));
                    }
                    if ((_settingsFilename == null) || (_settingsFilename == SettingsController <MVCSettings> .FILE_NEW))
                    {
                        throw new ApplicationException(String.Format("Settings filename not set: '{0}'.\nCheck SettingsFilename in app config file.", _settingsFilename));
                    }
                    //use with the supplied path
                    SettingsController <MVCSettings> .Filename = _settingsFilename;

                    if (Path.GetDirectoryName(_settingsFilename) == String.Empty)
                    {
                        //supply default path if missing
                        SettingsController <MVCSettings> .Pathname = PathExtensions.WithTrailingSeparator(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
                    }
#endif
                }

                returnValue = true;
            }
            catch (Exception ex)
            {
                Log.Write(ex, MethodBase.GetCurrentMethod(), EventLogEntryType.Error);
                //throw;
            }
            return(returnValue);
        }
コード例 #16
0
    // Method to store the intervals (in percent complete) from the current invocation of
    // the splash screen to the registry.
    private void StoreIncrements()
    {
        string sPercent = "";
        double dblElapsedMilliseconds = ElapsedMilliSeconds();

        for (int i = 0; i < m_alActualTimes.Count; i++)
        {
            sPercent += ((double)m_alActualTimes[i] / dblElapsedMilliseconds).ToString("0.####", System.Globalization.NumberFormatInfo.InvariantInfo) + " ";
        }

        RegistryAccess.SetStringRegistryValue(REGVALUE_PB_PERCENTS, sPercent);

        m_dblPBIncrementPerTimerInterval = 1.0 / (double)m_iActualTicks;
        RegistryAccess.SetStringRegistryValue(REGVALUE_PB_MILISECOND_INCREMENT, m_dblPBIncrementPerTimerInterval.ToString("#.000000", System.Globalization.NumberFormatInfo.InvariantInfo));
    }
コード例 #17
0
ファイル: FormMain.cs プロジェクト: cuplexProjects/C-Projects
        private void SaveApplicationSettings()
        {
            RegistryAccess registryAccess = new RegistryAccess(Application.ProductName);

            applicationSettings.ProcessDescriptionFilter = txtProcessDescriptionFilter.Text;

            try
            {
                registryAccess.SaveObjectToRegistry(applicationSettings);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #18
0
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();

            try
            {
                if (IsOnMe)
                {
                    RegistryAccess.TrySetValue(LastNavigatedPageRegKey, GetType().Name);
                }
                await CloseAsync(LifecycleEvents.Suspending).ConfigureAwait(false);
            }
            finally
            {
                deferral.Complete();
            }
        }
コード例 #19
0
ファイル: UsageEmailDialog.cs プロジェクト: sillsdev/WorldPad
        /// <summary>
        /// if you call this every time the application starts, it will send reports on those launches
        /// (e.g. {1, 10}) that are listed in the launches parameter.  It will get version number and name out of the application.
        /// </summary>
        public static void DoTrivialUsageReport(string emailAddress, string topMessage, int[] launches)
        {
            int launchCount = int.Parse(RegistryAccess.GetStringRegistryValue("launches", "0"));

            foreach (int launch in launches)
            {
                if (launch == launchCount)
                {
                    // Set the Application label to the name of the app
                    Assembly assembly = Assembly.GetEntryAssembly();
                    string   version  = Application.ProductVersion;
                    if (assembly != null)
                    {
                        object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
                        version = (attributes != null && attributes.Length > 0) ?
                                  ((AssemblyFileVersionAttribute)attributes[0]).Version : Application.ProductVersion;
                    }

                    using (UsageEmailDialog d = new SIL.Utils.UsageEmailDialog())
                    {
                        d.TopLineText  = topMessage;
                        d.EmailAddress = emailAddress;
                        d.EmailSubject = string.Format("{0} {1} Report {2} Launches", Application.ProductName, version, launchCount);
                        System.Text.StringBuilder bldr = new System.Text.StringBuilder();
                        bldr.AppendFormat("<report app='{0}' version='{1}'>", Application.ProductName, version);
                        bldr.AppendFormat("<stat type='launches' value='{0}'/>", launchCount);
                        if (launchCount > 1)
                        {
                            int val = RegistryAccess.GetIntRegistryValue("NumberOfSeriousCrashes", 0);
                            bldr.AppendFormat("<stat type='NumberOfSeriousCrashes' value='{0}'/>", val);
                            val = RegistryAccess.GetIntRegistryValue("NumberOfAnnoyingCrashes", 0);
                            bldr.AppendFormat("<stat type='NumberOfAnnoyingCrashes' value='{0}'/>", val);
                            int    csec     = RegistryAccess.GetIntRegistryValue("TotalAppRuntime", 0);
                            int    cmin     = csec / 60;
                            string sRuntime = String.Format("{0}:{1:d2}:{2:d2}",
                                                            cmin / 60, cmin % 60, csec % 60);
                            bldr.AppendFormat("<stat type='TotalAppRuntime' value='{0}'/>", sRuntime);
                        }
                        bldr.AppendFormat("</report>");
                        d.Body = bldr.ToString();
                        d.ShowDialog();
                    }
                    break;
                }
            }
        }
コード例 #20
0
        private bool ForceTimer(bool CurrentIsForm)
        {
            RegistryAccess Profile = new RegistryAccess();

            Generic.SortedList <string, string> ForcedSystemTimers;
            string ProcessFileName;
            bool   ForceSystemTimer, MatchedName;

            ForceTimer = !CurrentIsForm; // Set up default return value to supplied value. ForceTimer is opposite logic to IsForm, hence use of Not
            TL.LogMessage("ForceTimer", "Current IsForm: " + CurrentIsForm.ToString() + ", this makes the default ForceTimer value: " + ForceTimer);

            ProcessFileName = Process.GetCurrentProcess().MainModule.FileName.ToUpperInvariant(); // Get the current process processname
            TL.LogMessage("ForceTimer", "Main process file name: " + ProcessFileName);

            MatchedName        = false;
            ForcedSystemTimers = Profile.EnumProfile(FORCE_SYSTEM_TIMER);                        // Get the list of applications requiring special timer handling
            foreach (Generic.KeyValuePair <string, string> ForcedFileName in ForcedSystemTimers) // Check each forced file in turn
            {
                if (ProcessFileName.Contains(Trim(ForcedFileName.Key.ToUpperInvariant)))
                {
                    TL.LogMessage("ForceTimer", "  Found: \"" + ForcedFileName.Key + "\" = \"" + ForcedFileName.Value + "\"");
                    MatchedName = true;
                    if (bool.TryParse(ForcedFileName.Value, out ForceSystemTimer))
                    {
                        ForceTimer = ForceSystemTimer;
                        TL.LogMessage("ForceTimer", "    Parsed OK: " + ForceTimer.ToString() + ", ForceTimer set to: " + ForceTimer);
                    }
                    else
                    {
                        TL.LogMessage("ForceTimer", "    ***** Error - Value is not boolean!");
                    }
                }
                else
                {
                    TL.LogMessage("ForceTimer", "  Tried: \"" + ForcedFileName.Key + "\" = \"" + ForcedFileName.Value + "\"");
                }
            }
            if (!MatchedName)
            {
                TL.LogMessage("ForceTimer", "  Didn't match any force timer application names");
            }

            TL.LogMessage("ForceTimer", "Returning: " + ForceTimer.ToString());
            return(ForceTimer);
        }
コード例 #21
0
        //
        // Download Category files
        //
        public static void DownloadCategoryIndexFiles()
        {
            string url = "https://raw.githubusercontent.com/dipu-bd/uva-problem-category/master/data/";

            var index = Functions.GetCategoryIndex();

            foreach (string key in index.Keys)
            {
                long version = RegistryAccess.GetCategoryVersion(key);
                if (version < index[key])
                {
                    //problem category file
                    string file = LocalDirectory.GetCategoryDataFile(key);
                    DownloadFileAsync(url + key, file, key, Priority.Low,
                                      __DownloadCategoryFileProgress, __DownloadCategoryFileCompleted, 1);
                }
            }
        }
コード例 #22
0
ファイル: FormMain.cs プロジェクト: cuplexProjects/C-Projects
        private void FormMain_Load(object sender, EventArgs e)
        {
            RegistryAccess registryAccess = new RegistryAccess(Application.ProductName);

            try
            {
                applicationSettings = registryAccess.ReadObjectFromRegistry <ApplicationSettings>();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                applicationSettings = new ApplicationSettings();
            }

            UpdateGUIFromSettings();

            sysTrayNotifyIcon.BalloonTipText  = @"Application is now minimized to system tray";
            sysTrayNotifyIcon.BalloonTipTitle = @"Minimized to system tray";
            sysTrayNotifyIcon.BalloonTipIcon  = ToolTipIcon.Info;
        }
コード例 #23
0
ファイル: MareRegHandler.cs プロジェクト: Q-Sharp/MARE
        public void SaveReg()
        {
            int i   = 0;
            var sk  = RegistryAccess.OpenSubKey(sMainReg);
            var cfs = sk.GetSubKeyNames();

            foreach (var cf in cfs)
            {
                try
                {
                    int.Parse(cf);
                    var cr = sk.OpenSubKey(cf, true);

                    if (AllGFX[i].KMD_EnableInternalLargePage.HasValue)
                    {
                        cr.SetValue("KMD_EnableInternalLargePage", AllGFX[i].KMD_EnableInternalLargePage.ToString(), RegistryValueKind.DWord);
                    }

                    if (AllGFX[i].EnableCrossFireAutoLink.HasValue)
                    {
                        cr.SetValue("EnableCrossFireAutoLink", AllGFX[i].EnableCrossFireAutoLink.ToString(), RegistryValueKind.DWord);
                    }

                    if (AllGFX[i].EnableUlps.HasValue)
                    {
                        cr.SetValue("EnableUlps", AllGFX[i].EnableUlps.ToString(), RegistryValueKind.DWord);
                    }

                    i++;
                }
                catch (SecurityException)
                {
                    MessageBox.Show("This tool needs admin rights!");
                    break;
                }
                catch (Exception)
                {
                    continue;
                }
            }
        }
コード例 #24
0
        // Clean up debris left over from 4
        protected static void CleanUp4()
        {
            RegistryAccess RA = new RegistryAccess();
            RegistryKey    RK = RA.OpenSubKey3264(Registry.LocalMachine, @"SOFTWARE\ASCOM", true, RegistryAccess.RegWow64Options.KEY_WOW64_32KEY);

            try
            {
                RK.DeleteSubKeyTree(@"Telescope Drivers\SS2K.Telescope");
                LogMessage("CleanUp4", @"Deleted Registry: Telescope Drivers\SS2K.Telescope");
            }
            catch { }

            try
            {
                RK.DeleteSubKeyTree(@"Focuser Drivers\PCFocus.Focuser");
                LogMessage("CleanUp4", @"Deleted Registry: Focuser Drivers\PCFocus.Focuser");
            }
            catch { }
            RK.Close();
            RA.Dispose();
        }
コード例 #25
0
    // Function to read the checkpoint intervals from the previous invocation of the
    // splashscreen from the registry.
    private void ReadIncrements()
    {
        string sPBIncrementPerTimerInterval = RegistryAccess.GetStringRegistryValue(REGVALUE_PB_MILISECOND_INCREMENT, "0.0015");
        double dblResult;

        if (Double.TryParse(sPBIncrementPerTimerInterval, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out dblResult) == true)
        {
            m_dblPBIncrementPerTimerInterval = dblResult;
        }
        else
        {
            m_dblPBIncrementPerTimerInterval = .0015;
        }

        string sPBPreviousPctComplete = RegistryAccess.GetStringRegistryValue(REGVALUE_PB_PERCENTS, "");

        if (sPBPreviousPctComplete != "")
        {
            string [] aTimes = sPBPreviousPctComplete.Split(null);
            m_alPreviousCompletionFraction = new ArrayList();

            for (int i = 0; i < aTimes.Length; i++)
            {
                double dblVal;
                if (Double.TryParse(aTimes[i], System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out dblVal))
                {
                    m_alPreviousCompletionFraction.Add(dblVal);
                }
                else
                {
                    m_alPreviousCompletionFraction.Add(1.0);
                }
            }
        }
        else
        {
            m_bFirstLaunch        = true;
            lblTimeRemaining.Text = "";
        }
    }
コード例 #26
0
ファイル: USER_STAT.cs プロジェクト: oneshadab/UVA-Arena
        private void deleteUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (usernameList.SelectedObject == null)
            {
                return;
            }
            string val = ((KeyValuePair <string, string>)usernameList.SelectedObject).Key;

            if (val == RegistryAccess.DefaultUsername)
            {
                MessageBox.Show("You can not remove default user from this list.");
                return;
            }

            if (MessageBox.Show("Are you sure to delete '" + val + "' from list?",
                                "Delete User?", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            RegistryAccess.DeleteUserid(val);
            LoadUsernames();
        }
コード例 #27
0
        /// <summary>
        /// Show the open file window to the user
        /// </summary>
        /// <param name="filter">Filter spec list, e.g. "CSV files (*.csv)|*.csv|Tab delimited txt files (*.txt)|*.txt|"</param>
        private void ShowOpenFileWindow(string filter)
        {
            const string WORKING_FOLDER = "Working_Directory";

            var workingFolder = Settings.Default.WorkingFolder;

            if (string.IsNullOrWhiteSpace(workingFolder))
            {
                workingFolder = RegistryAccess.GetStringRegistryValue(WORKING_FOLDER, "");
            }

            if (!string.IsNullOrWhiteSpace(workingFolder))
            {
                try
                {
                    var diWorkingFolder = new DirectoryInfo(workingFolder);
                    while (!diWorkingFolder.Exists)
                    {
                        if (diWorkingFolder.Parent == null)
                        {
                            workingFolder = string.Empty;
                            break;
                        }
                        diWorkingFolder = diWorkingFolder.Parent;
                        workingFolder   = diWorkingFolder.FullName;
                    }
                }
                catch
                {
                    workingFolder = string.Empty;
                }
            }

            var fdlg = new OpenFileDialog
            {
                Title = mstrFldgTitle
            };

            if (!string.IsNullOrWhiteSpace(workingFolder))
            {
                fdlg.InitialDirectory = workingFolder;
            }
            else
            {
                fdlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }

            fdlg.Filter           = filter;
            fdlg.FilterIndex      = 1;
            fdlg.RestoreDirectory = false;
            if (fdlg.ShowDialog() == DialogResult.OK)
            {
                mstrLoadedfileName = fdlg.FileName;

                var fiDataFile = new FileInfo(mstrLoadedfileName);
                if (!fiDataFile.Exists)
                {
                    return;
                }
                mstrLoadedfileName = fiDataFile.FullName;

                if (fiDataFile.Directory != null)
                {
                    workingFolder = fiDataFile.Directory.FullName;
                }

                Settings.Default.WorkingFolder = workingFolder;
                Settings.Default.DataFileName  = fiDataFile.Name;
                Settings.Default.Save();

                RegistryAccess.SetStringRegistryValue(WORKING_FOLDER, workingFolder);
            }
            else
            {
                mstrLoadedfileName = null;
            }
        }
コード例 #28
0
        private void ProcessList()
        {
            if (currentUser == null)
            {
                currentUser      = new UserInfo();
                currentUser.uid  = currentUser.uname = currentUser.name = "[-]";
                currentUser.subs = new List <List <long> >();
                currentUser.Process();
            }

            userRank = RegistryAccess.GetUserRank(currentUser.uname);
            if (userRank == null)
            {
                userRank          = new UserRanklist();
                userRank.username = currentUser.uname;
                userRank.rank     = 0;
                userRank.activity = new List <long>();
                for (int i = 0; i < 5; ++i)
                {
                    userRank.activity.Add(0);
                }
            }

            _acOverTime.Clear();
            _subOverTime.Clear();
            _RankCount.Clear();

            _firstSub    = long.MaxValue;
            _solvedCount = _unsolvedCount = _tryCount = _totalSubmission = 0;
            _subInAnsiC  = _subInCPP = _subInCPP11 = _subInJava = _subInPascal = 0;
            _acCount     = _waCount = _tleCount = _reCount = _peCount = 0;
            _ceCount     = _oleCount = _subeCount = _mleCount = 0;

            List <long> solved = new List <long>();

            foreach (UserSubmission usub in currentUser.submissions)
            {
                //total submission count
                _totalSubmission++;

                //age meter
                if (_firstSub > usub.sbt)
                {
                    _firstSub = usub.sbt;
                }

                //add rank count
                if (usub.IsAccepted())
                {
                    _RankCount.Add(usub.rank, usub.pid);

                    //solve count
                    if (!solved.Contains(usub.pnum))
                    {
                        _solvedCount++;
                        solved.Add(usub.pnum);
                    }
                }


                //language
                switch ((Language)usub.lan)
                {
                case Language.C: _subInAnsiC++; break;

                case Language.Java: _subInJava++; break;

                case Language.Pascal: _subInPascal++; break;

                case Language.CPP: _subInCPP++; break;

                case Language.CPP11: _subInCPP11++; break;
                }

                //submissionPerTime
                double xval = new ZedGraph.XDate(UnixTimestamp.FromUnixTime(usub.sbt));
                if (_totalSubmission == 1)
                {
                    _subOverTime.Add(xval, 0);
                }

                _subOverTime.Add(xval, _totalSubmission);
                _acOverTime.Add(xval, _solvedCount);

                //verdict
                switch ((Verdict)usub.ver)
                {
                case Structures.Verdict.CompileError: _ceCount++; break;

                case Structures.Verdict.RuntimeError: _reCount++; break;

                case Structures.Verdict.OutputLimit: _oleCount++; break;

                case Structures.Verdict.TimLimit: _tleCount++; break;

                case Structures.Verdict.MemoryLimit: _mleCount++; break;

                case Structures.Verdict.WrongAnswer: _waCount++; break;

                case Structures.Verdict.PresentationError: _peCount++; break;

                case Structures.Verdict.Accepted: _acCount++; break;
                }
            }

            //finalize
            _tryCount      = currentUser.TryList.Count;
            _unsolvedCount = _tryCount - _solvedCount;
            _subOverTime.Add(new ZedGraph.XDate(DateTime.Now), _totalSubmission);
            _acOverTime.Add(new ZedGraph.XDate(DateTime.Now), _solvedCount);
        }
コード例 #29
0
ファイル: MetaEditor.cs プロジェクト: nolenfelten/Blam_BSP
        private void LoadENTControls(object[] entArray)
        {
            this.selectedTagType = Maps.map[mapIndex].SelectedMeta.type;

            this.toolStripTagType.Text = "[" + this.selectedTagType.ToString() + "]";
            this.toolStripTagName.Text = Maps.map[mapIndex].SelectedMeta.name;
            //this.Padding = new Padding(10);
            int colorSpaceCount = 4;

            // Custom Plugins access
            ra = new RegistryAccess(Microsoft.Win32.Registry.CurrentUser, RegistryAccess.RegPaths.Halo2CustomPlugins + pluginName + "\\" + this.selectedTagType);
            if (pluginName == null)
                ra.CloseReg();

            foreach (object o in entArray)
            {
                IFPIO.BaseObject tempbase = (IFPIO.BaseObject)o;
                if (tempbase.visible == false)
                    if (Meta_Editor.MetaEditor.ShowInvisibles == false)
                        continue;

                // skip hidden custom plugins variables (mark reflexives to be removed if empty)
                bool skipEmptyReflex = false;
                if (ra.isOpen && ra.getValue(tempbase.offset.ToString()) == bool.FalseString)
                    if (tempbase.ObjectType == IFPIO.ObjectEnum.Struct)
                        skipEmptyReflex = true;
                    else
                        continue;

                switch (tempbase.ObjectType)
                {
                    case IFPIO.ObjectEnum.Struct:
                        {
                            if (Meta_Editor.MetaEditor.ShowReflexives == false)
                                break;
                            // tempLabel is a blank space located above reflexives
                            Label tempLabel = new Label();
                            tempLabel.AutoSize = true;
                            tempLabel.Location = new System.Drawing.Point(0, 0);
                            tempLabel.Name = "label1";
                            tempLabel.Dock = DockStyle.Top;
                            tempLabel.Size = new System.Drawing.Size(35, 13);
                            tempLabel.TabIndex = tabIndex;

                            // tempReflexive is the reflexive and all data (incl other reflexives) within it
                            ReflexiveControl tempReflexive = new ReflexiveControl(mapIndex, Maps.map[mapIndex].SelectedMeta.offset, ((IFPIO.Reflexive)tempbase).HasCount, tempbase.lineNumber, this);
                            //tempReflexive.Location = new System.Drawing.Point(10, 0);
                            tempReflexive.Name = "reflexive";
                            tempReflexive.TabIndex = tabIndex;
                            tempReflexive.LoadENTControls( (IFPIO.Reflexive)tempbase, ((IFPIO.Reflexive)tempbase).items,
                                                           true, 0, ref tabIndex, tempbase.offset.ToString());

                            // Label, Combobox & Button are always added ( = 3)
                            if (!(tempReflexive.Controls.Count <= 2 && skipEmptyReflex))
                            {
                                this.Controls[0].Controls.Add(tempLabel);
                                this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                                this.Controls[0].Controls.Add(tempReflexive);
                                this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            }
                            break;
                        }
                    case IFPIO.ObjectEnum.Ident:
                        {
                            if (Meta_Editor.MetaEditor.ShowIdents == false)
                                break;
                            Ident tempident = new Ident(tempbase.name, mapIndex, tempbase.offset, ((IFPIO.Ident)tempbase).hasTagType, tempbase.lineNumber);
                            tempident.Name = "ident";
                            tempident.TabIndex = tabIndex;
                            tempident.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            tempident.Tag = "[" + tempident.Controls[2].Text + "] "
                                            + tempident.Controls[1].Text;
                            tempident.Controls[1].ContextMenuStrip = identContext;
                            this.Controls[0].Controls.Add(tempident);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.StringID:
                        {
                            if (Meta_Editor.MetaEditor.ShowSIDs == false)
                                break;
                            SID tempSID = new SID(tempbase.name, mapIndex, tempbase.offset, tempbase.lineNumber);
                            tempSID.Name = "sid";
                            tempSID.TabIndex = tabIndex;
                            tempSID.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempSID);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.Float:
                        {
                            if (Meta_Editor.MetaEditor.ShowFloats == false)
                                break;
                            DataValues tempFloat = new DataValues(tempbase.name, mapIndex, tempbase.offset, IFPIO.ObjectEnum.Float, tempbase.lineNumber);
                            tempFloat.TabIndex = tabIndex;
                            tempFloat.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempFloat);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.String32:
                        {
                            if (Meta_Editor.MetaEditor.ShowString32s == false && tempbase.ObjectType == IFPIO.ObjectEnum.String32)
                                break;
                            EntStrings tempstring = new EntStrings(tempbase.name, mapIndex, tempbase.offset, ((IFPIO.IFPString)tempbase).size, ((IFPIO.IFPString)tempbase).type, tempbase.lineNumber);
                            tempstring.Name = "string";
                            tempstring.TabIndex = tabIndex;
                            tempstring.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempstring);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.UnicodeString256:
                        {
                            if (Meta_Editor.MetaEditor.ShowUnicodeString256s == false)
                                break;
                            goto case IFPIO.ObjectEnum.String32;
                        }
                    case IFPIO.ObjectEnum.String256:
                        {
                            if (Meta_Editor.MetaEditor.ShowString256s == false)
                                break;
                            goto case IFPIO.ObjectEnum.String32;
                        }
                    case IFPIO.ObjectEnum.UnicodeString64:
                        {
                            if (Meta_Editor.MetaEditor.ShowUnicodeString64s == false)
                                break;
                            goto case IFPIO.ObjectEnum.String32;
                        }
                    case IFPIO.ObjectEnum.String:
                        {
                            if (Meta_Editor.MetaEditor.ShowString32s == false && tempbase.ObjectType == IFPIO.ObjectEnum.String32)
                                break;
                            EntStrings tempstring = new EntStrings(tempbase.name, mapIndex, tempbase.offset, ((IFPIO.IFPString)tempbase).size, ((IFPIO.IFPString)tempbase).type, tempbase.lineNumber);
                            tempstring.Name = "string";
                            tempstring.TabIndex = tabIndex;
                            tempstring.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempstring);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.Int:
                        {
                            if (((IFPIO.IFPInt)tempbase).entIndex.nulled == true)
                            {
                                if ((Meta_Editor.MetaEditor.ShowInts == false && tempbase.ObjectType == IFPIO.ObjectEnum.Int)
                                    || (Meta_Editor.MetaEditor.ShowShorts == false && tempbase.ObjectType == IFPIO.ObjectEnum.Short)
                                    || (Meta_Editor.MetaEditor.ShowUshorts == false && tempbase.ObjectType == IFPIO.ObjectEnum.UShort)
                                    || (Meta_Editor.MetaEditor.ShowUints == false && tempbase.ObjectType == IFPIO.ObjectEnum.UInt))
                                    break;
                                DataValues tempdatavalues = new DataValues(tempbase.name, mapIndex, tempbase.offset, tempbase.ObjectType, tempbase.lineNumber);
                                tempdatavalues.TabIndex = tabIndex;
                                tempdatavalues.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                                this.Controls[0].Controls.Add(tempdatavalues);
                                this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            }
                            else
                            {
                                if ((Meta_Editor.MetaEditor.ShowBlockIndex32s == false && (tempbase.ObjectType == IFPIO.ObjectEnum.Int | tempbase.ObjectType == IFPIO.ObjectEnum.UInt))
                                    || (Meta_Editor.MetaEditor.ShowBlockIndex16s == false && (tempbase.ObjectType == IFPIO.ObjectEnum.Short | tempbase.ObjectType == IFPIO.ObjectEnum.UShort))
                                    || (Meta_Editor.MetaEditor.ShowBlockIndex8s == false && tempbase.ObjectType == IFPIO.ObjectEnum.Byte))
                                    break;
                                Indices tempdatavalues = new Indices(tempbase.name, mapIndex, tempbase.offset, tempbase.ObjectType, ((IFPIO.IFPInt)tempbase).entIndex);
                                tempdatavalues.TabIndex = tabIndex;
                                this.Controls[0].Controls.Add(tempdatavalues);
                                this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            }
                            break;
                        }
                    case IFPIO.ObjectEnum.Short:
                        {
                            goto case IFPIO.ObjectEnum.Int;
                        }
                    case IFPIO.ObjectEnum.UShort:
                        {
                            goto case IFPIO.ObjectEnum.Int;
                        }
                    case IFPIO.ObjectEnum.UInt:
                        {
                            goto case IFPIO.ObjectEnum.Int;
                        }
                    case IFPIO.ObjectEnum.Unknown:
                        {
                            if (Meta_Editor.MetaEditor.ShowUndefineds == false)
                                break;
                            DataValues tempUnknown = new DataValues(tempbase.name, mapIndex, tempbase.offset, IFPIO.ObjectEnum.Unknown, tempbase.lineNumber);
                            tempUnknown.TabIndex = tabIndex;
                            tempUnknown.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempUnknown);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.Byte_Flags:
                        {
                            if (Meta_Editor.MetaEditor.ShowBitmask8s == false)
                                break;
                            Bitmask tempbitmask = new Bitmask(tempbase.name, mapIndex, tempbase.offset, ((IFPIO.Bitmask)tempbase).bitmaskSize, ((IFPIO.Bitmask)tempbase).options, tempbase.lineNumber);
                            tempbitmask.TabIndex = tabIndex;
                            tempbitmask.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempbitmask);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.Word_Flags:
                        {
                            if (Meta_Editor.MetaEditor.ShowBitmask16s == false)
                                break;
                            Bitmask tempbitmask = new Bitmask(tempbase.name, mapIndex, tempbase.offset, ((IFPIO.Bitmask)tempbase).bitmaskSize, ((IFPIO.Bitmask)tempbase).options, tempbase.lineNumber);
                            tempbitmask.TabIndex = tabIndex;
                            tempbitmask.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempbitmask);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.Long_Flags:
                        {
                            if (Meta_Editor.MetaEditor.ShowBitmask32s == false)
                                break;
                            Bitmask tempbitmask = new Bitmask(tempbase.name, mapIndex, tempbase.offset, ((IFPIO.Bitmask)tempbase).bitmaskSize, ((IFPIO.Bitmask)tempbase).options, tempbase.lineNumber);
                            tempbitmask.TabIndex = tabIndex;
                            tempbitmask.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempbitmask);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.Char_Enum:
                        {
                            if (Meta_Editor.MetaEditor.ShowEnum8s == false)
                                break;
                            Enums tempenum = new Enums(tempbase.name, mapIndex, tempbase.offset, ((IFPIO.IFPEnum)tempbase).enumSize, ((IFPIO.IFPEnum)tempbase).options, tempbase.lineNumber);
                            tempenum.TabIndex = tabIndex;
                            tempenum.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempenum);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.Enum:
                        {
                            if (Meta_Editor.MetaEditor.ShowEnum16s == false)
                                break;
                            Enums tempenum = new Enums(tempbase.name, mapIndex, tempbase.offset, ((IFPIO.IFPEnum)tempbase).enumSize, ((IFPIO.IFPEnum)tempbase).options, tempbase.lineNumber);
                            tempenum.TabIndex = tabIndex;
                            tempenum.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempenum);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.Long_Enum:
                        {
                            if (Meta_Editor.MetaEditor.ShowEnum32s == false)
                                break;
                            Enums tempenum = new Enums(tempbase.name, mapIndex, tempbase.offset, ((IFPIO.IFPEnum)tempbase).enumSize, ((IFPIO.IFPEnum)tempbase).options, tempbase.lineNumber);
                            tempenum.TabIndex = tabIndex;
                            tempenum.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempenum);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.Byte:
                        {
                            if (((IFPIO.IFPByte)tempbase).entIndex.nulled == true)
                            {
                                if (Meta_Editor.MetaEditor.ShowBytes == false)
                                    break;
                                DataValues tempByte = new DataValues(tempbase.name, mapIndex, tempbase.offset, IFPIO.ObjectEnum.Byte, tempbase.lineNumber);
                                tempByte.TabIndex = tabIndex;
                                this.Controls[0].Controls.Add(tempByte);
                                this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            }
                            else
                            {
                                if (Meta_Editor.MetaEditor.ShowBlockIndex8s == false)
                                    break;
                                Indices tempdatavalues = new Indices(tempbase.name, mapIndex, tempbase.offset, tempbase.ObjectType, ((IFPIO.IFPByte)tempbase).entIndex);
                                tempdatavalues.TabIndex = tabIndex;
                                this.Controls[0].Controls.Add(tempdatavalues);
                                this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            }
                            break;
                        }
                    case IFPIO.ObjectEnum.Unused:
                        {
                            DataValues tempUnknown = new DataValues(tempbase.name, mapIndex, tempbase.offset, IFPIO.ObjectEnum.Unused, tempbase.lineNumber);
                            tempUnknown.TabIndex = tabIndex;
                            tempUnknown.Populate(Maps.map[mapIndex].SelectedMeta.offset);
                            this.Controls[0].Controls.Add(tempUnknown);
                            this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                            break;
                        }
                    case IFPIO.ObjectEnum.TagType:
                        continue;
                        break;
                }

                if (!(tempbase is IFPIO.Reflexive))
                    ToolTip1.SetToolTip(this.Controls[0].Controls[0].Controls[0], "offset: " + tempbase.offset.ToString());

                if (this.Controls[0].Controls.Count > 0 && this.Controls[0].Controls[0] is DataValues)
                {
                    //if (((tempbase.name.ToLower().Contains(" a") & tempbase.name[tempbase.name.ToLower().IndexOf(" a")]) ||
                    //     tempbase.name.ToLower().Contains("alpha"))& alphaControl == null)
                    if (ColorWheel.checkForColor(tempbase.name, alphaControl, " a", "alpha"))
                    {
                        alphaControl = (DataValues)this.Controls[0].Controls[0];
                        colorSpaceCount = 0;
                    }
                    //if (tempbase.name.ToLower().Contains(" r") & redControl == null)
                    else if (ColorWheel.checkForColor(tempbase.name, redControl, " r", "red"))
                    {
                        redControl = (DataValues)this.Controls[0].Controls[0];
                        colorSpaceCount = 0;
                    }
                    //if (tempbase.name.ToLower().Contains(" g") & greenControl == null)
                    else if (ColorWheel.checkForColor(tempbase.name, greenControl, " g", "green"))
                    {
                        greenControl = (DataValues)this.Controls[0].Controls[0];
                        colorSpaceCount = 0;
                    }
                    //if (tempbase.name.ToLower().Contains(" b") & blueControl == null)
                    else if (ColorWheel.checkForColor(tempbase.name, blueControl, " b", "blue"))
                    {
                        blueControl = (DataValues)this.Controls[0].Controls[0];
                        colorSpaceCount = 0;
                    }
                    else
                    {
                        colorSpaceCount++;
                        if (colorSpaceCount == 1)
                        {
                            alphaControl = null;
                            redControl = null;
                            greenControl = null;
                            blueControl = null;
                        }
                    }
                    if (redControl != null & greenControl != null & blueControl != null)
                    {
                        // Create the new ColorWheel class, indicating
                        // the locations of the color wheel itself, the
                        // brightness area, and the position of the selected color.
                        ColorWheel cw = new ColorWheel();

                        if (alphaControl != null)
                            cw.setTextBox(alphaControl.textBox1, Color.White);
                        cw.setTextBox(redControl.textBox1, Color.Red);
                        cw.setTextBox(greenControl.textBox1, Color.Green);
                        cw.setTextBox(blueControl.textBox1, Color.Blue);

                        //p.I.AddRange(new Rectangle[] { SelectedColorRectangle });
                        cw.Dock = DockStyle.Top;
                        this.Controls[0].Controls.Add(cw);
                        this.Controls[0].Controls[this.Controls[0].Controls.Count - 1].BringToFront();
                        // Reset for next batch
                        colorSpaceCount++;
                        alphaControl = null;
                        redControl = null;
                        greenControl = null;
                        blueControl = null;
                    }
                }
                else colorSpaceCount++;
                tabIndex++;
            }
            ra.CloseReg();
        }
コード例 #30
0
        private static readonly double UNKNOWN_LEAP_SECONDS = double.MinValue;   // Value for dates which have not yet been determined

        static void Main(string[] args)
        {
            try
            {
                // In December 2020, ascom-standards.org minimum SSL protocol version is TLS1.2
                // Normally, this application will use the OS default SSL protocol, but Windows 7 default protocol is earlier that TLS1.2 and connection cannot be established to ascom-standards.org from this OS.
                // The following command ensures that TLS1.2 will be tried in addition to the OS default protocol.
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.SystemDefault;

                // Get some basic details for this run
                string   runBy    = WindowsIdentity.GetCurrent().Name; // Get the name of the user executing this program
                bool     isSystem = WindowsIdentity.GetCurrent().IsSystem;
                DateTime now      = DateTime.Now;

                ReturnCode = 0; // Initialise return code to success

                // Get access to the ASCOM Profile store and retrieve the trace logger configuration
                RegistryAccess profile       = new RegistryAccess();
                string         traceFileName = "";
                string         traceBasePath = "";
                if (isSystem) // If we are running as user SYSTEM, create our own trace file name so that all scheduled job trace files end up in the same directory
                {
                    // Get the configured trace file directory and make sure that it exists
                    traceBasePath = profile.GetProfile(GlobalItems.ASTROMETRY_SUBKEY,
                                                       GlobalItems.DOWNLOAD_TASK_TRACE_PATH_VALUE_NAME,
                                                       string.Format(GlobalItems.DOWNLOAD_TASK_TRACE_DEFAULT_PATH_FORMAT, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
                                                       ).TrimEnd('\\');
                    Directory.CreateDirectory(traceBasePath);
                    // Now make the full trace file name from the path above and the file name format template
                    traceFileName = string.Format(GlobalItems.DOWNLOAD_TASK_TRACE_FILE_NAME_FORMAT, traceBasePath, now.Year, now.Month, now.Day, now.Hour.ToString("00"), now.Minute.ToString("00"), now.Second.ToString("00"));
                }

                // Get the trace state from the Profile
                string DownloadTaskTraceEnabledString = profile.GetProfile(GlobalItems.ASTROMETRY_SUBKEY, GlobalItems.DOWNLOAD_TASK_TRACE_ENABLED_VALUE_NAME, GlobalItems.DOWNLOAD_TASK_TRACE_ENABLED_DEFAULT.ToString());
                if (!Boolean.TryParse(DownloadTaskTraceEnabledString, out bool DownloadTaskTraceEnabledValue)) //' String parsed OK so no further action
                {                                                                                              //'Returned string doesn't represent a boolean so use the default
                    DownloadTaskTraceEnabledValue = GlobalItems.DOWNLOAD_TASK_TRACE_ENABLED_DEFAULT;
                }

                // Create the trace logger with either the supplied fully qualified name if running as SYSTEM or an automatic file name if running as a normal user
                TL                 = new TraceLogger(traceFileName, GlobalItems.DOWNLOAD_TASK_TRACE_LOG_FILETYPE);
                TL.Enabled         = DownloadTaskTraceEnabledValue; // Set the trace state
                TL.IdentifierWidth = GlobalItems.DOWNLOAD_TASK_TRACE_LOGGER_IDENTIFIER_FIELD_WIDTH;

                invariantCulture = new CultureInfo("");
                invariantCulture.Calendar.TwoDigitYearMax = 2117;                          // Specify that two digit years will be converted to the range 2018-2117 - Likely to outlast ASCOM Platform and me!
                monthAbbrev       = invariantCulture.DateTimeFormat.AbbreviatedMonthNames; // Get the 12 three letter abbreviated month names of the year
                invariantTextInfo = invariantCulture.TextInfo;

                TL.LogMessage("EarthRotationUpdate", string.Format("InstalledUICulture: {0}, CurrentUICulture: {1}, CurrentCulture: {2}", CultureInfo.InstalledUICulture.Name, CultureInfo.CurrentUICulture, CultureInfo.CurrentCulture));

                parameters = new EarthRotationParameters(TL);                                                       // Get configuration from the Profile store
                string runDate = now.ToString(GlobalItems.DOWNLOAD_TASK_TIME_FORMAT, CultureInfo.CurrentUICulture); // Get today's date and time in a locally readable format
                hostURIString = parameters.DownloadTaskDataSource;                                                  // Initialise the data source URI

                if (args.Length > 0)
                {
                    foreach (string arg in args)
                    {
                        TL.LogMessage("EarthRotationUpdate", string.Format("Received parameter: {0}", arg));
                    }
                }

                // If we have been provided with an "Initialise" parameter then stop here after having set up all the default profile values by creating the EarthRotationParameters object
                if (args.Length == 1)
                {
                    if (args[0].Trim(' ', '-', '\\', '/').Equals("INITIALISE", StringComparison.OrdinalIgnoreCase)) // Test for the presence of and act on the initialise argument ignoring everything else
                    {
                        TL.LogMessage("EarthRotationUpdate", string.Format("Earth rotation parameter initialisation run on {0} by {1}, IsSystem: {2}", runDate, runBy, isSystem));
                        LogEvent(string.Format("Earth rotation parameter initialisation run on {0} by {1}, IsSystem: {2}", runDate, runBy, isSystem), EventLogEntryType.Information);

                        TL.LogMessage("EarthRotationUpdate", string.Format("Calling ManageScheduledTask"));
                        parameters.ManageScheduledTask();
                        TL.LogMessage("EarthRotationUpdate", string.Format("Completed ManageScheduledTask"));

                        Environment.Exit(0);
                    }
                }

                // If we have been provided with a "DataSource" override parameter then apply the new URI otherwise read it from the Profile
                if (args.Length == 2)
                {
                    if (args[0].Trim(' ', '-', '\\', '/').Equals("DATASOURCE", StringComparison.OrdinalIgnoreCase)) // Test for the presence of and act on the data source argument ignoring everything else
                    {
                        TL.LogMessage("EarthRotationUpdate", string.Format("Data source override parameter provided: {0}", args[1]));
                        string overrideDataSource = args[1].Trim(' ', '"');
                        bool   UriValid           = false; // Set the valid flag false, then set to true if the download source starts with a supported URI prefix
                        if (overrideDataSource.StartsWith(GlobalItems.URI_PREFIX_HTTP, StringComparison.OrdinalIgnoreCase))
                        {
                            UriValid = true;
                        }
                        if (overrideDataSource.StartsWith(GlobalItems.URI_PREFIX_HTTPS, StringComparison.OrdinalIgnoreCase))
                        {
                            UriValid = true;
                        }
                        if (overrideDataSource.StartsWith(GlobalItems.URI_PREFIX_FTP, StringComparison.OrdinalIgnoreCase))
                        {
                            UriValid = true;
                        }

                        if (UriValid)
                        {
                            hostURIString = overrideDataSource;
                            TL.LogMessage("EarthRotationUpdate", string.Format("Data source override parameter is valid and will be used: {0}", hostURIString));
                        }
                        else
                        {
                            TL.LogMessage("EarthRotationUpdate", string.Format("Data source override parameter {0} is not valid and the Profile data source will be used instead: {1}", overrideDataSource, hostURIString));
                        }
                    }
                }

                // Ensure that the host URI string, wherever it has come from, ends with a single backslash otherwise the URI will be incorrect when the file name is formed
                hostURIString = hostURIString.TrimEnd(' ', '-', '\\', '/') + "/";

                LogEvent(string.Format("Run on {0} by {1}, IsSystem: {2}", runDate, runBy, isSystem), EventLogEntryType.Information);
                TL.LogMessage("EarthRotationUpdate", string.Format("Run on {0} by {1}, IsSystem: {2}", runDate, runBy, isSystem));
                TL.BlankLine();
                LogEvent(string.Format("Log file: {0}, Trace state: {1}, Log file path: {2}", TL.LogFileName, parameters.DownloadTaskTraceEnabled, TL.LogFilePath), EventLogEntryType.Information);
                TL.LogMessage("EarthRotationUpdate", string.Format("Log file: {0}, Trace state: {1}, Log file path: {2}", TL.LogFileName, parameters.DownloadTaskTraceEnabled, TL.LogFilePath));
                TL.LogMessage("EarthRotationUpdate", string.Format("Earth rotation data last updated: {0}", parameters.EarthRotationDataLastUpdatedString));
                TL.LogMessage("EarthRotationUpdate", string.Format("Data source: {0}", hostURIString));

                DownloadTimeout = parameters.DownloadTaskTimeOut;

                WebClient client = new WebClient();

                client.DownloadProgressChanged += Client_DownloadProgressChanged;
                client.DownloadFileCompleted   += Client_DownloadFileCompleted;

                Uri hostURI = new Uri(hostURIString);

                if (WebRequest.DefaultWebProxy.GetProxy(hostURI) == hostURI)
                {
                    TL.LogMessage("EarthRotationUpdate", "No proxy server detected, going directly to Internet"); // No proxy is in use so go straight out
                }
                else // Proxy is in use so set it and apply credentials
                {
                    TL.LogMessage("EarthRotationUpdate", "Setting default proxy");
                    client.Proxy = WebRequest.DefaultWebProxy;
                    TL.LogMessage("EarthRotationUpdate", "Setting default credentials");
                    client.Proxy.Credentials = CredentialCache.DefaultCredentials;
                    TL.LogMessage("EarthRotationUpdate", "Using proxy server: " + WebRequest.DefaultWebProxy.GetProxy(hostURI).ToString());
                }

                client.Headers.Add("user-agent", GlobalItems.DOWNLOAD_TASK_USER_AGENT);
                client.Headers.Add("Accept", "text/plain");
                client.Encoding    = Encoding.ASCII;
                client.BaseAddress = hostURIString;
                NetworkCredential credentials = new NetworkCredential("anonymous", "guest"); // Apply some standard credentials for FTP sites
                client.Credentials = credentials;
                TL.BlankLine();

                // Get the latest delta UT1 values
                try
                {
                    string   dUT1fileName = DownloadFile("DeltaUT1", GlobalItems.DELTAUT1_FILE, client, TL); // Download the latest delta UT1 values and receive the filename holding the data
                    FileInfo info         = new FileInfo(dUT1fileName);                                      // Find out if we have any data
                    if (info.Length > 0)                                                                     // We actually received some data so process it
                    {
                        // List the data position parameters that will be used to extract the delta UT1 data from the file
                        TL.LogMessage("DeltaUT1", string.Format("Expected file format for the {0} file", GlobalItems.DELTAUT1_FILE));
                        TL.LogMessage("DeltaUT1", string.Format("Year string start position: {0}, Year string length: {1}", GlobalItems.DELTAUT1_YEAR_START, GlobalItems.DELTAUT1_YEAR_LENGTH));
                        TL.LogMessage("DeltaUT1", string.Format("Month string start position: {0}, Month string length: {1}", GlobalItems.DELTAUT1_MONTH_START, GlobalItems.DELTAUT1_MONTH_LENGTH));
                        TL.LogMessage("DeltaUT1", string.Format("Day string start position: {0}, Day string length: {1}", GlobalItems.DELTAUT1_DAY_START, GlobalItems.DELTAUT1_DAY_LENGTH));
                        TL.LogMessage("DeltaUT1", string.Format("Julian date start position: {0}, Julian date string length: {1}", GlobalItems.DELTAUT1_JULIAN_DATE_START, GlobalItems.DELTAUT1_JULIAN_DATE_LENGTH));
                        TL.LogMessage("DeltaUT1", string.Format("Delta UT1 start position: {0}, Delta UT1 string length: {1}", GlobalItems.DELTAUT1_START, GlobalItems.DELTAUT1_LENGTH));
                        TL.BlankLine();

                        profile.DeleteKey(GlobalItems.AUTOMATIC_UPDATE_DELTAUT1_SUBKEY_NAME); // Clear out old delta UT1 values
                        profile.CreateKey(GlobalItems.AUTOMATIC_UPDATE_DELTAUT1_SUBKEY_NAME);

                        // Process the data file
                        using (var filestream = new FileStream(dUT1fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            using (var file = new StreamReader(filestream, Encoding.ASCII, true, 4096))
                            {
                                string   lineOfText;
                                DateTime date;

                                while ((lineOfText = file.ReadLine()) != null) // Get lines of text one at a time and parse them
                                {
                                    try
                                    {
                                        // Extract string values for data items
                                        string yearString       = lineOfText.Substring(GlobalItems.DELTAUT1_YEAR_START, GlobalItems.DELTAUT1_YEAR_LENGTH);
                                        string monthString      = lineOfText.Substring(GlobalItems.DELTAUT1_MONTH_START, GlobalItems.DELTAUT1_MONTH_LENGTH);
                                        string dayString        = lineOfText.Substring(GlobalItems.DELTAUT1_DAY_START, GlobalItems.DELTAUT1_DAY_LENGTH);
                                        string julianDateString = lineOfText.Substring(GlobalItems.DELTAUT1_JULIAN_DATE_START, GlobalItems.DELTAUT1_JULIAN_DATE_LENGTH);
                                        string dUT1String       = lineOfText.Substring(GlobalItems.DELTAUT1_START, GlobalItems.DELTAUT1_LENGTH);

                                        // Validate that the data items are parse-able
                                        bool yearOK       = int.TryParse(yearString, NumberStyles.Integer, CultureInfo.InvariantCulture, out int year);
                                        bool monthOK      = int.TryParse(monthString, NumberStyles.Integer, CultureInfo.InvariantCulture, out int month);
                                        bool dayOK        = int.TryParse(dayString, NumberStyles.Integer, CultureInfo.InvariantCulture, out int day);
                                        bool julianDateOK = double.TryParse(julianDateString, NumberStyles.Float, CultureInfo.InvariantCulture, out double julianDate);
                                        bool dut1OK       = double.TryParse(dUT1String, NumberStyles.Float, CultureInfo.InvariantCulture, out double dUT1);

                                        if (yearOK & monthOK & dayOK & julianDateOK & dut1OK)       // We have good values for all data items so save these to the Profile
                                        {
                                            year = invariantCulture.Calendar.ToFourDigitYear(year); // Convert the two digit year to a four digit year
                                            date = new DateTime(year, month, day);

                                            // Only save the item if it is from a few days back or is a future prediction
                                            if (date.Date >= DateTime.Now.Date.Subtract(new TimeSpan(GlobalItems.DOWNLOAD_TASK_NUMBER_OF_BACK_DAYS_OF_DELTAUT1_DATA_TO_LOAD, 0, 0, 0)))
                                            {
                                                string deltaUT1ValueName = string.Format(GlobalItems.DELTAUT1_VALUE_NAME_FORMAT,
                                                                                         date.Year.ToString(GlobalItems.DELTAUT1_VALUE_NAME_YEAR_FORMAT),
                                                                                         date.Month.ToString(GlobalItems.DELTAUT1_VALUE_NAME_MONTH_FORMAT),
                                                                                         date.Day.ToString(GlobalItems.DELTAUT1_VALUE_NAME_DAY_FORMAT));
                                                TL.LogMessage("DeltaUT1", string.Format("Setting {0}, JD = {1} - DUT1 = {2} with key: {3}", date.ToLongDateString(), julianDate, dUT1, deltaUT1ValueName));
                                                profile.WriteProfile(GlobalItems.AUTOMATIC_UPDATE_DELTAUT1_SUBKEY_NAME, deltaUT1ValueName, dUT1.ToString("0.000", CultureInfo.InvariantCulture));
                                            }
                                        }
                                        else
                                        {
                                            TL.LogMessage("DeltaUT1", string.Format("Unable to parse Delta UT1 values from the line below - Year: {0}, Month: {1}, Day: {2}, Julian Day: {3},Delta UT1: {4}",
                                                                                    yearString, monthString, dayString, julianDateString, dUT1String));
                                            TL.LogMessage("DeltaUT1", string.Format("Corrupt line: {0}", lineOfText));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        TL.LogMessageCrLf("DeltaUT1", string.Format("Unexpected exception: {0}, parsing line: ", ex.Message, lineOfText));
                                        TL.LogMessageCrLf("DeltaUT1", ex.ToString());
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        TL.LogMessage("DeltaUT1", string.Format("Downloaded file size was zero so nothing to process!"));
                    }
                    File.Delete(dUT1fileName);
                    TL.BlankLine();
                }
                catch (WebException ex) // An issue occurred with receiving the leap second file over the network
                {
                    TL.LogMessageCrLf("DeltaUT1", string.Format("Error: {0} - delta UT1 data not updated", ex.Message));
                    ReturnCode = 1;
                }
                catch (Exception ex)
                {
                    TL.LogMessageCrLf("DeltaUT1", ex.ToString());
                    ReturnCode = 2;
                }

                // Get the latest leap second values
                try
                {
                    string   leapSecondsfileName = DownloadFile("LeapSeconds", GlobalItems.LEAP_SECONDS_FILE, client, TL); // Download the latest leap second values and receive the filename holding the data
                    FileInfo info = new FileInfo(leapSecondsfileName);                                                     // Find out if we have any data
                    if (info.Length > 0)                                                                                   // We actually received some data so process it
                    {
                        // List the data position parameters that will be used to extract the delta UT1 data from the file
                        TL.LogMessage("LeapSeconds", string.Format("Expected file format for the {0} file", GlobalItems.DELTAUT1_FILE));
                        TL.LogMessage("LeapSeconds", string.Format("Year string start position: {0}, Year string length: {1}", GlobalItems.LEAP_SECONDS_YEAR_START, GlobalItems.LEAP_SECONDS_YEAR_LENGTH));
                        TL.LogMessage("LeapSeconds", string.Format("Month string start position: {0}, Month string length: {1}", GlobalItems.LEAP_SECONDS_MONTH_START, GlobalItems.LEAP_SECONDS_MONTH_LENGTH));
                        TL.LogMessage("LeapSeconds", string.Format("Day string start position: {0}, Day string length: {1}", GlobalItems.LEAP_SECONDS_DAY_START, GlobalItems.LEAP_SECONDS_DAY_LENGTH));
                        TL.LogMessage("LeapSeconds", string.Format("Julian date start position: {0}, Julian date string length: {1}", GlobalItems.LEAP_SECONDS_JULIAN_DATE_START, GlobalItems.LEAP_SECONDS_JULIAN_DATE_LENGTH));
                        TL.LogMessage("LeapSeconds", string.Format("Leap seconds start position: {0}, Leap seconds string length: {1}", GlobalItems.LEAP_SECONDS_LEAPSECONDS_START, GlobalItems.LEAP_SECONDS_LEAPSECONDS_LENGTH));
                        TL.BlankLine();

                        profile.DeleteKey(GlobalItems.AUTOMATIC_UPDATE_LEAP_SECOND_HISTORY_SUBKEY_NAME);;  // Clear out old leap second values
                        profile.CreateKey(GlobalItems.AUTOMATIC_UPDATE_LEAP_SECOND_HISTORY_SUBKEY_NAME);

                        // Process the data file
                        using (var filestream = new FileStream(leapSecondsfileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            double   currentLeapSeconds  = UNKNOWN_LEAP_SECONDS;
                            double   nextLeapSeconds     = 0.0;
                            DateTime leapSecondDate      = UNKNOWN_DATE;
                            DateTime nextleapSecondsDate = UNKNOWN_DATE;

                            using (var file = new StreamReader(filestream, Encoding.ASCII, true, 4096))
                            {
                                string   lineOfText;
                                DateTime latestLeapSecondDate = UNKNOWN_DATE;
                                while ((lineOfText = file.ReadLine()) != null) // Get lines of text one at a time and parse them
                                {
                                    try
                                    {
                                        // Read values from the file as strings based on their position within the file
                                        string yearString        = lineOfText.Substring(GlobalItems.LEAP_SECONDS_YEAR_START, GlobalItems.LEAP_SECONDS_YEAR_LENGTH);
                                        string monthString       = lineOfText.Substring(GlobalItems.LEAP_SECONDS_MONTH_START, GlobalItems.LEAP_SECONDS_MONTH_LENGTH);
                                        string dayString         = lineOfText.Substring(GlobalItems.LEAP_SECONDS_DAY_START, GlobalItems.LEAP_SECONDS_DAY_LENGTH);
                                        string julianDateString  = lineOfText.Substring(GlobalItems.LEAP_SECONDS_JULIAN_DATE_START, GlobalItems.LEAP_SECONDS_JULIAN_DATE_LENGTH);
                                        string leapSecondsString = lineOfText.Substring(GlobalItems.LEAP_SECONDS_LEAPSECONDS_START, GlobalItems.LEAP_SECONDS_LEAPSECONDS_LENGTH);

                                        // Validate that the data items are parse-able
                                        bool yearOK        = int.TryParse(yearString, NumberStyles.Integer, CultureInfo.InvariantCulture, out int year);
                                        bool dayOK         = int.TryParse(dayString, NumberStyles.Integer, CultureInfo.InvariantCulture, out int day);
                                        bool julianDateOK  = double.TryParse(julianDateString, NumberStyles.Float, CultureInfo.InvariantCulture, out double julianDate);
                                        bool leapSecondsOK = double.TryParse(leapSecondsString, NumberStyles.Float, CultureInfo.InvariantCulture, out double leapSeconds);

                                        // Get the month number by trimming the month string, converting to lower case then title case then looking up the index in the abbreviated months array
                                        int month = Array.IndexOf(monthAbbrev, invariantTextInfo.ToTitleCase(monthString.Trim(' ').ToLower(CultureInfo.InvariantCulture))) + 1; // If IndexOf fails, it returns -1 so the resultant month number will be zero and this is checked below

                                        if (yearOK & (month > 0) & dayOK & julianDateOK & leapSecondsOK)                                                                        // We have good values for all data items so save these to the Profile
                                        {
                                            double modifiedJulianDate = julianDate - GlobalItems.MODIFIED_JULIAN_DAY_OFFSET;
                                            leapSecondDate = new DateTime(year, month, day);

                                            // Write all leap second values and Julian dates that they become effective to the leap second history subkey
                                            profile.WriteProfile(GlobalItems.AUTOMATIC_UPDATE_LEAP_SECOND_HISTORY_SUBKEY_NAME, julianDate.ToString(CultureInfo.InvariantCulture), leapSeconds.ToString(CultureInfo.InvariantCulture));

                                            if ((leapSecondDate.Date >= latestLeapSecondDate) & (leapSecondDate.Date <= DateTime.UtcNow.Date.Subtract(new TimeSpan(GlobalItems.TEST_HISTORIC_DAYS_OFFSET, 0, 0, 0))))
                                            {
                                                currentLeapSeconds = leapSeconds;
                                            }
                                            if ((leapSecondDate.Date > DateTime.UtcNow.Date.Subtract(new TimeSpan(GlobalItems.TEST_HISTORIC_DAYS_OFFSET, 0, 0, 0))) & (nextleapSecondsDate == UNKNOWN_DATE)) // Record the next leap seconds value in the file
                                            {
                                                nextLeapSeconds     = leapSeconds;
                                                nextleapSecondsDate = leapSecondDate;
                                            }

                                            TL.LogMessage("LeapSeconds", string.Format("Leap second takes effect on: {0}, Modified JD = {1} - Current Leap Seconds = {2}, Latest Leap Seconds: {3}, Next Leap Seconds: {4} on {5}", leapSecondDate.ToLongDateString(), modifiedJulianDate, leapSeconds, currentLeapSeconds, nextLeapSeconds, nextleapSecondsDate.ToLongDateString()));
                                        }
                                        else
                                        {
                                            TL.LogMessage("LeapSeconds", string.Format("Unable to parse leap second values from the line below - Year: {0}, Month: {1}, Day: {2}, Julian Day: {3},Leap seconds: {4}",
                                                                                       yearString, monthString, dayString, julianDateString, leapSecondsString));
                                            TL.LogMessage("LeapSeconds", string.Format("Corrupt line: {0}", lineOfText));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        TL.LogMessageCrLf("LeapSeconds", ex.ToString());
                                    }
                                }
                            }
                            TL.BlankLine();

                            if (currentLeapSeconds == UNKNOWN_LEAP_SECONDS) // No valid leap seconds were found so indicate that this
                            {
                                profile.WriteProfile(GlobalItems.ASTROMETRY_SUBKEY, GlobalItems.AUTOMATIC_LEAP_SECONDS_VALUENAME, GlobalItems.AUTOMATIC_LEAP_SECONDS_NOT_AVAILABLE_DEFAULT);
                            }
                            else  // Persist the current leap second value to the Profile
                            {
                                parameters.AutomaticLeapSecondsString = currentLeapSeconds.ToString(CultureInfo.InvariantCulture);
                                // Also include a value that is in the SOFA library defaults but is not in the USNO files. It pre-dates the start of UTC but I am assuming that IAU is correct on this occasion
                                profile.WriteProfile(GlobalItems.AUTOMATIC_UPDATE_LEAP_SECOND_HISTORY_SUBKEY_NAME, double.Parse("2436934.5", CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture), double.Parse("1.4178180", CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture));
                            }

                            // Persist the next leap second value and its implementation date if these have been announced
                            if (nextleapSecondsDate == UNKNOWN_DATE) // No announcement has been made
                            {
                                parameters.NextLeapSecondsString     = GlobalItems.DOWNLOAD_TASK_NEXT_LEAP_SECONDS_NOT_PUBLISHED_MESSAGE;
                                parameters.NextLeapSecondsDateString = GlobalItems.DOWNLOAD_TASK_NEXT_LEAP_SECONDS_NOT_PUBLISHED_MESSAGE;
                            }
                            else // A future leap second has been announced
                            {
                                parameters.NextLeapSecondsString     = nextLeapSeconds.ToString(CultureInfo.InvariantCulture);
                                parameters.NextLeapSecondsDateString = nextleapSecondsDate.ToString(GlobalItems.DOWNLOAD_TASK_TIME_FORMAT, CultureInfo.InvariantCulture);
                            }
                            TL.BlankLine();
                            TL.LogMessage("LeapSeconds", string.Format("Current Leap Seconds = {0}, Next Leap Seconds: {1} on {2}", currentLeapSeconds, nextLeapSeconds, nextleapSecondsDate.ToLongDateString()));
                        }
                    }
                    else
                    {
                        TL.LogMessage("LeapSeconds", string.Format("Downloaded file size was zero so nothing to process!"));
                    }

                    parameters.EarthRotationDataLastUpdatedString = runDate; // Save a new last run time to the Profile

                    TL.BlankLine();
                    TL.LogMessage("LeapSeconds", string.Format("Task completed."));

                    File.Delete(leapSecondsfileName);
                    parameters.Dispose();
                    parameters = null;
                }
                catch (WebException ex) // An issue occurred with receiving the leap second file over the network
                {
                    TL.LogMessageCrLf("LeapSeconds", string.Format("Error: {0} - leap second data not updated.", ex.Message));
                    ReturnCode = 3;
                }
                catch (Exception ex)
                {
                    TL.LogMessageCrLf("LeapSeconds", ex.ToString());
                    ReturnCode = 4;
                }

                TL.Enabled = false;
                TL.Dispose();
                TL = null;
            }
            catch (Exception ex)
            {
                try { TL.LogMessageCrLf("EarthRotationUpdate", ex.ToString()); } catch { }

                EventLogCode.LogEvent("EarthRotationUpdate",
                                      string.Format("EarthRotationUpdate - Unexpected exception: {0}", ex.Message),
                                      EventLogEntryType.Error,
                                      GlobalConstants.EventLogErrors.EarthRotationUpdate,
                                      ex.ToString());
                ReturnCode = 5;
            }
            Environment.Exit(ReturnCode);
        }
コード例 #31
0
        static int Main()
        {
            try
            {
                TL         = new TraceLogger("", "UninstallASCOM"); // Create a tracelogger so we can log what happens
                TL.Enabled = true;

                LogMessage("Uninstall", "Creating RegistryAccess object");
                RegAccess = new RegistryAccess(TL); //Create a RegistryAccess object that will use the UninstallASCOM trace logger to ensure all messages appear in one log file

                // This has been removed because it destroys the ability to remove 5.5 after use and does NOT restore all the
                // Platform 5 files resulting in an unexpected automatic repair. Its left here just in case, Please DO NOT RE-ENABLE THIS FEATURE unless have a way round the resulting issues
                // CreateRestorePoint();

                LogMessage("Uninstall", "Removing previous versions of ASCOM....");

                //Initial setup
                bool is64BitProcess         = (IntPtr.Size == 8);
                bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();
                LogMessage("Uninstall", "OS is 64bit: " + is64BitOperatingSystem.ToString() + ", Process is 64bit: " + is64BitProcess.ToString());

                string platform4164KeyValue = null;
                string platform564aKeyValue = null;
                string platform564bKeyValue = null;
                string platform564KeyValue  = null;
                string platform5564KeyValue = null;

                bool found = false;

                if (is64BitOperatingSystem)                                     // Is a 64bit OS
                {
                    platform4164KeyValue = Read(uninstallString, platform4164); // Read the 4.1 uninstall string
                    platform5564KeyValue = Read(uninstallString, platform5564); // Read the 5.5 uninstall string
                    platform564aKeyValue = Read(uninstallString, platform564a); // Read the 5.0A uninstall string
                    platform564bKeyValue = Read(uninstallString, platform564b); // Read the 5.0B uninstall string

                    if (platform564bKeyValue != null)                           // We have a 5.0B value so go with this
                    {
                        platform564KeyValue = platform564bKeyValue;
                        LogMessage("Uninstall", "Found 64bit Platform 5.0B");
                    }
                    else if (platform564aKeyValue != null) // No 5.0B value so go  with 5.0A if it is present
                    {
                        platform564KeyValue = platform564aKeyValue;
                        LogMessage("Uninstall", "Found 64bit Platform 5.0A");
                        //Now have to fix a missing registry key that fouls up the uninstaller - this was fixed in 5B but prevents 5A from uninstalling on 64bit systems
                        RegistryKey RKey = Registry.ClassesRoot.CreateSubKey(@"AppID\{DF2EB077-4D59-4231-9CB4-C61AD4ECB874}");
                        RKey.SetValue("", "Fixed registry key value");
                        RKey.Close();
                        RKey = null;
                        LogMessage("Uninstall", @"Successfully set AppID\{DF2EB077-4D59-4231-9CB4-C61AD4ECB874}");
                    }

                    StringBuilder Path = new StringBuilder(260);
                    int           rc   = SHGetSpecialFolderPath(IntPtr.Zero, Path, CSIDL_PROGRAM_FILES_COMMONX86, 0);
                    AscomDirectory = Path.ToString() + @"\ASCOM";
                    LogMessage("Uninstall", "64bit Common Files Path: " + AscomDirectory);
                }
                else //32 bit OS
                {
                    AscomDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles) + @"\ASCOM";
                    LogMessage("Uninstall", "32bit Common Files Path: " + AscomDirectory);
                }

                string platform4132KeyValue = Read(uninstallString, platform4132);
                string platform5532KeyValue = Read(uninstallString, platform5532);
                string platform532aKeyValue = Read(uninstallString, platform532a);
                string platform532bKeyValue = Read(uninstallString, platform532b);
                string platform532KeyValue  = null;

                if (platform532bKeyValue != null) // We have a 5.0B value so go with this
                {
                    platform532KeyValue = platform532bKeyValue;
                    LogMessage("Uninstall", "Found 32bit Platform 5,0B");
                }
                else if (platform532aKeyValue != null) // No 5.0B value so go  with 5.0A if it is present
                {
                    platform532KeyValue = platform532aKeyValue;
                    LogMessage("Uninstall", "Found 32bit Platform 5,0A");
                }

                // Backup the profile based on the latest platform installed
                if ((platform5564KeyValue != null) | (platform5532KeyValue != null))
                {
                    RegAccess.BackupProfile("5.5");
                }
                else if ((platform564KeyValue != null) | (platform532KeyValue != null))
                {
                    RegAccess.BackupProfile("5");
                }
                else
                {
                    RegAccess.BackupProfile("");
                }

                //remove 5.5
                if (platform5564KeyValue != null)
                {
                    LogMessage("Uninstall", "64 Removing ASCOM 5.5... " + platform5564KeyValue);
                    found = true;
                    RunProcess(platform5564KeyValue, " /VERYSILENT /NORESTART /LOG");
                    RemoveAssembly("policy.1.0.ASCOM.DriverAccess"); // Remove left over policy file
                }
                else
                {
                    if (platform5532KeyValue != null)
                    {
                        LogMessage("Uninstall", "32 Removing ASCOM 5.5... " + platform5532KeyValue);
                        found = true;
                        RunProcess(platform5532KeyValue, " /VERYSILENT /NORESTART /LOG");
                        RemoveAssembly("policy.1.0.ASCOM.DriverAccess"); // Remove left over policy file
                    }
                }

                //remove 5.0
                if (platform564KeyValue != null)
                {
                    FixHelper("Helper.dll", 5, 0);// Original helpers should be in place at this point, check and fix if not to prevent Platform 5 uninstaller from failing
                    FixHelper("Helper2.dll", 4, 0);
                    LogMessage("Uninstall", "64 Removing ASCOM 5... " + platform564KeyValue);
                    found = true;
                    RunProcess("MsiExec.exe", SplitKey(platform564KeyValue));
                }
                else
                {
                    if (platform532KeyValue != null)
                    {
                        FixHelper("Helper.dll", 5, 0);
                        FixHelper("Helper2.dll", 4, 0);
                        LogMessage("Uninstall", "32 Removing ASCOM 5... " + platform532KeyValue);
                        found = true;
                        RunProcess("MsiExec.exe", SplitKey(platform532KeyValue));
                    }
                }

                //Remove 4.1
                //remove 5.0
                if (platform4164KeyValue != null)
                {
                    LogMessage("Uninstall", "64 Removing ASCOM 4.1... " + platform4164KeyValue);
                    found = true;

                    string[] vals = platform4164KeyValue.Split(new string[] { " " }, System.StringSplitOptions.RemoveEmptyEntries);
                    LogMessage("Uninstall", @"Found uninstall values: """ + vals[0] + @""", """ + vals[1] + @"""");

                    RunProcess(vals[0], @"/S /Z " + vals[1]);
                    CleanUp4();
                }
                else
                {
                    if (platform4132KeyValue != null)
                    {
                        LogMessage("Uninstall", "32 Removing ASCOM 4.1... " + platform4132KeyValue);
                        found = true;

                        string[] vals = platform4132KeyValue.Split(new string[] { " " }, System.StringSplitOptions.RemoveEmptyEntries);
                        LogMessage("Uninstall", @"Found uninstall values: """ + vals[0] + @""", """ + vals[1] + @"""");

                        RunProcess(vals[0], @"/S /Z " + vals[1]);
                        CleanUp4();
                    }
                }

                if (found == true)
                {
                    CleanUp55();
                    CleanUp5();
                }
                else
                {
                    LogMessage("Uninstall", "No previous platforms found");
                }

                LogMessage("Uninstall", "Setting Profile registry ACL");
                RegAccess.SetRegistryACL();

                // Restore the relevant profile based on the latest platform installed
                if ((platform5564KeyValue != null) | (platform5532KeyValue != null))
                {
                    LogMessage("Uninstall", "Restoring Platform 5.5 Profile");
                    RegAccess.RestoreProfile("5.5");
                }
                else if ((platform564KeyValue != null) | (platform532KeyValue != null))
                {
                    LogMessage("Uninstall", "Restoring Platform 5 Profile");
                    RegAccess.RestoreProfile("5");
                }

                LogMessage("Uninstall", "Disposing of registry access object");
                RegAccess.Dispose();
                RegAccess = null;
                LogMessage("Uninstall", "Completed uninstall process");
            }
            catch (Exception ex)
            {
                LogError("Uninstall", ex.ToString());
                ReturnCode = 1;
            }
            TL.Enabled = false; // Clean up tracelogger

            TL.Dispose();
            TL = null;

            Pic();
            return(ReturnCode);
        }
コード例 #32
0
ファイル: cSecurity.cs プロジェクト: nullkuhl/fsu-dev
        /// <summary>
        /// Changes key permissions
        /// </summary>
        /// <param name="RootKey"></param>
        /// <param name="SubKey"></param>
        /// <param name="AccountName"></param>
        /// <param name="AccessMask"></param>
        /// <param name="accessTypes"></param>
        /// <param name="Inheritence"></param>
        /// <returns></returns>
        public bool ChangeKeyPermissions(ROOT_KEY RootKey, string SubKey, string AccountName, RegistryAccess AccessMask, AccessTypes accessTypes, InheritenceFlags Inheritence)
        {
            // set key permissions (gate)
            IntPtr lKey = IntPtr.Zero;
            ACCOUNT_PERM tAccount = new ACCOUNT_PERM();
            SID_IDENTIFIER_AUTHORITY tAuthority = new SID_IDENTIFIER_AUTHORITY();

            try
            {
                // default account
                tAccount.AccountName = "";
                tAccount.AccessMask = (uint)ACCESS_MASK.GENERIC_READ;
                tAccount.AceFlags = (byte)CONTAINER_INHERIT_ACE;
                tAccount.AceType = (byte)ACCESS_ALLOWED_ACE_TYPE;
                tAccount.pSid = IntPtr.Zero;
                tAuthority.Value = new byte[] { 0, 0, 0, 0, 0, (byte)SECURITY_WORLD_SID_AUTHORITY };

                // test access
                if (AllocateAndInitializeSid(ref tAuthority, (byte)1, (int)SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, ref tAccount.pSid) == true)
                {
                    // set up account
                    tAccount.AccountName = AccountName;
                    tAccount.AccessMask = (uint)AccessMask;
                    tAccount.AceFlags = (byte)Inheritence;
                    tAccount.AceType = (byte)accessTypes;
                    tAccount.pSid = IntPtr.Zero;
                    tAccount.SidPassedByCaller = false;
                    // apply change to key
                    if ((RegOpenKeyEx(RootKey, SubKey, 0, (int)(READ_CONTROL | WRITE_DAC), ref lKey) == 0))
                    {
                        return SetKeyPermissions(lKey, tAccount);
                    }
                }
                return false;
            }
            finally
            {
                // cleanup
                if (lKey != IntPtr.Zero)
                {
                    RegCloseKey(lKey);
                }
                if ((tAccount.pSid != IntPtr.Zero) && (tAccount.SidPassedByCaller == true))
                {
                    FreeSid(tAccount.pSid);
                    tAccount.pSid = IntPtr.Zero;
                }
            }
        }