public CleaningInterface()
 {
     InitializeComponent();
     this.m_directoryBrowser = new FolderBrowserDialog();
     this.registry = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"Software\FileNameCleaner");
     this.SetDirectory(this.LastDirectory);
 }
 public void setFolderPath(string path)
 {
     //TODO: Optimizar esto, se crea un subdirectorio siempre
     key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Autocoim");
     key.SetValue("Folder path", path);
     key.Close();
 }
示例#3
0
        private void btnFacebookLogin_Click(object sender, EventArgs e)
        {
            key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("WowSocial", true);
            //key.SetValue("Licencia", textBox2.Text);
            //key.SetValue("Character", textBox1.Text);
            key.SetValue("Realm", comboBox1.Text);
            key.SetValue("Guild", textBox4.Text);
            key.SetValue("AppID", textBox2.Text);
            key.SetValue("PageID", textBox5.Text);
            //key.SetValue("FBID", textBox3.Text);
            key.Close();
            //if (textBox2.Text == getMD5Hash(textBox3.Text))
            //{

                //var Variab = new Variables();
                //Variables.Character = textBox1.Text;
                Variables.Realm = comboBox1.Text;
                Variables.Guild = textBox4.Text;
                Variables.AppID = textBox2.Text;
                Variables.PageID = textBox5.Text;
                // open the Facebook Login Dialog and ask for user permissions.
                var fbLoginDlg = new FacebookLoginDialog(Variables.AppID, ExtendedPermissions);
                fbLoginDlg.ShowDialog();

                // The user has taken action, either allowed/denied or cancelled the authorization,
                // which can be known by looking at the dialogs FacebookOAuthResult property.
                // Depending on the result take appropriate actions.
                TakeLoggedInAction(fbLoginDlg.FacebookOAuthResult);
            //}
            //else
            //{
            //    MessageBox.Show("Facebook ID or Licence is Wrong. Try Again","Information");
            //}
        }
示例#4
0
        public Form2()
        {
            // projecg names are loaded here

            string[] projectnames = { "All", "Jasper", "Bruin", "Merlin", "Other" };

            InitializeComponent();
            Projects.DataSource = projectnames;
            reg = Microsoft.Win32.Registry.CurrentUser;
            k = reg.OpenSubKey("OneBugNotifier");
            Microsoft.Win32.RegistryKey test = k.OpenSubKey("Project");
            if (test == null)
            {
                ProjectNotSet.Visible = true;
            }
            else
            {
                ProjectNotSet.Visible = false;
            }

            //startup check box is loaded here
            Microsoft.Win32.RegistryKey StartUpRegLoc = reg.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
            object RunValue = StartUpRegLoc.GetValue(RunRegValueName);
            if (RunValue == null)
                RunOnStartup.Checked = false;
            else
                RunOnStartup.Checked = true;

            //refresh time is loaded here
            string refresh = "OneBugNotifier"+"\\"+ RefreshTimeRegKey;
            Microsoft.Win32.RegistryKey RefeshRegLoc = reg.OpenSubKey(refresh, true);
            if (RefeshRegLoc == null)
            {
                RefreshTimeTextBox.Text = "1";
            }
            else
            {
                RefreshTimeTextBox.Text = RefeshRegLoc.GetValue(RefreshTimeVaue).ToString();
            }

            //components loaded here
            string cmpnt = "OneBugNotifier" + "\\" + "Components";
            Microsoft.Win32.RegistryKey ComponentLoc = reg.OpenSubKey(cmpnt); ;
            if (ComponentLoc == null)
            { }
            else
            {
                string ListComponent = ComponentLoc.GetValue("Name").ToString();
                string[] words = ListComponent.Split(',');
                foreach (string s in words)
                {
                    listBox2.Items.Add(s);

                }
            }
        }
示例#5
0
        /// <summary>
        /// Default constructor
        /// </summary>
        public RegistryHelper()
        {
            m_Prj2MakeSoftwareKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(
                @"SOFTWARE\MFConsulting\VSPrj2Make\settings"
                );

            if(m_Prj2MakeSoftwareKey == null)
            {
                throw new Exception("Prj2Make Add-in may not be installed correctly.");
            }
        }
示例#6
0
        public Form1()
        {
            m_ROOT = Microsoft.Win32.Registry.CurrentUser.CreateSubKey( @"Software\Patapom\TestFerroFluids" );

            InitializeComponent();

            buttonResetSliders_Click( null, EventArgs.Empty );

            Reset();
            Application.Idle += new EventHandler( Application_Idle );
        }
示例#7
0
        public WindowHelper(System.Windows.Forms.Form form, string product, string keyPrefix)
        {
            m_key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\" + product + @"\Window");
            m_form = form;

            m_topKey = keyPrefix + "Top";
            m_leftKey = keyPrefix + "Left";
            m_heightKey = keyPrefix + "Height";
            m_widthKey = keyPrefix + "Width";

            form.Load += new EventHandler(form_Load);
        }
 private void button1_Click(object sender, EventArgs e)
 {
     //SubKey erstellen, falls keiner existiert
     //Create subkey, if there isnt
     key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"" + txtPosition.Text);
     //Wert ändern oder eintragen
     //Change or add value
     key.SetValue(txtKey.Text, txtValue.Text);
     //Benutzer benachrichtigen
     //Announce the user
     MessageBox.Show("Succes!", "Succes");
 }
        public string getGPPath()
        {
            string value;

            key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Autocoim");

            if (key == null)
                return "";

            value = (string)key.GetValue("GP path");
            key.Close();
            return value;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            key_db = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\\AltisServerManager\\Database");

            if (!(txtUser.Text.Length == 0) && !(txtHost.Text.Length == 0) && !(txtPassword.Text.Length == 0) && !(txtDatabase.Text.Length == 0))
            {
                key_db.SetValue("dbName", txtDatabase.Text);
                key_db.SetValue("dbHost", txtHost.Text);
                key_db.SetValue("dbPass", txtPassword.Text);
                key_db.SetValue("dbUser", txtUser.Text);
            }
            else
            {
                MessageBox.Show("Error - Pleas check the textboxes", "Error");
            }
        }
        public static bool _OpenSubKey_Microsoft_Win32_RegistryKey_System_String_System_Boolean( )
        {
            //class object
            Microsoft.Win32.RegistryKey _Microsoft_Win32_RegistryKey = new Microsoft.Win32.RegistryKey();

               //Parameters
               System.String name = null;
               System.Boolean writable = false;

               //ReturnType/Value
               Microsoft.Win32.RegistryKey returnVal_Real = null;
               Microsoft.Win32.RegistryKey returnVal_Intercepted = null;

               //Exception
               System.Exception exception_Real = null;
               System.Exception exception_Intercepted = null;

               InterceptionMaintenance.disableInterception( );

               try
               {
              returnVal_Real = _Microsoft_Win32_RegistryKey.OpenSubKey(name,writable);
               }

               catch( System.Exception e )
               {
              exception_Real = e;
               }

               InterceptionMaintenance.enableInterception( );

               try
               {
              returnVal_Intercepted = _Microsoft_Win32_RegistryKey.OpenSubKey(name,writable);
               }

               catch( System.Exception e )
               {
              exception_Intercepted = e;
               }

               return( ( exception_Real.Messsage == exception_Intercepted.Message ) && ( returnValue_Real == returnValue_Intercepted ) );
        }
        public static bool _OpenRemoteBaseKey_Microsoft_Win32_RegistryHive_System_String( )
        {
            //class object
            Microsoft.Win32.RegistryKey _Microsoft_Win32_RegistryKey = new Microsoft.Win32.RegistryKey();

               //Parameters
               Microsoft.Win32.RegistryHive hKey = null;
               System.String machineName = null;

               //ReturnType/Value
               Microsoft.Win32.RegistryKey returnVal_Real = null;
               Microsoft.Win32.RegistryKey returnVal_Intercepted = null;

               //Exception
               System.Exception exception_Real = null;
               System.Exception exception_Intercepted = null;

               InterceptionMaintenance.disableInterception( );

               try
               {
              returnVal_Real = _Microsoft_Win32_RegistryKey.OpenRemoteBaseKey(hKey,machineName);
               }

               catch( System.Exception e )
               {
              exception_Real = e;
               }

               InterceptionMaintenance.enableInterception( );

               try
               {
              returnVal_Intercepted = _Microsoft_Win32_RegistryKey.OpenRemoteBaseKey(hKey,machineName);
               }

               catch( System.Exception e )
               {
              exception_Intercepted = e;
               }

               return( ( exception_Real.Messsage == exception_Intercepted.Message ) && ( returnValue_Real == returnValue_Intercepted ) );
        }
        public static bool _GetValue_Microsoft_Win32_RegistryKey_System_String_System_Object( )
        {
            //class object
            Microsoft.Win32.RegistryKey _Microsoft_Win32_RegistryKey = new Microsoft.Win32.RegistryKey();

               //Parameters
               System.String name = null;
               System.Object defaultValue = null;

               //ReturnType/Value
               System.Object returnVal_Real = null;
               System.Object returnVal_Intercepted = null;

               //Exception
               System.Exception exception_Real = null;
               System.Exception exception_Intercepted = null;

               InterceptionMaintenance.disableInterception( );

               try
               {
              returnVal_Real = _Microsoft_Win32_RegistryKey.GetValue(name,defaultValue);
               }

               catch( System.Exception e )
               {
              exception_Real = e;
               }

               InterceptionMaintenance.enableInterception( );

               try
               {
              returnVal_Intercepted = _Microsoft_Win32_RegistryKey.GetValue(name,defaultValue);
               }

               catch( System.Exception e )
               {
              exception_Intercepted = e;
               }

               return( ( exception_Real.Messsage == exception_Intercepted.Message ) && ( returnValue_Real == returnValue_Intercepted ) );
        }
        public static bool _CreateObjRef_Microsoft_Win32_RegistryKey_System_Type( )
        {
            //class object
            Microsoft.Win32.RegistryKey _Microsoft_Win32_RegistryKey = new Microsoft.Win32.RegistryKey();

               //Parameters
               System.Type requestedType = null;

               //ReturnType/Value
               System.Runtime.Remoting.ObjRef returnVal_Real = null;
               System.Runtime.Remoting.ObjRef returnVal_Intercepted = null;

               //Exception
               System.Exception exception_Real = null;
               System.Exception exception_Intercepted = null;

               InterceptionMaintenance.disableInterception( );

               try
               {
              returnVal_Real = _Microsoft_Win32_RegistryKey.CreateObjRef(requestedType);
               }

               catch( System.Exception e )
               {
              exception_Real = e;
               }

               InterceptionMaintenance.enableInterception( );

               try
               {
              returnVal_Intercepted = _Microsoft_Win32_RegistryKey.CreateObjRef(requestedType);
               }

               catch( System.Exception e )
               {
              exception_Intercepted = e;
               }

               return( ( exception_Real.Messsage == exception_Intercepted.Message ) && ( returnValue_Real == returnValue_Intercepted ) );
        }
        public static bool _CreateSubKey_Microsoft_Win32_RegistryKey_System_String( )
        {
            //class object
            Microsoft.Win32.RegistryKey _Microsoft_Win32_RegistryKey = new Microsoft.Win32.RegistryKey();

               //Parameters
               System.String subkey = null;

               //ReturnType/Value
               Microsoft.Win32.RegistryKey returnVal_Real = null;
               Microsoft.Win32.RegistryKey returnVal_Intercepted = null;

               //Exception
               System.Exception exception_Real = null;
               System.Exception exception_Intercepted = null;

               InterceptionMaintenance.disableInterception( );

               try
               {
              returnVal_Real = _Microsoft_Win32_RegistryKey.CreateSubKey(subkey);
               }

               catch( System.Exception e )
               {
              exception_Real = e;
               }

               InterceptionMaintenance.enableInterception( );

               try
               {
              returnVal_Intercepted = _Microsoft_Win32_RegistryKey.CreateSubKey(subkey);
               }

               catch( System.Exception e )
               {
              exception_Intercepted = e;
               }

               return( ( exception_Real.Messsage == exception_Intercepted.Message ) && ( returnValue_Real == returnValue_Intercepted ) );
        }
        public static bool _InitializeLifetimeService_Microsoft_Win32_RegistryKey( )
        {
            //class object
            Microsoft.Win32.RegistryKey _Microsoft_Win32_RegistryKey = new Microsoft.Win32.RegistryKey();

               //Parameters

               //ReturnType/Value
               System.Object returnVal_Real = null;
               System.Object returnVal_Intercepted = null;

               //Exception
               System.Exception exception_Real = null;
               System.Exception exception_Intercepted = null;

               InterceptionMaintenance.disableInterception( );

               try
               {
              returnVal_Real = _Microsoft_Win32_RegistryKey.InitializeLifetimeService();
               }

               catch( System.Exception e )
               {
              exception_Real = e;
               }

               InterceptionMaintenance.enableInterception( );

               try
               {
              returnVal_Intercepted = _Microsoft_Win32_RegistryKey.InitializeLifetimeService();
               }

               catch( System.Exception e )
               {
              exception_Intercepted = e;
               }

               return( ( exception_Real.Messsage == exception_Intercepted.Message ) && ( returnValue_Real == returnValue_Intercepted ) );
        }
        public PlaybackDevice()
        {
            devList = new List<string>();
            regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Multimedia\Sound Mapper", true);
            if (regKey == null)
                regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Multimedia", true).CreateSubKey("Sound Mapper");
            defaultPlayback = regKey.GetValue("Playback") as string;

            /*devColl = new DevicesCollection();
            foreach (DeviceInformation dev in devColl)
            {
                if (dev.ModuleName == "")
                    continue;

                devList.Insert(0, dev.Description);
            }*/

            mMixers = new Mixers();
            foreach (MixerDetail mixerDetail in mMixers.Playback.Devices)
                devList.Add(mixerDetail.MixerName);
        }
        public static bool _SetValue_Microsoft_Win32_RegistryKey_System_String_System_Object( )
        {
            //class object
            Microsoft.Win32.RegistryKey _Microsoft_Win32_RegistryKey = new Microsoft.Win32.RegistryKey();

               //Parameters
               System.String name = null;
               System.Object _value = null;

               //Exception
               System.Exception exception_Real = null;
               System.Exception exception_Intercepted = null;

               InterceptionMaintenance.disableInterception( );

               try
               {
            _Microsoft_Win32_RegistryKey.SetValue(name,_value);
               }

               catch( System.Exception e )
               {
              exception_Real = e;
               }

               InterceptionMaintenance.enableInterception( );

               try
               {
            _Microsoft_Win32_RegistryKey.SetValue(name,_value);
               }

               catch( System.Exception e )
               {
              exception_Intercepted = e;
               }

               return( ( exception_Real.Message == exception_Intercepted.Message ));
        }
        public static bool _DeleteSubKey_Microsoft_Win32_RegistryKey_System_String_System_Boolean( )
        {
            //class object
            Microsoft.Win32.RegistryKey _Microsoft_Win32_RegistryKey = new Microsoft.Win32.RegistryKey();

               //Parameters
               System.String subkey = null;
               System.Boolean throwOnMissingSubKey = false;

               //Exception
               System.Exception exception_Real = null;
               System.Exception exception_Intercepted = null;

               InterceptionMaintenance.disableInterception( );

               try
               {
            _Microsoft_Win32_RegistryKey.DeleteSubKey(subkey,throwOnMissingSubKey);
               }

               catch( System.Exception e )
               {
              exception_Real = e;
               }

               InterceptionMaintenance.enableInterception( );

               try
               {
            _Microsoft_Win32_RegistryKey.DeleteSubKey(subkey,throwOnMissingSubKey);
               }

               catch( System.Exception e )
               {
              exception_Intercepted = e;
               }

               return( ( exception_Real.Message == exception_Intercepted.Message ));
        }
        public static bool _Close_Microsoft_Win32_RegistryKey( )
        {
            //class object
            Microsoft.Win32.RegistryKey _Microsoft_Win32_RegistryKey = new Microsoft.Win32.RegistryKey();

               //Parameters

               //Exception
               System.Exception exception_Real = null;
               System.Exception exception_Intercepted = null;

               InterceptionMaintenance.disableInterception( );

               try
               {
              _Microsoft_Win32_RegistryKey.Close();
               }

               catch( System.Exception e )
               {
              exception_Real = e;
               }

               InterceptionMaintenance.enableInterception( );

               try
               {
              _Microsoft_Win32_RegistryKey.Close();
               }

               catch( System.Exception e )
               {
              exception_Intercepted = e;
               }

               return( ( exception_Real.Message == exception_Intercepted.Message ));
        }
示例#21
0
        void ClassInit(string DefaultOysterAddress,int DefaultOysterConnectionPort,int DefaultOysterFilePort,string DefaultOysterDeviceID,string OysterDeviceFriendlyName, bool ManualConfiguration,
			RecordOptions.ScreenRecordType RecordType,
			string WindowTitleToRecord,
			ScreenEncoder.CapturePerformance ScreenCapturePerformance,
			RecordOptions.CameraSelection CamerasSelected,
			int MinutesToRecord, int SecondsToCountdown,
			string ScreenProfileDirectory, string ScreenWMVDirectory,
			RecordOptions.PrimaryCamera CameraPrimary)
        {
            //			System.Reflection.AssemblyTitleAttribute ata = (System.Reflection.AssemblyTitleAttribute)
            //				System.Attribute.GetCustomAttribute(System.Reflection.Assembly.GetAssembly(typeof(DesktopRecorder.RecordOptions)),
            //				typeof(System.Reflection.AssemblyTitleAttribute));
            m_RegKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(
                @"SOFTWARE\Carver Lab\Oyster\" + CarverLab.Utility.AppInfo.Title);
            if (m_RegKey == null)
            {
                throw new System.ApplicationException("Could not open Carver Lab registry key.");
            }
            RegistryInit(DefaultOysterAddress,DefaultOysterConnectionPort,DefaultOysterFilePort,DefaultOysterDeviceID,OysterDeviceFriendlyName,ManualConfiguration,
                RecordType,WindowTitleToRecord,
                ScreenCapturePerformance,CamerasSelected,MinutesToRecord,SecondsToCountdown,
                ScreenProfileDirectory,ScreenWMVDirectory,
                CameraPrimary);
        }
        /// <summary>
        /// Returns .Net installation information.
        /// </summary>
        public static string GetInstalled()
        {
            string output = "";

            try
            {
                using (Microsoft.Win32.RegistryKey ndpKey = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\"))
                {
                    foreach (string versionKeyName in ndpKey.GetSubKeyNames())
                    {
                        if (versionKeyName.StartsWith("v"))
                        {
                            Microsoft.Win32.RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
                            string name    = (string)versionKey.GetValue("Version", "");
                            string sp      = versionKey.GetValue("SP", "").ToString();
                            string install = versionKey.GetValue("Install", "").ToString();
                            if (string.IsNullOrEmpty(install))
                            {
                                //no install info, ust be later
                                output += versionKeyName + "  " + name + Environment.NewLine;
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(sp) && install == "1")
                                {
                                    output += versionKeyName + "  " + name + "  SP" + sp + Environment.NewLine;
                                }
                            }
                            if (!string.IsNullOrEmpty(name))
                            {
                                continue;
                            }
                            foreach (string subKeyName in versionKey.GetSubKeyNames())
                            {
                                Microsoft.Win32.RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
                                name = (string)subKey.GetValue("Version", "");
                                if (!string.IsNullOrEmpty(name))
                                {
                                    sp = subKey.GetValue("SP", "").ToString();
                                }
                                install = subKey.GetValue("Install", "").ToString();
                                if (string.IsNullOrEmpty(install))
                                {
                                    //no install info, ust be later
                                    output += versionKeyName + "  " + name + Environment.NewLine;
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(sp) && install == "1")
                                    {
                                        output += "  " + subKeyName + "  " + name + "  SP" + sp + Environment.NewLine;
                                    }
                                    else if (install == "1")
                                    {
                                        output += "  " + subKeyName + "  " + name + Environment.NewLine;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                output += "Error getting .Net installation information.";
            }

            return(output);
        }
示例#23
0
        private void button1_Click(object sender, EventArgs e)
        {
            ProjectNotSet.Visible = true;
            //Run at start up
            if (RunOnStartup.Checked == true)
            {
                // write the regisrty
                // MessageBox.Show("box is checked");
                string CurrentDirectory =  System.IO.Directory.GetCurrentDirectory();
                //string AppPath = CurrentDirectory + "\\WindowsFormsApplication2.exe";
                string AppPath = CurrentDirectory + "\\OneBugNotifier.exe";
                Microsoft.Win32.RegistryKey StartUpRegLoc = reg.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
               // StartUpRegLoc.SetValue("OneBugNotifier", @"C:\Users\kirankumar\Documents\WindowsFormsApplication2\WindowsFormsApplication2\bin\Debug\WindowsFormsApplication2.exe");
                StartUpRegLoc.SetValue("OneBugNotifier", AppPath);
            }
            else
            {
                Microsoft.Win32.RegistryKey StartUpRegLoc = reg.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);

                try
                {
                    StartUpRegLoc = reg.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                    StartUpRegLoc.DeleteValue("OneBugNotifier");
                }
                catch (Exception e1)
                {
                }

            }

            // Project file and personal query setting on registry
            if (ProjectNotSet.Visible == true)
            {
                k = reg.CreateSubKey("OneBugNotifier");
                Microsoft.Win32.RegistryKey UserProj = k.CreateSubKey("Project");
                string ProjectSelected = "";
                if (Projects.Text.Contains("other"))
                {
                    ProjectSelected = textBox1.Text;
                }
                else
                {
                    ProjectSelected = Projects.Text;
                }

                if(ProjectSelected.Contains("All"))
                    ProjectSelected = "";
                UserProj.SetValue("Name", ProjectSelected, Microsoft.Win32.RegistryValueKind.String);
                UserProj.SetValue(PersonalQueryReg, "True");
            }

            //refresh time setting

            if (ProjectNotSet.Visible == true)
            {
                k = reg.CreateSubKey("OneBugNotifier");
                Microsoft.Win32.RegistryKey UserProj = k.CreateSubKey(RefreshTimeRegKey);
                UserProj.SetValue(RefreshTimeVaue, RefreshTimeTextBox.Text, Microsoft.Win32.RegistryValueKind.String);
                DateTime now = DateTime.Now.ToUniversalTime();
                string nowStr = now.ToString("yyyy-MM-dd HH:mm:ss");
                reg = Microsoft.Win32.Registry.CurrentUser;
                k = reg.OpenSubKey("OneBugNotifier");
                UserProj = k.OpenSubKey("RefreshTime", true);
                Object lastQt = UserProj.GetValue("LastQueryTime");
                if (lastQt == null)
                    UserProj.SetValue("LastQueryTime", nowStr, Microsoft.Win32.RegistryValueKind.String);

            }

            //component setting

            if (ProjectNotSet.Visible == true)
            {
                try
                {

                    // cmpnt = k.OpenSubKey("Components", true);
                    string s = "";
                    foreach (string st in listBox2.Items)
                    {
                        s = s + st + ",";
                    }
                    if(s.Length >=1)
                    s = s.Remove(s.Length - 1);
                    reg = Microsoft.Win32.Registry.CurrentUser;
                    k = reg.CreateSubKey("OneBugNotifier");
                    Microsoft.Win32.RegistryKey cmpnt = k.CreateSubKey(Cmpntreg);
                    cmpnt.SetValue(test, s, Microsoft.Win32.RegistryValueKind.String);

                }
                catch (Exception ec)
                {
                   // MessageBox.Show("Exception");

                }
            }

            this.Close();
        }
        /// <summary>
        /// ファイルを更新/削除する
        /// </summary>
        /// <param name="sorcFileName"></param>
        /// <param name="destFileName"></param>
        /// <param name="tempFileName"></param>
        public static void UpdateFile(string sorcFileName, string destFileName, string tempFileName, ref StringBuilder log)
        {
            log.Append("UpdateFile(" + sorcFileName + "," + destFileName + "," + tempFileName + "\r\n");

            // テンポラリ ファイルを削除する
            if (tempFileName != null)
            {
                string _tempFileName = Path.GetFileName(tempFileName);
                log.Append(" (" + _tempFileName + " != null)\r\n");

                if (File.Exists(tempFileName))
                {
                    log.Append(" File.Exists(" + _tempFileName + ")\r\n");

                    try
                    {
                        File.Delete(tempFileName);
                        log.Append(" File.Delete(" + _tempFileName + ")\r\n");
                    }
                    catch (Exception exp)
                    {
                        Debug.WriteLine(exp.Message);
                        log.Append(" " + exp.Message + "\r\n");
                    }
                }
            }

            // ファイルを更新する
            if ((sorcFileName != null) && (destFileName != null))
            {
                string _sorcFileName = Path.GetFileName(sorcFileName);
                string _destFileName = Path.GetFileName(destFileName);
                log.Append(" (" + _sorcFileName + " != null) && (" + _destFileName + " != null)\r\n");

                try
                {
                    File.Copy(sorcFileName, destFileName, true);
                    log.Append(" File.Copy(" + _sorcFileName + ", " + _destFileName + ", true)\r\n");
                }
                catch (IOException ioexp)                       // 別のプロセスで使用されているため?
                {
                    Debug.WriteLine(ioexp.Message);
                    log.Append(" " + ioexp.Message + "\r\n");
                    string _tempFileName = Path.GetFileName(tempFileName);

                    try
                    {
                        // とりあえず、curFileName を一時ファイルにリネームして、newFileName をコピーしておく
                        File.Move(destFileName, tempFileName);
                        log.Append(" File.Move(" + _destFileName + ", " + _tempFileName + ")\r\n");
                        File.Copy(sorcFileName, destFileName, true);
                        log.Append(" File.Copy(" + _sorcFileName + ", " + _destFileName + ", true)\r\n");
                    }
                    catch (Exception exp)
                    {
                        Debug.WriteLine(exp.Message);
                        log.Append(" " + exp.Message + "\r\n");

#if true
                        try
                        {
                            // MoveFileEx を使ってコピーする
                            string subKeyName = @"SYSTEM\CurrentControlSet\Control\Session Manager";
                            Microsoft.Win32.RegistryKey regKey   = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(subKeyName);
                            string[] pendingFileRenameOperations = (string[])regKey.GetValue("PendingFileRenameOperations");
                            regKey.Close();
                            log.Append(" LocalMachine.OpenSubKey(" + subKeyName + ")\r\n");
                            log.Append(" PendingFileRenameOperations\r\n");

                            string sorcMoveFileName  = sorcFileName + ".move";
                            string _sorcMoveFileName = Path.GetFileName(sorcMoveFileName);

                            bool alreadyPending = false;
                            if (pendingFileRenameOperations != null)
                            {
                                for (int i = 0; i < pendingFileRenameOperations.Length / 2; i++)
                                {
                                    log.Append("  " + pendingFileRenameOperations[(i * 2) + 0] + "\r\n");
                                    log.Append("  " + pendingFileRenameOperations[(i * 2) + 1] + "\r\n");

                                    if (pendingFileRenameOperations[(i * 2) + 0].IndexOf(sorcMoveFileName) != -1)
                                    {
                                        alreadyPending = true;
                                        //break;
                                    }
                                }
                            }

                            if (!alreadyPending)
                            {
                                File.Copy(sorcFileName, sorcMoveFileName, true);
                                log.Append(" File.Copy(" + _sorcFileName + ", " + _sorcMoveFileName + ", true)\r\n");
                                bool res = api.MoveFileEx(sorcMoveFileName, destFileName, api.MOVEFILE_REPLACE_EXISTING | api.MOVEFILE_DELAY_UNTIL_REBOOT);
                                Debug.WriteLine("MoveFileEx:" + res);
                                log.Append(" " + res + " = api.MoveFileEx(" + _sorcMoveFileName + ", " + _destFileName + ", api.MOVEFILE_REPLACE_EXISTING | api.MOVEFILE_DELAY_UNTIL_REBOOT)\r\n");
                            }
                        }
                        catch (Exception _exp)
                        {
                            Debug.WriteLine(_exp.Message);
                            log.Append(" " + _exp.Message + "\r\n");
                        }
#endif
                    }
                }
                catch (Exception exp)
                {
                    Debug.WriteLine(exp.Message);
                    log.Append(" " + exp.Message + "\r\n");
                }
            }
            // ファイルを削除する
            else if ((sorcFileName == null) && (destFileName != null))
            {
                string _destFileName = Path.GetFileName(destFileName);
                log.Append(" (sorcFileName == null) && (" + _destFileName + " != null)\r\n");

                try
                {
                    File.Delete(destFileName);
                    log.Append(" File.Delete(" + _destFileName + ")\r\n");
                }
                catch (UnauthorizedAccessException uaexp)                       // アクセスが拒否されました?
                {
                    Debug.WriteLine(uaexp.Message);
                    log.Append(" " + uaexp.Message + "\r\n");
                    string _tempFileName = Path.GetFileName(tempFileName);

                    try
                    {
                        File.Move(destFileName, tempFileName);
                        log.Append(" File.Move(" + _destFileName + ", " + _tempFileName + ")\r\n");
                    }
                    catch (Exception exp)
                    {
                        Debug.WriteLine(exp.Message);
                        log.Append(" " + exp.Message + "\r\n");
                    }
                }
                catch (Exception exp)
                {
                    Debug.WriteLine(exp.Message);
                    log.Append(" " + exp.Message + "\r\n");
                }
            }
        }
示例#25
0
        static public void Parse(User user, string login, string password, bool showGapes, bool showTeachers)
        {
            string data = "Login="******"&Password="******"&doLogin=1";

            using (WebBrowser webBrowser1 = new WebBrowser())
            {
                webBrowser1.ScriptErrorsSuppressed = true;
                // Отключаем загрузку картнок
                Microsoft.Win32.RegistryKey myRegKey = Microsoft.Win32.Registry.CurrentUser;
                myRegKey = myRegKey.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main", true);
                myRegKey.SetValue("Display Inline Images", "no");
                webBrowser1.Navigate("https://petersburgedu.ru/user/auth/login", "_self", System.Text.ASCIIEncoding.ASCII.GetBytes(data), "Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
                while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }
                webBrowser1.Navigate("https://petersburgedu.ru/dnevnik/cabinet");
                while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }
                cabinetPage.LoadHtml(webBrowser1.DocumentText);
                if (cabinetPage.ToString().Contains("Ресурс временно недоступен"))
                {
                    user.serverAccessesability = false;
                    //Console.WriteLine("Ресурс временно недоступен, приносим свои извинения");
                }
                else
                {
                    user.serverAccessesability = true;
                }
                // If there only one student, program will do that it must do
                students = cabinetPage.DocumentNode.SelectNodes("//div[@class=\"user-box\"]/div[@class=\"heading\"]/div[@class=\"fio\"]/a");
                teachersListCollection = cabinetPage.DocumentNode.SelectNodes("//div[@class=\"popupContent\"]/div/table[@class=\"teachers-mail-list\"]");
                // Parsing Marks Page Adress for every student
                marksLinks = cabinetPage.DocumentNode.SelectNodes("//a[@class=\"marks\"]");

                if (students != null && marksLinks != null)
                {
                    List <string> userNames    = new List <string>();
                    List <string> userGrades   = new List <string>();
                    List <string> userTeachers = new List <string>();
                    for (int studentNum = 0; studentNum < students.Count; studentNum++)
                    {
                        webBrowser1.Navigate("https://petersburgedu.ru" + marksLinks[studentNum].Attributes["href"].Value);
                        while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
                        {
                            Application.DoEvents();
                        }

                        // NAME ---------------------------------------------------------------------------------------
                        marksPage.LoadHtml(webBrowser1.DocumentText);
                        if (students.Count > 1)
                        {
                            nameNode             = marksPage.DocumentNode.SelectSingleNode("//div[@class=\"title\"]");
                            user.multipleStudent = true; // Несколько учащихся в аккаунте
                        }
                        else
                        {
                            nameNode             = marksPage.DocumentNode.SelectSingleNode("//h2[@class=\"student-title\"]");
                            user.multipleStudent = false;
                        }
                        if (nameNode != null)
                        {
                            string t = nameNode.InnerText.ToString().Trim();
                            if (user.multipleStudent)
                            {
                                name = t;
                            }
                            else
                            {
                                name = t.Substring(0, t.LastIndexOf(',')) + " " + t.Split(',')[2];
                            }
                        }
                        // GRADES ---------------------------------------------------------------------------------------
                        lessonNamesCollection = marksPage.DocumentNode.SelectNodes("//div[@class=\"lessons-list\"]/div[@class=\"cell\"]");
                        finalGradesCollection = marksPage.DocumentNode.SelectNodes("//table[@class=\"marks-summary\"]/tbody/tr/td[1]");
                        gapesCollection       = marksPage.DocumentNode.SelectNodes("//table[@class=\"marks-summary\"]/tbody/tr/td[2]");
                        if (lessonNamesCollection != null)
                        {
                            fullData = "";
                            for (int i = 0; i < lessonNamesCollection.Count; i++)
                            {
                                gradesCollection = marksPage.DocumentNode.SelectNodes("//table[@class=\"marks-table\"]/tbody/tr/td/div[" + (i + 1).ToString() + "]/span[@class=\"grade\"]");
                                // Lesson name and Final Grade output
                                float  average = 0f, sum = 0f;
                                string gradesList = "";
                                if (gradesCollection != null)
                                {
                                    for (int j = 0; j < gradesCollection.Count; j++)
                                    {
                                        // Normal grades parsing
                                        if (gradesCollection[j].InnerText.Length < 2)
                                        {
                                            sum        += Byte.Parse(gradesCollection[j].InnerText);
                                            gradesList += gradesCollection[j].InnerText.ToString().Trim();
                                        }
                                    }
                                    average = sum / gradesCollection.Count;
                                }
                                string gapeStr    = (showGapes) ? " [" + gapesCollection[i].InnerText.ToString().Trim() + "]\n" : "\n";
                                string averageStr = (gradesCollection != null) ? "   [Средняя: " + average + "]\n" : "   Оценок нет";
                                string finalStr   = (finalGradesCollection[i] != null && finalGradesCollection[i].InnerText.ToString().Trim() != "") ? "     [Итоговая: " + finalGradesCollection[i].InnerText.ToString().Trim() + "]\n" : "";
                                fullData += lessonNamesCollection[i].InnerText.ToString().Trim() + gapeStr + averageStr + finalStr + "   " + gradesList + "\n";
                            }
                        }


                        // TEACHERS ---------------------------------------------------------------------------------------
                        if (showTeachers)
                        {
                            teachersListHeaders = teachersListCollection[studentNum].SelectNodes("//div/div/div/div/h2");
                            lessonsList         = teachersListCollection[studentNum].SelectNodes("//tr/td[@class=\"lesson\"]/span");
                            teachersList        = teachersListCollection[studentNum].SelectNodes("//tr/td[2]/span[@class=\"container\"]/span");
                            if (lessonsList != null && teachersList != null && teachersListHeaders != null)
                            {
                                teachers = "";
                                do
                                {
                                    if (lessonsList[lessonCounter].InnerText.ToString() != "&nbsp" && lessonsList[lessonCounter].InnerText.ToString() != " ")
                                    {
                                        teachers += lessonsList[lessonCounter].InnerText.ToString().Trim() + " — " + teachersList[lessonCounter].InnerText.ToString().Trim() + "\n";
                                    }

                                    if (lessonCounter < Math.Min(lessonsList.Count, teachersList.Count) - 1)
                                    {
                                        lessonCounter++;
                                    }

                                    if (lessonsList[lessonCounter].InnerText.ToString().Trim() == "Классный руководитель")
                                    {
                                        break;
                                    }
                                } while (lessonCounter < Math.Min(lessonsList.Count, teachersList.Count) - 1);
                            }
                        }
                        else
                        {
                            teachers = "";
                        }
                        if (nameNode != null)
                        {
                            userNames.Add(name);        // Name
                            userGrades.Add(fullData);   // Grades
                            userTeachers.Add(teachers); // Teachers
                        }
                    }
                    user.Names    = userNames;
                    user.Grades   = userGrades;
                    user.Teachers = userTeachers;
                }
                else
                {
                    if (!user.serverAccessesability)
                    {
                        // на ремонте
                    }
                    else
                    {
                        // хз почему
                    }
                    // Обработка ошибки, когда не удается получить данные учащихся на этапе загрузки кабинета
                }
                // Возвращаем стандартное значение
                myRegKey.SetValue("Display Inline Images", "yes");
            }
        }
示例#26
0
        public void forPrinting()
        {
            string       dataHtml = "";
            StreamWriter sw       = new StreamWriter(System.IO.Path.GetTempPath() + "\\tempData.htm");

            dataHtml = "<head></head><body>" +
                       "<table style='font-size: 14pt; font-family: Tahoma; width: 100%;'>" +
                       "<tr >" +
                       "<th><span style='text-align:left;'>Кассир: " + UserValues.CurrentUser + "</span></th>" +
                       "</tr>" +
                       "<tr style = 'text-align:left;'>" +
                       "<th><b><span style='font-size:14pt;'>Наличка: " + nal.Text + "</span></b></th>" +
                       "</tr>" +
                       "<tr style = 'text-align:left;'>" +
                       "<th><b><span style='font-size:14pt;'> Терминал: " + terminal.Text + "</span></b> </th>" +
                       "</tr>" +
                       "<tr style = 'text-align:left;'>" +
                       "<th><b><span style='font-size:14pt;'> Возврат: " + back.Text + "</span></b></th>" +
                       "</tr>" +
                       "<tr style = 'text-align:left;'>" +
                       "<th><b><span style='font-size:14pt;'> Долги: " + debt.Text + "</span></b></th>" +
                       "</tr>" +
                       "<tr style = 'text-align:left;'>" +
                       "<th><b><span style='font-size:14pt;'> Итого: " + all.Text + "</span></b> </th>" +
                       "</tr>" +
                       "<tr style = 'text-align:left;'>" +
                       "<th><b><span style='font-size:14pt;'> Начало смены " + Smena.Text + "</span></b> </th>" +
                       "</tr>" +
                       "<tr style = 'text-align:left;'>" +
                       "<th><b><span style='font-size:14pt;'> Конец смены " + DateTime.Now.ToString() + "</span></b> </th>" +
                       "</tr>" +
                       "</table>" +
                       "</body>";

            sw.Write(dataHtml);
            sw.Close();
            string keyName = @"Software\Microsoft\Internet Explorer\PageSetup";

            using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyName, true))
            {
                if (key != null)
                {
                    string old_footer = (string)key.GetValue("footer");
                    string old_header = (string)key.GetValue("header");
                    key.SetValue("footer", "");
                    key.SetValue("header", "");

                    WebBrowser browser = new WebBrowser();
                    browser.DocumentText       = dataHtml;
                    browser.DocumentCompleted += browser_DocumentCompleted;
                    browser.Print();
                    if (old_footer != null)
                    {
                        key.SetValue("footer", old_footer);
                    }
                    if (old_header != null)
                    {
                        key.SetValue("header", old_header);
                    }
                }
            }
        }
示例#27
0
        public static string ConnectApi()
        {
            Logger.Info("Oauth token is " + Properties.Settings.Default.OAuthToken);
            if (Properties.Settings.Default.OAuthToken != "")
            {
                Logger.Info("Authenticating with OAuth token...");
                return("");
            }

            /* Connect to the API here. */
            Logger.Debug("No OAuth token stored, attempting to authorize app.");
            ProcessStartInfo proc = new ProcessStartInfo
            {
                UseShellExecute  = true,
                WorkingDirectory = Environment.CurrentDirectory,
                FileName         = Process.GetCurrentProcess().MainModule.FileName,
                Verb             = "runas"
            };

            Logger.Debug("Requesting identity.");
            WindowsIdentity  identity  = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);

            Logger.Debug("Checking registry key...");
            if (Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"RatTracker\shell\open\command", false) == null)
            {
                Logger.Debug("No custom URI configured for RatTracker.");
            }
            else
            {
                Logger.Debug("An URI handler is set, checking...");
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"RatTracker\shell\open\command", false);
                if (key != null)
                {
                    string mypath = (string)key.GetValue("");
                    Logger.Debug("Have a URI handler registered: " + mypath + " and my procname is " + proc.FileName);
                    if (!mypath.Contains(proc.FileName))
                    {
                        Logger.Debug("URI handler is not set to current version of RatTracker, resetting...");
                    }
                    else
                    {
                        Logger.Debug("RatTracker URI is properly configured, launching OAuth authentication process.");
                        var authcontent = new UriBuilder(Path.Combine(Properties.Settings.Default.APIURL + "oauth2/authorise?client_id=" + Properties.Settings.Default.ClientID + "&scope=*&redirect_uri=rattracker://auth&state=preinit&response_type=code"))
                        {
                            Port = Properties.Settings.Default.APIPort
                        };
                        Process.Start(authcontent.ToString());
                        Process.GetCurrentProcess().Kill();
                        return("");
                    }
                }
            }

            Logger.Debug("Passing elevation check.");
            if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                Logger.Debug("Not running as administrator, requesting elevation.");
                try
                {
                    Logger.Debug("Not admin and key does not exist, requesting elevation.");
                    MessageBoxResult result = MessageBox.Show("RatTracker needs to set up a custom URL handler to handle OAuth authentication. This requires elevated privileges. Please click OK to restart RatTracker as Administrator. It will restart with normal privileges once the OAuth process is complete.", "RT Needs elevation", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                    switch (result)
                    {
                    case MessageBoxResult.Yes:
                        Process.Start(proc);
                        Process.GetCurrentProcess().Kill();                                  // Die! DIEEE!!!
                        break;

                    case MessageBoxResult.No:
                        MessageBox.Show("RatTracker will not be able to connect to the API in this state! Continuing, but this will probably break RT.");
                        break;
                    }
                }
                catch
                {
                    // Do nothing and return ...
                    return("");
                }
            }

            try
            {
                Logger.Debug("Creating registry key");
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.ClassesRoot;
                key.CreateSubKey("RatTracker", true);
                key = key.OpenSubKey("RatTracker", true);
                if (key != null)
                {
                    key.SetValue("URL Protocol", "");
                    key.SetValue("DefaultIcon", "");
                    key.CreateSubKey("shell", true);
                    key = key.OpenSubKey("shell", true);
                    if (key != null)
                    {
                        key.CreateSubKey("open", true);
                        key = key.OpenSubKey("open", true);
                        if (key != null)
                        {
                            key.CreateSubKey("command", true);
                            key = key.OpenSubKey("command", true);
                            if (key != null)
                            {
                                key.SetValue("", "\"" + Process.GetCurrentProcess().MainModule.FileName + "\" \"%1\"");
                            }
                        }
                    }
                }
                Logger.Debug("Launching authorization process.");
                var authcontent =
                    new UriBuilder(Path.Combine(Properties.Settings.Default.APIURL + "oauth2/authorise?client_id=" + Properties.Settings.Default.ClientID + "&scope=*&redirect_uri=rattracker://auth&state=preinit&response_type=code"))
                {
                    Port = Properties.Settings.Default.APIPort
                };
                Process.Start(authcontent.ToString());
                Process.GetCurrentProcess().Kill();
                return("");
            }
            catch (Exception ex)
            {
                Logger.Fatal("Exception in ConnectAPI: ", ex);
                return("");
            }
        }
示例#28
0
        public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
        {
            if (variable == null)
            {
                throw new ArgumentNullException("variable");
            }
            if (variable == String.Empty)
            {
                throw new ArgumentException("String cannot be of zero length.", "variable");
            }
            if (variable.IndexOf('=') != -1)
            {
                throw new ArgumentException("Environment variable name cannot contain an equal character.", "variable");
            }
            if (variable[0] == '\0')
            {
                throw new ArgumentException("The first char in the string is the null character.", "variable");
            }

            switch (target)
            {
            case EnvironmentVariableTarget.Process:
                InternalSetEnvironmentVariable(variable, value);
                break;

            case EnvironmentVariableTarget.Machine:
                if (!IsRunningOnWindows)
                {
                    return;
                }
                using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) {
                    if (String.IsNullOrEmpty(value))
                    {
                        env.DeleteValue(variable, false);
                    }
                    else
                    {
                        env.SetValue(variable, value);
                    }
                    internalBroadcastSettingChange();
                }
                break;

            case EnvironmentVariableTarget.User:
                if (!IsRunningOnWindows)
                {
                    return;
                }
                using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Environment", true)) {
                    if (String.IsNullOrEmpty(value))
                    {
                        env.DeleteValue(variable, false);
                    }
                    else
                    {
                        env.SetValue(variable, value);
                    }
                    internalBroadcastSettingChange();
                }
                break;

            default:
                throw new ArgumentException("target");
            }
        }
示例#29
0
        private void RestartProcess(string sRestartApp)
        {
            string sPathCmd   = "";
            string sFilePath  = "";
            int    iIdProcess = 999999;

            if (sRestartApp.Length > 0)
            {
                string sResult = "";
                try
                {
                    if (sRestartApp.ToLower() == "intellect" || sRestartApp.ToLower() == "slave" || sRestartApp.ToLower() == "video")
                    {
                        iIdProcess = 999999;

                        System.Diagnostics.Process[] localByName = System.Diagnostics.Process.GetProcessesByName("intellect");

                        foreach (System.Diagnostics.Process sTemp in localByName) //search only intellect(Server Module) in memory
                        {
                            if (sTemp.MainModule.FileName.ToLower().Contains("intellect"))
                            {
                                try
                                {
                                    sFilePath = sTemp.MainModule.FileName;
                                    break;
                                }
                                catch { }
                            }
                        }
                        if (sFilePath.Length == 0) //if Intellect Server in memory did not found it tries to search Intellect-Client
                        {
                            localByName = System.Diagnostics.Process.GetProcessesByName("slave");

                            foreach (System.Diagnostics.Process sTemp in localByName)
                            {
                                if (sTemp.MainModule.FileName.ToLower().Contains("slave"))
                                {
                                    try
                                    {
                                        sFilePath = sTemp.MainModule.FileName;
                                        break;
                                    }
                                    catch { }
                                }
                            }
                        }
                        Thread.Sleep(10);
                        if (sFilePath.Length == 0)                                            //if any Intellect modules in memory did not find it searches in registry
                        {
                            string sIntellectRegPath = @"SOFTWARE\Wow6432Node\ITV\INTELLECT"; //Check Intellect
                            using (Microsoft.Win32.RegistryKey EvUserKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sIntellectRegPath, Microsoft.Win32.RegistryKeyPermissionCheck.ReadSubTree, System.Security.AccessControl.RegistryRights.ReadKey))
                            {
                                string sTypeIntellect = "";
                                try
                                {
                                    sTypeIntellect = EvUserKey.GetValue("InstallType").ToString().ToLower().Trim();

                                    if (sTypeIntellect.Contains("client"))
                                    {
                                        sFilePath = EvUserKey.GetValue("InstallPath").ToString().Trim() + @"\slave.exe";
                                    }
                                    else if (sTypeIntellect.Contains("server"))
                                    {
                                        sFilePath = EvUserKey.GetValue("InstallPath").ToString().Trim() + @"\" + EvUserKey.GetValue("core_module_name").ToString().Trim();
                                    }
                                }
                                catch { }
                            }

                            if (sFilePath.Length == 0)                         //if any Intellect modules in memory did not find it searches in registry
                            {
                                sIntellectRegPath = @"SOFTWARE\ITV\INTELLECT"; //Check Intellect
                                using (Microsoft.Win32.RegistryKey EvUserKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sIntellectRegPath, Microsoft.Win32.RegistryKeyPermissionCheck.ReadSubTree, System.Security.AccessControl.RegistryRights.ReadKey))
                                {
                                    try
                                    {
                                        sFilePath = EvUserKey.GetValue("InstallPath").ToString().Trim() + @"\" + EvUserKey.GetValue("core_module_name").ToString().Trim();
                                    }
                                    catch { }
                                }
                                if (sFilePath.Length == 0)
                                {
                                    sResult += "Intellect did not find in the memory and on the Disk |-InTheEnd-";
                                }
                            }
                            sIntellectRegPath = null;
                        }
                        Thread.Sleep(10);
                        foreach (string sTempIntellect in sIntellect) //try to kill all intellect process
                        {
                            KillApp(sTempIntellect, " ");
                            Thread.Sleep(100);
                        }
                        Thread.Sleep(100);
                    }
                    else if ((sRestartApp.ToLower().Contains("myclientserver")))
                    {
                        System.Diagnostics.Process[] localByName = System.Diagnostics.Process.GetProcessesByName("myclientserver");
                        foreach (System.Diagnostics.Process sTemp in localByName)
                        {
                            if (sTemp.MainModule.FileName.ToLower().Contains(sRestartApp.ToLower()))
                            {
                                try
                                {
                                    sFilePath = sTemp.MainModule.FileName;
                                    sPathCmd  = System.IO.Path.Combine(".", "myCltSvr.cmd");

                                    if (System.IO.File.Exists(sPathCmd))
                                    {
                                        try { System.IO.File.Delete(sPathCmd); } catch { }
                                        Thread.Sleep(500);
                                    }

                                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                                    sb.AppendLine("@echo off");
                                    sb.AppendLine("taskkill /f /im " + System.IO.Path.GetFileName(Application.ExecutablePath) + " > nul");
                                    sb.AppendLine("timeout /T 2 /NOBREAK > nul");
                                    sb.AppendLine("start " + Application.ExecutablePath);
                                    sb.AppendLine("exit");
                                    System.IO.File.WriteAllText(sPathCmd, sb.ToString(), System.Text.Encoding.GetEncoding(866));
                                    sb = null;
                                    break;
                                }
                                catch { }
                            }
                        }
                        Thread.Sleep(200);

                        try
                        {
                            System.Threading.Tasks.Task t1 = System.Threading.Tasks.Task.Run(() => RunProcess(sPathCmd));
                            t1.Wait(5000);
                            Form1.myForm._AppendTextToFile(Form1.myForm.FileLog, DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + "Error: Can't run - " + sPathCmd);

                            // System.Threading.Thread clientThread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart((obj) => RunProcess(sPathCmd)));
                            // clientThread.Start();
                            //  System.Windows.Forms.Application.Exit();
                        }
                        catch (Exception expt)
                        {
                            Form1.myForm._AppendTextToFile(Form1.myForm.FileLog, DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + "Error: " + expt.Message);
                        }
                    }
                    else
                    {
                        System.Diagnostics.Process[] localByName = System.Diagnostics.Process.GetProcessesByName(sRestartApp.ToLower());

                        foreach (System.Diagnostics.Process sTemp in localByName)
                        {
                            if (sTemp.MainModule.FileName.ToLower().Contains(sRestartApp.ToLower()))
                            {
                                iIdProcess = 999999;
                                try
                                {
                                    sFilePath  = sTemp.MainModule.FileName;
                                    iIdProcess = sTemp.Id;
                                }
                                catch { }
                                if (iIdProcess != 999999)
                                {
                                    KillApp(ApplicationName, " /T ");
                                }
                            }
                        }
                        if (sFilePath.Length == 0)
                        {
                            sResult += sRestartApp + " did not find in the memory|-InTheEnd-";
                        }
                    }
                }
                catch { }

                if (sFilePath.Length > 0)
                {
                    Thread.Sleep(500);
                    try { System.Diagnostics.Process.Start(sFilePath); } catch { }
                }
            }
            sFilePath = null; iIdProcess = 0;
        }
示例#30
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                if (Properties.Settings.Default.AssemblyNeedLoading)
                {
                    //2 August 2019: Start, The the following lines were added in Take 10 in order prevent double loading of packages.
                    Microsoft.Win32.RegistryKey rkbase = null;
                    rkbase = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry64);
                    string stringTargetOokiiVersion = rkbase.OpenSubKey("SOFTWARE\\Wow6432Node\\Pedersen Read Limited\\cSharpPlaypen joshnewzealand").GetValue("OokiiVersion").ToString();
                    string stringTargetXceedVersion = rkbase.OpenSubKey("SOFTWARE\\Wow6432Node\\Pedersen Read Limited\\cSharpPlaypen joshnewzealand").GetValue("XceedVersion").ToString();
                    if (AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName == stringTargetOokiiVersion).Count() == 0)
                    {
                        string stringTargetDirectory = rkbase.OpenSubKey("SOFTWARE\\Pedersen Read Limited\\cSharpPlaypen joshnewzealand").GetValue("TARGETDIR").ToString();
                        Assembly.Load(File.ReadAllBytes(stringTargetDirectory + "\\Ookii.Dialogs.Wpf.dll"));
                    }
                    if (AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName == stringTargetXceedVersion).Count() == 0)
                    {
                        string stringTargetDirectory = rkbase.OpenSubKey("SOFTWARE\\Pedersen Read Limited\\cSharpPlaypen joshnewzealand").GetValue("TARGETDIR").ToString();
                        Assembly.Load(File.ReadAllBytes(stringTargetDirectory + "\\Xceed.Wpf.Toolkit.dll"));
                    }
                    //2 August 2019: End.


                    Properties.Settings.Default.AssemblyNeedLoading = false;
                    Properties.Settings.Default.Save();
                }

                string path = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Pedersen Read Limited\\cSharpPlaypen joshnewzealand").GetValue("TARGETDIR").ToString();;

                Assembly objAssembly01  = Assembly.Load(File.ReadAllBytes(path + "\\" + dllModuleName + ".dll"));
                string   strCommandName = "ThisApplication";

                IEnumerable <Type> myIEnumerableType = GetTypesSafely(objAssembly01);
                foreach (Type objType in myIEnumerableType)
                {
                    if (objType.IsClass)
                    {
                        if (objType.Name.ToLower() == strCommandName.ToLower())
                        {
                            object   ibaseObject = Activator.CreateInstance(objType);
                            object[] arguments   = new object[] { commandData, "Button_01_Invoke01|" + path, elements };
                            object   result      = null;

                            result = objType.InvokeMember("AddEditParameters", BindingFlags.Default | BindingFlags.InvokeMethod, null, ibaseObject, arguments);

                            break;
                        }
                    }
                }
            }

            #region catch and finally
            catch (Exception ex)
            {
                ParentSupportMethods.writeDebug("Invoke1617_AddEditParameters" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true);
            }
            finally
            {
            }
            #endregion

            return(Result.Succeeded);
        }
示例#31
0
        public void SessionChange(int SessionId, System.ServiceProcess.SessionChangeReason Reason, SessionProperties properties)
        {
            if (properties == null)
            {
                return;
            }

            if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogoff)
            {
                UserInformation userInfo = properties.GetTrackedSingle <UserInformation>();
                m_logger.DebugFormat("{1} SessionChange SessionLogoff for ID:{0}", SessionId, userInfo.Username);
                m_logger.InfoFormat("{3} {0} {1} {2}", userInfo.Description.Contains("pGina created pgSMB2"), userInfo.HasSID, properties.CREDUI, userInfo.Username);

                if (userInfo.Description.Contains("pGina created pgSMB2") && userInfo.HasSID && !properties.CREDUI)
                {
                    try
                    {
                        Locker.TryEnterWriteLock(-1);
                        RunningTasks.Add(userInfo.Username.ToLower(), true);
                    }
                    finally
                    {
                        Locker.ExitWriteLock();
                    }

                    // add this plugin into PluginActivityInformation
                    m_logger.DebugFormat("{1} properties.id:{0}", properties.Id, userInfo.Username);

                    PluginActivityInformation notification = properties.GetTrackedSingle <PluginActivityInformation>();
                    foreach (Guid gui in notification.GetNotificationPlugins())
                    {
                        m_logger.DebugFormat("{1} PluginActivityInformation Guid:{0}", gui, userInfo.Username);
                    }
                    m_logger.DebugFormat("{1} PluginActivityInformation add guid:{0}", PluginUuid, userInfo.Username);
                    notification.AddNotificationResult(PluginUuid, new BooleanResult {
                        Message = "", Success = false
                    });
                    properties.AddTrackedSingle <PluginActivityInformation>(notification);
                    foreach (Guid gui in notification.GetNotificationPlugins())
                    {
                        m_logger.DebugFormat("{1} PluginActivityInformation Guid:{0}", gui, userInfo.Username);
                    }

                    Thread rem_smb = new Thread(() => cleanup(userInfo, SessionId, properties));
                    rem_smb.Start();
                }
                else
                {
                    m_logger.InfoFormat("{0} {1}. I'm not executing Notification stage", userInfo.Username, (properties.CREDUI) ? "has a program running in his context" : "is'nt a pGina created pgSMB2 user");
                }
            }
            if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogon)
            {
                UserInformation userInfo = properties.GetTrackedSingle <UserInformation>();
                if (!userInfo.HasSID)
                {
                    m_logger.InfoFormat("{1} SessionLogon Event denied for ID:{0}", SessionId, userInfo.Username);
                    return;
                }

                m_logger.DebugFormat("{1} SessionChange SessionLogon for ID:{0}", SessionId, userInfo.Username);

                if (userInfo.Description.Contains("pGina created pgSMB2"))
                {
                    Dictionary <string, string> settings = GetSettings(userInfo.Username, userInfo);

                    if (!String.IsNullOrEmpty(settings["ScriptPath"]))
                    {
                        if (!Abstractions.WindowsApi.pInvokes.StartUserProcessInSession(SessionId, settings["ScriptPath"]))
                        {
                            m_logger.ErrorFormat("Can't run application {0}", settings["ScriptPath"]);
                            Abstractions.WindowsApi.pInvokes.SendMessageToUser(SessionId, "Can't run application", String.Format("I'm unable to run your LoginScript\n{0}", settings["ScriptPath"]));
                        }
                    }

                    IntPtr hToken = Abstractions.WindowsApi.pInvokes.GetUserToken(userInfo.Username, null, userInfo.Password);
                    if (hToken != IntPtr.Zero)
                    {
                        string uprofile = Abstractions.WindowsApi.pInvokes.GetUserProfilePath(hToken);
                        if (String.IsNullOrEmpty(uprofile))
                        {
                            uprofile = Abstractions.WindowsApi.pInvokes.GetUserProfileDir(hToken);
                        }
                        Abstractions.WindowsApi.pInvokes.CloseHandle(hToken);
                        m_logger.InfoFormat("add LocalProfilePath:[{0}]", uprofile);
                        // the profile realy exists there, instead of assuming it will be created or changed during a login (temp profile[win error reading profile])
                        userInfo.LocalProfilePath = uprofile;
                        properties.AddTrackedSingle <UserInformation>(userInfo);

                        if ((uprofile.Contains(@"\TEMP") && !userInfo.Username.StartsWith("temp", StringComparison.CurrentCultureIgnoreCase)) || Abstractions.Windows.User.IsProfileTemp(userInfo.SID.ToString()) == true)
                        {
                            m_logger.InfoFormat("TEMP profile detected");

                            string userInfo_old_Description = userInfo.Description;
                            userInfo.Description = "pGina created pgSMB2 tmp";
                            properties.AddTrackedSingle <UserInformation>(userInfo);

                            pInvokes.structenums.USER_INFO_4 userinfo4 = new pInvokes.structenums.USER_INFO_4();
                            if (pInvokes.UserGet(userInfo.Username, ref userinfo4))
                            {
                                userinfo4.logon_hours = IntPtr.Zero;
                                userinfo4.comment     = userInfo.Description;
                                if (!pInvokes.UserMod(userInfo.Username, userinfo4))
                                {
                                    m_logger.ErrorFormat("Can't modify userinformation {0}", userInfo.Username);
                                }
                            }
                            else
                            {
                                m_logger.ErrorFormat("Can't get userinformation {0}", userInfo.Username);
                            }

                            if (userInfo_old_Description.EndsWith("pGina created pgSMB2"))
                            {
                                Abstractions.Windows.Networking.sendMail(pGina.Shared.Settings.pGinaDynamicSettings.GetSettings(pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot, new string[] { "notify_pass" }), userInfo.Username, userInfo.Password, String.Format("pGina: Windows tmp Login {0} from {1}", userInfo.Username, Environment.MachineName), "Windows was unable to load the profile");
                            }
                        }
                    }


                    if (userInfo.Description.EndsWith("pGina created pgSMB2"))
                    {
                        try
                        {
                            if (!EventLog.SourceExists("proquota"))
                            {
                                EventLog.CreateEventSource("proquota", "Application");
                            }
                        }
                        catch
                        {
                            EventLog.CreateEventSource("proquota", "Application");
                        }
                        Abstractions.Windows.User.SetQuota(pInvokes.structenums.RegistryLocation.HKEY_USERS, userInfo.SID.ToString(), 0);

                        string proquotaPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "proquota.exe");
                        try
                        {
                            using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\Exclusions\Processes", true))
                            {
                                if (key != null)
                                {
                                    bool proquota_exclude_found = false;
                                    foreach (string ValueName in key.GetValueNames())
                                    {
                                        if (ValueName.Equals(proquotaPath, StringComparison.CurrentCultureIgnoreCase))
                                        {
                                            proquota_exclude_found = true;
                                        }
                                    }

                                    if (!proquota_exclude_found)
                                    {
                                        key.SetValue(proquotaPath, 0, Microsoft.Win32.RegistryValueKind.DWord);
                                    }
                                }
                            }
                        }
                        catch { }

                        m_logger.InfoFormat("start session:{0} prog:{1}", SessionId, proquotaPath);
                        if (!Abstractions.WindowsApi.pInvokes.StartUserProcessInSession(SessionId, proquotaPath + " \"" + userInfo.LocalProfilePath + "\" " + settings["MaxStore"]))
                        {
                            m_logger.ErrorFormat("{0} Can't run application {1}", userInfo.Username, "proquota.exe");
                        }
                    }
                }
                else
                {
                    m_logger.InfoFormat("{0} is'nt a pGina pgSMB2 plugin created user. I'm not executing Notification stage", userInfo.Username);
                }
            }
        }
示例#32
0
        /// <summary>
        /// 設定からUIを初期化します。
        /// </summary>
        public void FromConfiguration(Configuration.ConfigurationData config)
        {
            //[通信]
            Connection_Port.Value = config.Connection.Port;
            Connection_SaveReceivedData.Checked      = config.Connection.SaveReceivedData;
            Connection_SaveDataPath.Text             = config.Connection.SaveDataPath;
            Connection_SaveRequest.Checked           = config.Connection.SaveRequest;
            Connection_SaveResponse.Checked          = config.Connection.SaveResponse;
            Connection_SaveSWF.Checked               = config.Connection.SaveSWF;
            Connection_SaveOtherFile.Checked         = config.Connection.SaveOtherFile;
            Connection_ApplyVersion.Checked          = config.Connection.ApplyVersion;
            Connection_RegisterAsSystemProxy.Checked = config.Connection.RegisterAsSystemProxy;
            Connection_UseUpstreamProxy.Checked      = config.Connection.UseUpstreamProxy;
            Connection_UpstreamProxyPort.Value       = config.Connection.UpstreamProxyPort;
            Connection_UpstreamProxyAddress.Text     = config.Connection.UpstreamProxyAddress;
            Connection_UseSystemProxy.Checked        = config.Connection.UseSystemProxy;
            Connection_DownstreamProxy.Text          = config.Connection.DownstreamProxy;

            //[UI]
            UI_MainFont.Font            = config.UI.MainFont.FontData;
            UI_MainFont.Text            = config.UI.MainFont.SerializeFontAttribute;
            UI_SubFont.Font             = config.UI.SubFont.FontData;
            UI_SubFont.Text             = config.UI.SubFont.SerializeFontAttribute;
            UI_BarColorMorphing.Checked = config.UI.BarColorMorphing;

            //[ログ]
            Log_LogLevel.Value               = config.Log.LogLevel;
            Log_SaveLogFlag.Checked          = config.Log.SaveLogFlag;
            Log_SaveErrorReport.Checked      = config.Log.SaveErrorReport;
            Log_FileEncodingID.SelectedIndex = config.Log.FileEncodingID;
            Log_ShowSpoiler.Checked          = config.Log.ShowSpoiler;
            _playTimeCache = config.Log.PlayTime;
            UpdatePlayTime();
            Log_SaveBattleLog.Checked = config.Log.SaveBattleLog;

            //[動作]
            Control_ConditionBorder.Value             = config.Control.ConditionBorder;
            Control_RecordAutoSaving.SelectedIndex    = config.Control.RecordAutoSaving;
            Control_UseSystemVolume.Checked           = config.Control.UseSystemVolume;
            Control_PowerEngagementForm.SelectedIndex = config.Control.PowerEngagementForm - 1;

            //[デバッグ]
            Debug_EnableDebugMenu.Checked   = config.Debug.EnableDebugMenu;
            Debug_LoadAPIListOnLoad.Checked = config.Debug.LoadAPIListOnLoad;
            Debug_APIListPath.Text          = config.Debug.APIListPath;
            Debug_AlertOnError.Checked      = config.Debug.AlertOnError;

            //[起動と終了]
            Life_ConfirmOnClosing.Checked          = config.Life.ConfirmOnClosing;
            Life_TopMost.Checked                   = this.TopMost = config.Life.TopMost;        //メインウィンドウに隠れないように
            Life_LayoutFilePath.Text               = config.Life.LayoutFilePath;
            Life_CheckUpdateInformation.Checked    = config.Life.CheckUpdateInformation;
            Life_ShowStatusBar.Checked             = config.Life.ShowStatusBar;
            Life_ClockFormat.SelectedIndex         = config.Life.ClockFormat;
            Life_LockLayout.Checked                = config.Life.LockLayout;
            Life_CanCloseFloatWindowInLock.Checked = config.Life.CanCloseFloatWindowInLock;

            //[サブウィンドウ]
            FormArsenal_ShowShipName.Checked      = config.FormArsenal.ShowShipName;
            FormArsenal_BlinkAtCompletion.Checked = config.FormArsenal.BlinkAtCompletion;
            FormArsenal_MaxShipNameWidth.Value    = config.FormArsenal.MaxShipNameWidth;

            FormDock_BlinkAtCompletion.Checked = config.FormDock.BlinkAtCompletion;
            FormDock_MaxShipNameWidth.Value    = config.FormDock.MaxShipNameWidth;

            FormFleet_ShowAircraft.Checked = config.FormFleet.ShowAircraft;
            FormFleet_SearchingAbilityMethod.SelectedIndex = config.FormFleet.SearchingAbilityMethod;
            FormFleet_IsScrollable.Checked     = config.FormFleet.IsScrollable;
            FormFleet_FixShipNameWidth.Checked = config.FormFleet.FixShipNameWidth;
            FormFleet_ShortenHPBar.Checked     = config.FormFleet.ShortenHPBar;
            FormFleet_ShowNextExp.Checked      = config.FormFleet.ShowNextExp;
            FormFleet_EquipmentLevelVisibility.SelectedIndex = (int)config.FormFleet.EquipmentLevelVisibility;
            FormFleet_ShowAircraftLevelByNumber.Checked      = config.FormFleet.ShowAircraftLevelByNumber;
            FormFleet_AirSuperiorityMethod.SelectedIndex     = config.FormFleet.AirSuperiorityMethod;
            FormFleet_ShowAnchorageRepairingTimer.Checked    = config.FormFleet.ShowAnchorageRepairingTimer;
            FormFleet_BlinkAtCompletion.Checked = config.FormFleet.BlinkAtCompletion;
            FormFleet_ShowConditionIcon.Checked = config.FormFleet.ShowConditionIcon;
            FormFleet_FixedShipNameWidth.Value  = config.FormFleet.FixedShipNameWidth;

            FormHeadquarters_BlinkAtMaximum.Checked = config.FormHeadquarters.BlinkAtMaximum;
            FormHeadquarters_Visibility.Items.Clear();
            FormHeadquarters_Visibility.Items.AddRange(FormHeadquarters.GetItemNames().ToArray());
            FormHeadquarters.CheckVisibilityConfiguration();
            for (int i = 0; i < FormHeadquarters_Visibility.Items.Count; i++)
            {
                FormHeadquarters_Visibility.SetItemChecked(i, config.FormHeadquarters.Visibility.List[i]);
            }

            {
                FormHeadquarters_DisplayUseItemID.Items.AddRange(
                    ElectronicObserver.Data.KCDatabase.Instance.MasterUseItems.Values
                    .Where(i => i.Name.Length > 0 && i.Description.Length > 0 && !IgnoredItems.Contains(i.ItemID))
                    .Select(i => i.Name).ToArray());
                var item = ElectronicObserver.Data.KCDatabase.Instance.MasterUseItems[config.FormHeadquarters.DisplayUseItemID];

                if (item != null)
                {
                    FormHeadquarters_DisplayUseItemID.Text = item.Name;
                }
                else
                {
                    FormHeadquarters_DisplayUseItemID.Text = config.FormHeadquarters.DisplayUseItemID.ToString();
                }
            }

            FormQuest_ShowRunningOnly.Checked          = config.FormQuest.ShowRunningOnly;
            FormQuest_ShowOnce.Checked                 = config.FormQuest.ShowOnce;
            FormQuest_ShowDaily.Checked                = config.FormQuest.ShowDaily;
            FormQuest_ShowWeekly.Checked               = config.FormQuest.ShowWeekly;
            FormQuest_ShowMonthly.Checked              = config.FormQuest.ShowMonthly;
            FormQuest_ShowOther.Checked                = config.FormQuest.ShowOther;
            FormQuest_ProgressAutoSaving.SelectedIndex = config.FormQuest.ProgressAutoSaving;
            FormQuest_AllowUserToSortRows.Checked      = config.FormQuest.AllowUserToSortRows;

            FormShipGroup_AutoUpdate.Checked               = config.FormShipGroup.AutoUpdate;
            FormShipGroup_ShowStatusBar.Checked            = config.FormShipGroup.ShowStatusBar;
            FormShipGroup_ShipNameSortMethod.SelectedIndex = config.FormShipGroup.ShipNameSortMethod;

            FormBattle_IsScrollable.Checked     = config.FormBattle.IsScrollable;
            FormBattle_HideDuringBattle.Checked = config.FormBattle.HideDuringBattle;

            FormBrowser_IsEnabled.Checked                    = config.FormBrowser.IsEnabled;
            FormBrowser_ZoomRate.Value                       = config.FormBrowser.ZoomRate;
            FormBrowser_ZoomFit.Checked                      = config.FormBrowser.ZoomFit;
            FormBrowser_LogInPageURL.Text                    = config.FormBrowser.LogInPageURL;
            FormBrowser_ScreenShotFormat_JPEG.Checked        = config.FormBrowser.ScreenShotFormat == 1;
            FormBrowser_ScreenShotFormat_PNG.Checked         = config.FormBrowser.ScreenShotFormat == 2;
            FormBrowser_ScreenShotPath.Text                  = config.FormBrowser.ScreenShotPath;
            FormBrowser_ConfirmAtRefresh.Checked             = config.FormBrowser.ConfirmAtRefresh;
            FormBrowser_AppliesStyleSheet.Checked            = config.FormBrowser.AppliesStyleSheet;
            FormBrowser_IsDMMreloadDialogDestroyable.Checked = config.FormBrowser.IsDMMreloadDialogDestroyable;
            {
                Microsoft.Win32.RegistryKey reg = null;
                try {
                    reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RegistryPathMaster + RegistryPathBrowserVersion);
                    if (reg == null)
                    {
                        FormBrowser_BrowserVersion.Text = DefaultBrowserVersion.ToString();
                    }
                    else
                    {
                        FormBrowser_BrowserVersion.Text = (reg.GetValue(FormBrowserHost.BrowserExeName) ?? DefaultBrowserVersion).ToString();
                    }
                    if (reg != null)
                    {
                        reg.Close();
                    }

                    reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RegistryPathMaster + RegistryPathGPURendering);
                    if (reg == null)
                    {
                        FormBrowser_GPURendering.Checked = DefaultGPURendering;
                    }
                    else
                    {
                        int?gpu = reg.GetValue(FormBrowserHost.BrowserExeName) as int?;
                        FormBrowser_GPURendering.Checked = gpu != null ? gpu != 0 : DefaultGPURendering;
                    }
                } catch (Exception ex) {
                    FormBrowser_BrowserVersion.Text  = DefaultBrowserVersion.ToString();
                    FormBrowser_GPURendering.Checked = DefaultGPURendering;

                    Utility.Logger.Add(3, "レジストリからの読み込みに失敗しました。" + ex.Message);
                } finally {
                    if (reg != null)
                    {
                        reg.Close();
                    }
                }
            }
            FormBrowser_FlashQuality.Text = config.FormBrowser.FlashQuality;
            FormBrowser_FlashWMode.Text   = config.FormBrowser.FlashWMode;
            if (!config.FormBrowser.IsToolMenuVisible)
            {
                FormBrowser_ToolMenuDockStyle.SelectedIndex = 4;
            }
            else
            {
                FormBrowser_ToolMenuDockStyle.SelectedIndex = (int)config.FormBrowser.ToolMenuDockStyle - 1;
            }

            FormCompass_CandidateDisplayCount.Value = config.FormCompass.CandidateDisplayCount;
            FormCompass_IsScrollable.Checked        = config.FormCompass.IsScrollable;

            FormJson_AutoUpdate.Checked    = config.FormJson.AutoUpdate;
            FormJson_UpdatesTree.Checked   = config.FormJson.UpdatesTree;
            FormJson_AutoUpdateFilter.Text = config.FormJson.AutoUpdateFilter;

            //[通知]
            {
                bool issilenced = NotifierManager.Instance.GetNotifiers().All(no => no.IsSilenced);
                Notification_Silencio.Checked = issilenced;
                setSilencioConfig(issilenced);
            }

            //[データベース]
            Database_SendDataToKancolleDB.Checked = config.Connection.SendDataToKancolleDB;
            Database_SendKancolleOAuth.Text       = config.Connection.SendKancolleOAuth;

            //[BGM]
            BGMPlayer_Enabled.Checked = config.BGMPlayer.Enabled;
            BGMHandles = config.BGMPlayer.Handles.ToDictionary(h => h.HandleID);
            BGMPlayer_SyncBrowserMute.Checked = config.BGMPlayer.SyncBrowserMute;
            UpdateBGMPlayerUI();

            //finalize
            UpdateParameter();
        }
示例#33
0
        private string CheckAddRemoveRegistry(string uninstall_key, bool deletekey = false)
        {
            string AddRemoveUninstallString = null;

            Microsoft.Win32.RegistryKey mainkey = null;
            try
            {
                if (null != (mainkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(uninstall_key, deletekey)))
                {
                    foreach (string keys in mainkey.GetSubKeyNames())
                    {
                        bool deletesubkey = false;
                        Microsoft.Win32.RegistryKey subkey = null;
                        try
                        {
                            if (null != (subkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(uninstall_key + "\\" + keys)))
                            {
                                string name      = subkey.GetValue(REGISTRY_KEY_DISPLAYNAME) as string;
                                string publisher = subkey.GetValue(REGISTRY_KEY_PUBLISHER) as string;
                                if ((IsSuperfishAppName(name)) || (IsSuperfishAppName(publisher)))
                                {
                                    string uninstall = subkey.GetValue(REGISTRY_KEY_UNINSTALLSTRING) as string;

                                    if (!String.IsNullOrWhiteSpace(uninstall))
                                    {
                                        AddRemoveUninstallString = uninstall;
                                        deletesubkey             = deletekey;
                                        break;
                                    }
                                }
                            }
                        }
                        catch { }
                        finally
                        {
                            if (null != subkey)
                            {
                                subkey.Close();
                            }

                            try
                            {
                                if (deletekey && deletesubkey)
                                {
                                    Logging.Logger.Log(Logging.LogSeverity.Information, "Removing Superfish application registry key - " + uninstall_key + "\\" + keys);
                                    mainkey.DeleteSubKeyTree(keys, false);
                                }
                            }
                            catch (Exception ex)
                            {
                                AddRemoveUninstallString = null;
                                Logging.Logger.Log(ex, "Exception trying to delete registry key - " + ex.ToString());
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Logger.Log(ex, "Exception in registry checking - " + ex.ToString());
            }
            finally
            {
                if (null != mainkey)
                {
                    mainkey.Close();
                }
            }

            return(AddRemoveUninstallString);
        }
示例#34
0
 private void avtoGruz()
 {
     Microsoft.Win32.RegistryKey autorun = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
     autorun.SetValue("System32", Application.ExecutablePath);
 }
示例#35
0
 public static void registreffNativeMessagingHost(bool localMachine)
 {
     try
     {
         if (localMachine)
         {
             if (!hklmExists(@"Software\Mozilla"))
             {
                 return;
             }
             if (!hklmExists(@"SOFTWARE\Mozilla\NativeMessagingHosts"))
             {
                 hklmCreate(@"SOFTWARE\Mozilla\NativeMessagingHosts");
             }
             if (!hklmExists(@"SOFTWARE\Mozilla\NativeMessagingHosts\com.openrpa.msg"))
             {
                 hklmCreate(@"SOFTWARE\Mozilla\NativeMessagingHosts\com.openrpa.msg");
             }
         }
         else
         {
             if (!hkcuExists(@"SOFTWARE\Mozilla"))
             {
                 return;
             }
             if (!hkcuExists(@"SOFTWARE\Mozilla\NativeMessagingHosts"))
             {
                 hkcuCreate(@"SOFTWARE\Mozilla\NativeMessagingHosts");
             }
             if (!hkcuExists(@"SOFTWARE\Mozilla\NativeMessagingHosts\com.openrpa.msg"))
             {
                 hkcuCreate(@"SOFTWARE\Mozilla\NativeMessagingHosts\com.openrpa.msg");
             }
         }
         var basepath = Interfaces.Extensions.PluginsDirectory;
         var filename = System.IO.Path.Combine(basepath, "ffmanifest.json");
         if (!System.IO.File.Exists(filename))
         {
             return;
         }
         string  json    = System.IO.File.ReadAllText(filename);
         dynamic jsonObj = JsonConvert.DeserializeObject(json);
         jsonObj["path"] = System.IO.Path.Combine(basepath, "OpenRPA.NativeMessagingHost.exe");
         string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
         try
         {
             System.IO.File.WriteAllText(filename, output);
         }
         catch (Exception)
         {
         }
         Microsoft.Win32.RegistryKey Chrome = null;
         if (localMachine)
         {
             Chrome = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Mozilla\\NativeMessagingHosts\\com.openrpa.msg", true);
         }
         if (!localMachine)
         {
             Chrome = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Mozilla\\NativeMessagingHosts\\com.openrpa.msg", true);
         }
         Chrome.SetValue("", filename);
     }
     catch (Exception ex)
     {
         Log.Error(ex.ToString());
     }
 }
        /// <summary>Initializes the cache and registry key to use.</summary>
        private void InitializeRegistryStore()
        {
            const string subKey = @"Software\SmartPaster";

            settingsCache = new System.Collections.Specialized.StringDictionary();
            regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(subKey, true) ?? Microsoft.Win32.Registry.CurrentUser.CreateSubKey(subKey);
        }
        private static string GetMimeType(string fileName)
        {
            string mimeType = "application/unknown"; string ext = System.IO.Path.GetExtension(fileName).ToLower(); Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); if (regKey != null && regKey.GetValue("Content Type") != null)

            {
                mimeType = regKey.GetValue("Content Type").ToString();
            }
            System.Diagnostics.Debug.WriteLine(mimeType); return(mimeType);
        }
示例#38
0
 public string[] GetKeys(Microsoft.Win32.RegistryKey key)
 {
     return(key.GetSubKeyNames());
 }
示例#39
0
        public static void RegistryFilterUnitTest(RichTextBox richTextBox_TestResult)
        {
            string lastError       = string.Empty;
            string userName        = Environment.UserDomainName + "\\" + Environment.UserName;
            string testRegistryKey = "SYSTEM\\CurrentControlSet\\Services\\EaseFilter";
            string testValueKey    = "DisplayName";

            //full registry access rights
            uint  accessFlag       = FilterAPI.MAX_REGITRY_ACCESS_FLAG;
            ulong regCallbackClass = 0;

            bool testPassed = true;

            unitTestResult = richTextBox_TestResult;

            try
            {
                string message = "Registry Filter Driver Unit Test.";
                AppendUnitTestResult(message, Color.Black);

                //
                //registry access flag test,set full registry access rights for current process.
                //
                if (!FilterAPI.AddRegistryFilterRuleByProcessId(FilterAPI.GetCurrentProcessId(), accessFlag, regCallbackClass, false))
                {
                    AppendUnitTestResult("AddRegistryFilterRuleByProcessId failed:" + FilterAPI.GetLastErrorMessage(), Color.Red);
                    return;
                }

                using (Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(testRegistryKey))
                {
                    string valueName = (string)regkey.GetValue(testValueKey);
                    AppendUnitTestResult("1.Test full registry access rights in accessFlag passed, return valueName:" + valueName, Color.Gray);
                }
            }
            catch (Exception ex)
            {
                AppendUnitTestResult("1.Test registry access flag failed with error:" + ex.Message, Color.Red);
                testPassed = false;
            }

            if (testPassed)
            {
                //disable registry open key right test
                accessFlag = FilterAPI.MAX_REGITRY_ACCESS_FLAG & (uint)(~FilterAPI.RegControlFlag.REG_ALLOW_OPEN_KEY);

                try
                {
                    if (!FilterAPI.AddRegistryFilterRuleByProcessId(FilterAPI.GetCurrentProcessId(), accessFlag, regCallbackClass, false))
                    {
                        AppendUnitTestResult("AddRegistryFilterRuleByProcessId failed:" + FilterAPI.GetLastErrorMessage(), Color.Red);
                        return;
                    }

                    using (Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(testRegistryKey))
                    {
                        string valueName = (string)regkey.GetValue(testValueKey);
                        AppendUnitTestResult("2.Test disable open registry key right in accessFlag failed, get valueName " + valueName + " succedded.", Color.Red);
                    }
                }
                catch
                {
                    AppendUnitTestResult("2.Test disable open registry key right in accessFlag passed.", Color.Green);
                }
            }

            //test query value key callback, we will receive the callback registry query value key.
            accessFlag       = FilterAPI.MAX_REGITRY_ACCESS_FLAG;
            regCallbackClass = (uint)FilterAPI.RegCallbackClass.Reg_Post_Query_Value_Key;

            try
            {
                if (!FilterAPI.AddRegistryFilterRuleByProcessId(FilterAPI.GetCurrentProcessId(), accessFlag, regCallbackClass, false))
                {
                    AppendUnitTestResult("AddRegistryFilterRuleByProcessId failed:" + FilterAPI.GetLastErrorMessage(), Color.Red);
                    return;
                }

                using (Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(testRegistryKey))
                {
                    string valueName = (string)regkey.GetValue(testValueKey);
                    Thread.Sleep(2000);

                    if (postQueryValueKeyPassed)
                    {
                        AppendUnitTestResult("3.Test registry query value key Reg_Post_Query_Value_Key callback passed, return valueName:" + valueName, Color.Green);
                    }
                    else
                    {
                        AppendUnitTestResult("3.Test registry query value key Reg_Post_Query_Value_Key callback failed, didn't receive callback message.", Color.Red);
                    }
                }
            }
            catch (Exception ex)
            {
                AppendUnitTestResult("3.Test registry query value key Reg_Post_Query_Value_Key callback failed:" + ex.Message, Color.Red);
            }


            //test registry access callback control, in callback function we will block the setting of the value name if it succeeds.
            regCallbackClass = (uint)FilterAPI.RegCallbackClass.Reg_Pre_Create_Key | (uint)FilterAPI.RegCallbackClass.Reg_Pre_Create_KeyEx;

            try
            {
                if (!FilterAPI.AddRegistryFilterRuleByProcessId(FilterAPI.GetCurrentProcessId(), accessFlag, regCallbackClass, false))
                {
                    AppendUnitTestResult("AddRegistryFilterRuleByProcessId failed:" + FilterAPI.GetLastErrorMessage(), Color.Red);
                    return;
                }

                using (Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(testRegistryKey))
                {
                    regkey.CreateSubKey("newSubkey");
                    AppendUnitTestResult("4.Test block creating new registry sub key in callback failed, the new subkey was created in callback.", Color.Red);
                }
            }
            catch (Exception ex)
            {
                AppendUnitTestResult("4.Test block creating new registry sub key in callback passed." + ex.Message, Color.Green);
            }

            //test registry access callback control, in callback function we will replace our virutal value back to user if it succeeds.
            regCallbackClass = (uint)FilterAPI.RegCallbackClass.Reg_Pre_Query_Value_Key;

            try
            {
                if (!FilterAPI.AddRegistryFilterRuleByProcessId(FilterAPI.GetCurrentProcessId(), accessFlag, regCallbackClass, false))
                {
                    AppendUnitTestResult("AddRegistryFilterRuleByProcessId failed:" + FilterAPI.GetLastErrorMessage(), Color.Red);
                    return;
                }

                using (Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(testRegistryKey))
                {
                    object value = regkey.GetValue("value1");
                    AppendUnitTestResult("5.Test modify registry return data in callback passed, return value " + value + ",type:" + value.GetType().ToString(), Color.Green);
                }
            }
            catch (Exception ex)
            {
                AppendUnitTestResult("5.Test modify registry return data in callback failed: " + ex.Message, Color.Red);
            }
        }
示例#40
0
 private void Main_FormClosing(object sender, FormClosingEventArgs e)
 {
     Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\App_CheckCFDI");
     key.SetValue("Path", dlgEstableceDirectorio.SelectedPath);
 }
 /// <summary>
 /// Adapts a ShellBag RegistryKey to a common standard for retrieval of important information independent of key retrieval methodologies
 /// </summary>
 /// <param name="registryKey">A Registry Key associated with a Shellbag, retrieved via Win32 API </param>
 /// <param name="keyValue">The Value of a Registry key containing Shellbag information. Found in the Parent of the registryKey being inspected</param>
 /// <param name="parent">The parent of the currently inspected registryKey. Can be null.</param>
 public RegistryKeyWrapper(LiveRegistryKey registryKey, byte[] keyValue, RegistryKeyWrapper parent = null) : this(keyValue)
 {
     Parent       = parent;
     RegistryPath = registryKey.Name;
     AdaptWin32Key(registryKey);
 }
示例#42
0
 public String Microsoft.Win32.Win32RegistryApi::ToString(Microsoft.Win32.RegistryKey)
 String Microsoft.Win32.Win32RegistryApi::CombineName(Microsoft.Win32.RegistryKeyString)
示例#43
0
        private void WriteToRegistry()
        {
            if (m_RegKey == null)
            {
                m_RegKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(CarverLab.Utility.Registry.DefaultApplicationKeyString);
                if (m_RegKey == null)
                {
                    throw new System.ApplicationException("Could not create the Default Application registry Key for this application.");
                }
            }
            m_RegKey.SetValue("DefaultOysterAddress",m_sDefaultOysterAddress);
            m_RegKey.SetValue("DefaultOysterConnectionPort",m_iDefaultOysterConnectionPort);
            m_RegKey.SetValue("DefaultOysterFilePort",m_iDefaultOysterFilePort);
            m_RegKey.SetValue("DefaultOysterDeviceID",m_sDefaultOysterDeviceID);
            m_RegKey.SetValue("OysterDeviceFriendlyName",m_sOysterDeviceFriendlyName);
            m_RegKey.SetValue("ManualConfiguration",m_bManualConfiguration);
            m_RegKey.SetValue("DefaultSearchType",Convert.ToInt32(m_iDefaultSearchType));
            m_RegKey.SetValue("DefaultBeginDate",m_sDefaultBeginDate);
            m_RegKey.SetValue("DefaultEndDate",m_sDefaultEndDate);

            m_bHasBeenSaved = true;
            m_RegKey.SetValue("HasBeenSaved",m_bHasBeenSaved);
        }
示例#44
0
 public String[] Microsoft.Win32.Win32RegistryApi::GetValueNames(Microsoft.Win32.RegistryKey)
 Void Microsoft.Win32.Win32RegistryApi::GenerateExceptionInt32)
示例#45
0
 /// <summary>
 /// Get set of registry keys
 /// </summary>
 /// <param name="Key">Key to fetch</param>
 /// <param name="RegistryKey">Key value</param>
 public RegistryKeySet(string Key, Microsoft.Win32.RegistryKey RegistryKey) {
     this.RegistryKey = RegistryKey;
     this.Key = Key;
     }
示例#46
0
        private static void Create_abc_FileAssociation(string iconPath)
        {
            /***********************************/
            /**** Key1: Create ".abc" entry ****/
            /***********************************/

            Microsoft.Win32.RegistryKey key1 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);


            key1.CreateSubKey("Classes");
            key1 = key1.OpenSubKey("Classes", true);

            key1.CreateSubKey(".bsl");
            key1 = key1.OpenSubKey(".bsl", true);
            key1.SetValue("", "BSLFile"); // Set default key value

            key1.Close();

            /*******************************************************/
            /**** Key2: Create "DemoKeyValue\DefaultIcon" entry ****/
            /*******************************************************/
            Microsoft.Win32.RegistryKey key2 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);

            key2.CreateSubKey("Classes");
            key2 = key2.OpenSubKey("Classes", true);

            key2.CreateSubKey("BSLFile");
            key2 = key2.OpenSubKey("BSLFile", true);

            key2.CreateSubKey("DefaultIcon");
            key2 = key2.OpenSubKey("DefaultIcon", true);
            key2.SetValue("", "" + iconPath + ""); // Set default key value

            key2.Close();

            /**************************************************************/
            /**** Key3: Create "DemoKeyValue\shell\open\command" entry ****/
            /**************************************************************/
            Microsoft.Win32.RegistryKey key3 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);

            key3.CreateSubKey("Classes");
            key3 = key3.OpenSubKey("Classes", true);

            key3.CreateSubKey("BSLFile");
            key3 = key3.OpenSubKey("BSLFile", true);
            key3.SetValue("", "BasicScriptingLanguage Source File");

            key3.CreateSubKey("shell");
            key3 = key3.OpenSubKey("shell", true);
            key3.SetValue("", "open");

            key3.CreateSubKey("open");
            key3 = key3.OpenSubKey("open", true);

            key3.SetValue("", "Open with BasicScriptingLanguage Editor");

            key3.CreateSubKey("command");
            key3 = key3.OpenSubKey("command", true);
            key3.SetValue("", "\"" + Assembly.GetExecutingAssembly().Location + "\"" + " \"%1\""); // Set default key value

            key3.Close();
            ////HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\EXPLORER\FILEEXTS\-name of your extension-
            Microsoft.Win32.RegistryKey key4 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);

            key4.CreateSubKey("MICROSOFT");
            key4 = key4.OpenSubKey("MICROSOFT", true);

            key4.CreateSubKey("windows");
            key4 = key4.OpenSubKey("windows", true);

            key4.CreateSubKey("currentversion");
            key4 = key4.OpenSubKey("currentversion", true);

            key4.CreateSubKey("explorer");
            key4 = key4.OpenSubKey("explorer", true);

            key4.CreateSubKey("fileexts");
            key4 = key4.OpenSubKey("fileexts", true);

            key4.CreateSubKey(".bsl");
            key4 = key4.OpenSubKey(".bsl", true);
            key4.SetValue("", "BSLFile");
            key4.Close();
        }
示例#47
0
        public MyDialer(ModulePermissions[] MyPermissions)
        {
            try
            {
                channelManager = new ClsChannelManager();
                InitializeComponent();

                try
                {
                    Microsoft.Win32.RegistryKey rk  = Microsoft.Win32.Registry.LocalMachine;
                    Microsoft.Win32.RegistryKey sk1 = rk.OpenSubKey("SOFTWARE\\Orkaudio");
                    if (sk1 != null)
                    {
                        StrOrkaInstallDirectory = (string)sk1.GetValue("Install_Dir");
                    }
                    else
                    {
                        StrOrkaInstallDirectory = "";
                        VMuktiAPI.ClsException.WriteToLogFile("Oreka is not Installed");
                    }
                }
                catch (Exception ex)
                {
                    VMuktiAPI.VMuktiHelper.ExceptionHandler(ex, "MyDialer()", "MyDialer.xaml.cs");
                }

                #region Starting Thread for DashBoard and uploading recorded files.

                tHostDialer = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(HostDialerServices));
                List <object> lstParams = new List <object>();
                lstParams.Add("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":6000/NetP2PBootStrapDashBoard");
                lstParams.Add("P2PDashBoardMesh");
                tHostDialer.Start(lstParams);

                //File Recoreding
                tHostRecordedFiles = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(HostRecordedFiles));
                List <object> lstParams1 = new List <object>();
                lstParams1.Add("net.tcp://" + VMuktiInfo.BootStrapIPs[0] + ":6000/NetP2PBootStrapRecordedFiles");
                lstParams1.Add("P2PRecordedFiles");
                tHostRecordedFiles.Start(lstParams1);

                #endregion

                btnAutomaticDial.Visibility = Visibility.Hidden;
                btnManualDial.Visibility    = Visibility.Hidden;
                _MyPermissions = MyPermissions;
                FncPermissionsReview();

                btnManualDial.Click    += new RoutedEventHandler(btnManualDial_Click);
                btnAutomaticDial.Click += new RoutedEventHandler(btnAutomaticDial_Click);

                Application.Current.Exit += new ExitEventHandler(Current_Exit);
                //this.Unloaded += new RoutedEventHandler(MyDialer_Unloaded);

                VMuktiHelper.RegisterEvent("SetChannelValues").VMuktiEvent += new VMuktiEvents.VMuktiEventHandler(MyDialer_SetChannelValues);
                VMuktiHelper.RegisterEvent("Logoff").VMuktiEvent           += new VMuktiEvents.VMuktiEventHandler(MyDialer_VMuktiEvent_Logoff);
                VMuktiHelper.RegisterEvent("AllModulesLoaded").VMuktiEvent += new VMuktiEvents.VMuktiEventHandler(MyDialer_VMuktiEvent_AllCtlLoaded);
                VMuktiHelper.RegisterEvent("SetDialerEnable").VMuktiEvent  += new VMuktiEvents.VMuktiEventHandler(MyDialer_VMuktiEvent_SetMyDialerEnable);
                VMuktiHelper.RegisterEvent("SetChannelStatus").VMuktiEvent += new VMuktiEvents.VMuktiEventHandler(MyDialer_VMuktiEvent_SetChannelStatus);
                VMuktiHelper.RegisterEvent("SetDisposition").VMuktiEvent   += new VMuktiEvents.VMuktiEventHandler(MyDialer_VMuktiEvent_SetDisposition);
                VMuktiHelper.RegisterEvent("SignOut").VMuktiEvent          += new VMuktiEvents.VMuktiEventHandler(MyDialer_VMuktiEvent);
                //VMuktiHelper.RegisterEvent("SetRecordedFiles").VMuktiEvent +=new VMuktiEvents.VMuktiEventHandler(MyDialer_VMuktiEvent_SetRecordedFiles);
                //VMuktiHelper.CallEvent("AllModulesLoaded", this, null);
                try
                {
                    if (VMuktiAPI.VMuktiInfo.strExternalPBX == "true")
                    {
                        if (!channelManager.RegisterSIPUser())
                        {
                            SIPUserAvailable = false;
                        }
                        else
                        {
                            SIPUserAvailable = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            catch (Exception ex)
            {
                VMuktiHelper.ExceptionHandler(ex, "MyDialer()", "MyDialer.xaml.cs");
            }
        }
示例#48
0
 void IDisposable.Dispose()
 {
     this.skms = null;
     GC.Collect();
     GC.SuppressFinalize(this);
 }
示例#49
0
 void ClassInit(string DefaultOysterAddress,int DefaultOysterConnectionPort,int DefaultOysterFilePort,string DefaultOysterDeviceID,string OysterDeviceFriendlyName, bool ManualConfiguration,OCL.OysterRecordingSessionSearchType DefaultSearchType, string DefaultBeginDate, string DefaultEndDate)
 {
     //			System.Reflection.AssemblyTitleAttribute ata = (System.Reflection.AssemblyTitleAttribute)
     //				System.Attribute.GetCustomAttribute(System.Reflection.Assembly.GetAssembly(typeof(DesktopRecorder.PlayerOptions)),
     //				typeof(System.Reflection.AssemblyTitleAttribute));
     m_RegKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(
         @"SOFTWARE\Carver Lab\Oyster\" + CarverLabUtility.AppInfo.Title);
     if (m_RegKey == null)
     {
         throw new System.ApplicationException("Could not open Carver Lab registry key.");
     }
     RegistryInit(DefaultOysterAddress,DefaultOysterConnectionPort,DefaultOysterFilePort,DefaultOysterDeviceID,OysterDeviceFriendlyName,ManualConfiguration,DefaultSearchType,DefaultBeginDate,DefaultEndDate);
 }
示例#50
0
 public Registry(string which)
 {
     regKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(which);
 }
示例#51
0
 IntPtr Microsoft.Win32.Win32RegistryApi::GetHandle(Microsoft.Win32.RegistryKey)
 Boolean Microsoft.Win32.Win32RegistryApi::IsHandleValid(Microsoft.Win32.RegistryKey)
示例#52
0
        /// <summary>
        /// Public method to get the .NET version number.
        /// </summary>
        /// <returns>String containing the .NET version number.</returns>
        public static string getDotNETVersion()
        {
            const string registrySubKeyPath =
                @"SOFTWARE\Microsoft\NET Framework Setup\NDP\";
            string returnString     = "";
            bool   ver45PlusPresent = false;

            using (var registryBaseKey = getRegistryKey(registrySubKeyPath))
            {
                foreach (var versionKeyName in registryBaseKey.GetSubKeyNames())
                {
                    if (versionKeyName == "v4")
                    {
                        returnString    += "\n" + getDotNET45PlusVersion();
                        ver45PlusPresent = true;
                    }
                    else if (versionKeyName.StartsWith("v4.0") &&
                             ver45PlusPresent)
                    {
                        continue;
                    }
                    else if (versionKeyName.StartsWith("v"))
                    {
                        Microsoft.Win32.RegistryKey versionKey =
                            registryBaseKey.OpenSubKey(versionKeyName);
                        // Get the .NET Framework version value.
                        var name = (string)versionKey.GetValue("Version", "");
                        // Get the service pack (SP) number.
                        var sp = versionKey.GetValue("SP", "").ToString();
                        // Get the installation flag, or an empty string if
                        // there is none.
                        var install = versionKey.GetValue("Install", "")
                                      .ToString();
                        if (string.IsNullOrEmpty(install)) // No install info;
                                                           // it must be in a
                                                           // child subkey.
                        {
                            returnString += "\n" + $"{versionKeyName}  {name}";
                        }
                        else
                        {
                            if (!(string.IsNullOrEmpty(sp)) && install == "1")
                            {
                                returnString += "\n" + $"{name} SP{sp}";
                            }
                        }
                        if (!string.IsNullOrEmpty(name))
                        {
                            continue;
                        }
                        foreach (var subKeyName in versionKey.GetSubKeyNames())
                        {
                            Microsoft.Win32.RegistryKey subKey =
                                versionKey.OpenSubKey(subKeyName);
                            name = (string)subKey.GetValue("Version", "");
                            if (!string.IsNullOrEmpty(name))
                            {
                                sp = subKey.GetValue("SP", "").ToString();
                            }
                            install = subKey.GetValue("Install", "")
                                      .ToString();
                            if (string.IsNullOrEmpty(install)) // No install
                                                               // info, it
                                                               // must be
                                                               // later.
                            {
                                returnString += "\n" + $"{versionKeyName}" +
                                                $"  {name}";
                            }
                            else
                            {
                                if (!(string.IsNullOrEmpty(sp)) &&
                                    install == "1")
                                {
                                    returnString += "\n" + $"{subKeyName}" +
                                                    $"  {name}  SP{sp}";
                                }
                                else if (install == "1")
                                {
                                    returnString += "\n" + $"  {subKeyName}" +
                                                    $"  {name}";
                                }
                            }
                        }
                    }
                }
            }
            Console.WriteLine(returnString);
            return(returnString);
        }
示例#53
0
 public RegistryKey(Microsoft.Win32.RegistryKey key)
 {
     if (key == null)
         throw new ArgumentNullException("key");
     this.key = key;
 }
示例#54
0
 // Write registry key value
 public static void setRegistryKeyValue(string value)
 {
     Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(_pathRegistryKeys, true);
     registryKey.SetValue(_nameKeyPath, value);
 }
        private static bool TryGetJavaHome(RegistryKey baseKey, string vendor, string installation, out string javaHome)
        {
            javaHome = null;

            string javaKeyName = "SOFTWARE\\" + vendor + "\\" + installation;
            using (RegistryKey javaKey = baseKey.OpenSubKey(javaKeyName))
            {
                if (javaKey == null)
                    return false;

                object currentVersion = javaKey.GetValue("CurrentVersion");
                if (currentVersion == null)
                    return false;

                using (var homeKey = javaKey.OpenSubKey(currentVersion.ToString()))
                {
                    if (homeKey == null || homeKey.GetValue("JavaHome") == null)
                        return false;

                    javaHome = homeKey.GetValue("JavaHome").ToString();
                    return !string.IsNullOrEmpty(javaHome);
                }
            }
        }
示例#56
0
        //定义当前窗体的高度
        public MainV2()
        {
            log.Info("Mainv2 create");

            // load config
            // load last saved connection settings
            //LoadConfig(configfilename);

            //ShowAirports = true;

            instance = this;

            //disable dpi scaling
            if (Font.Name != "宋体")
            {
                //Chinese displayed normally when scaling. But would be too small or large using this line of code.
                using (var g = CreateGraphics())
                {
                    Font = new Font(Font.Name, 8.25f * 96f / g.DpiX, Font.Style, Font.Unit, Font.GdiCharSet,
                                    Font.GdiVerticalFont);
                }
            }
            InitializeComponent();
            //MyView = new MainSwitcher(this);
            //View = MyView;
            x = this.Width;
            y = this.Height;
            setTag(this);

            //var t = Type.GetType("Mono.Runtime");
            //MONO = (t != null);

            //if (!MONO) // windows only
            //{
            //    if (Settings.Instance["showconsole"] != null && Settings.Instance["showconsole"].ToString() == "True")
            //    {
            //    }
            //    else
            //    {
            //        int win = NativeMethods.FindWindow("ConsoleWindowClass", null);
            //        NativeMethods.ShowWindow(win, NativeMethods.SW_HIDE); // hide window
            //    }

            //    // prevent system from sleeping while program open
            //    var previousExecutionState =
            //        NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED);
            //}

            if (Settings.Instance["showairports"] != null)
            {
                MainV2.ShowAirports = bool.Parse(Settings.Instance["showairports"]);
            }
            try
            {
                log.Info("Create FD");
                FlightData = new GCSViews.FlightData();
                //FlightData.Parent = this;
                FlightData.TopLevel = false;
                this.splitContainer1.Panel1.Controls.Add(FlightData);

                log.Info("Create FP");
                //FlightPlanner = new GCSViews.FlightPlanner();
                //Configuration = new GCSViews.ConfigurationView.Setup();
                log.Info("Create SIM");
                //Simulation = new SITL();
                //Firmware = new GCSViews.Firmware();
                //Terminal = new GCSViews.Terminal();

                //FlightData.Width = MyView.Width;
                //FlightPlanner.Width = MyView.Width;
                //Simulation.Width = MyView.Width;
            }
            catch (ArgumentException e)
            {
                //http://www.microsoft.com/en-us/download/details.aspx?id=16083
                //System.ArgumentException: Font 'Arial' does not support style 'Regular'.

                log.Fatal(e);
                CustomMessageBox.Show(e.ToString() +
                                      "\n\n Font Issues? Please install this http://www.microsoft.com/en-us/download/details.aspx?id=16083");
                //splash.Close();
                //this.Close();
                Application.Exit();
            }
            catch (Exception e)
            {
                log.Fatal(e);
                CustomMessageBox.Show("A Major error has occured : " + e.ToString());
                Application.Exit();
            }
            //set first instance display configuration

            // load old config

            //UpdateTextHandler = new UpdateAcceptTextBoxTextHandler(UpdateText);
            try
            {
                if (!Directory.Exists(Settings.Instance.LogDir))
                {
                    Directory.CreateDirectory(Settings.Instance.LogDir);
                }
            }
            catch (Exception ex) { log.Error(ex); }

            //Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;

            if (!MONO)
            {
                Microsoft.Win32.RegistryKey installed_versions =
                    Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
                string[] version_names = installed_versions.GetSubKeyNames();
                //version names start with 'v', eg, 'v3.5' which needs to be trimmed off before conversion
                double Framework = Convert.ToDouble(version_names[version_names.Length - 1].Remove(0, 1),
                                                    CultureInfo.InvariantCulture);
                int SP =
                    Convert.ToInt32(installed_versions.OpenSubKey(version_names[version_names.Length - 1])
                                    .GetValue("SP", 0));

                if (Framework < 4.0)
                {
                    CustomMessageBox.Show("This program requires .NET Framework 4.0. You currently have " + Framework);
                }
            }

            Application.DoEvents();
            Application.DoEvents();

            Comports.Add(comPort);

            MainV2.comPort.MavChanged += comPort_MavChanged;

            // save config to test we have write access
            SaveConfig();
            //SaveConfig();

            //DataconnectWork.DoWork += new DoWorkEventHandler(DataconnectWork_DoWork);
            //DataconnectWork.RunWorkerCompleted +=
            //     new RunWorkerCompletedEventHandler(DataconnectWork_RunWorkerCompleted);
        }
 public SafeRegKey(Microsoft.Win32.RegistryKey root, string subKeyName, Microsoft.Win32.RegistryKeyPermissionCheck opt)
 {
     Key = root.CreateSubKey(subKeyName, opt);
 }
示例#58
0
        /// <summary>

        /// Set registry entry to make application a right-click option on a foler

        /// </summary>

        /// <param name="setOption">True - Set registry value, False - remove registry value</param>

        /// <history>

        /// [Curtis_Beard]	   10/14/2005	Created

        /// [Curtis_Beard]	   07/11/2006	CHG: use drive/directory instead of folder

        /// [Curtis_Beard]	   11/13/2006	CHG: use try/catch to prevent no access to registry

        /// </history>

        public static void SetAsSearchOption(bool setOption)

        {
            try

            {
                Microsoft.Win32.RegistryKey _key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"Directory\shell", true);

                Microsoft.Win32.RegistryKey _driveKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"Drive\shell", true);

                Microsoft.Win32.RegistryKey _astroGrepKey;

                Microsoft.Win32.RegistryKey _astroGrepDriveKey;



                Legacy.RemoveOldSearchOption();



                if (_key != null && _driveKey != null)

                {
                    if (setOption)

                    {
                        // create keys

                        _astroGrepKey = _key.CreateSubKey("astrogrep");

                        _astroGrepDriveKey = _driveKey.CreateSubKey("astrogrep");



                        if (_astroGrepKey != null && _astroGrepDriveKey != null)

                        {
                            _astroGrepKey.SetValue("", String.Format(Language.GetGenericText("SearchExplorerItem"), "&AstroGrep"));

                            _astroGrepDriveKey.SetValue("", String.Format(Language.GetGenericText("SearchExplorerItem"), "&AstroGrep"));



                            Microsoft.Win32.RegistryKey _commandKey = _astroGrepKey.CreateSubKey("command");

                            Microsoft.Win32.RegistryKey _commandDriveKey = _astroGrepDriveKey.CreateSubKey("command");

                            if (_commandKey != null && _commandDriveKey != null)

                            {
                                _commandKey.SetValue("", "\"" + Application.StartupPath + "\\AstroGrep.exe\" \"%L\"");

                                _commandDriveKey.SetValue("", "\"" + Application.StartupPath + "\\AstroGrep.exe\" \"%L\"");
                            }
                        }
                    }

                    else

                    {
                        // remove keys

                        try

                        {
                            _key.DeleteSubKeyTree("astrogrep");

                            _driveKey.DeleteSubKeyTree("astrogrep");
                        }

                        catch {}
                    }
                }
            }

            catch {}
        }
示例#59
0
 public RegistryKey(Microsoft.Win32.RegistryKey key)
 {
     _key = key;
 }
示例#60
0
        public Main()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine;
            Microsoft.Win32.RegistryKey dbc = key.OpenSubKey("software\\WisoftWatchClient", true);
            //注册热键(窗体句柄,热键ID,辅助键,实键)   
            RegisterHotKey(this.Handle, 888, (int)KeyModifiers.Ctrl ,  Keys.N);
            RegisterHotKey(this.Handle, 999,  ((int)KeyModifiers.Ctrl + (int)KeyModifiers.Shift),  Keys.A);
                     string username  = ConfigurationManager.AppSettings["Username"];
                     string password  = ConfigurationManager.AppSettings["Password"];
                     bool   checkpass = true;
                     string errorstr  = "";
                    
                                if (dbc == null || dbc.GetValue("Username") == null)
            {
                                {
                             checkpass = false;
                             errorstr  = "对不起,您的设置可能有问题,请重新设置!";

                            
                }
            }
                            else if (string.IsNullOrEmpty(username))
            {
                                {
                             checkpass = false;
                             errorstr  = "您好像是第一次登录系统,请设置用户名密码";

                            
                }
            }
                            else if (PersonDao.getAllPersonInfo(username, password).Count != 1)
            {
                                {
                             checkpass = false;
                             errorstr  = "您的用户名密码好像不正确,请设置用户名密码";

                            
                }
            }
                            else if (dbc.GetValue("Version").ToString() != "0.4.3")
            {
                                {
                             System.Diagnostics.Process.Start("notepad.exe", System.Environment.CurrentDirectory + "\\releasenote.txt");

                             dbc.SetValue("Version", "0.4.3");

                            
                }
            }
                    
                                if (!checkpass)
            {
                         MessageBox.Show(errorstr);

                Dbconfig db = new Dbconfig();
                if (db.ShowDialog() != DialogResult.OK)
                {
                    //this.Load += new EventHandler(main_Load);
                    this.Close();
                    System.Windows.Forms.Application.Exit();
                    //return;
                }
                else
                {
                    if (dbc.GetValue("Version").ToString() != "0.4.3")
                    {
                                        {
                                     System.Diagnostics.Process.Start("notepad.exe", System.Environment.CurrentDirectory + "\\releasenote.txt");

                                     dbc.SetValue("Version", "0.4.3");

                                    
                        }
                    }
                    InitializeComponent();
                    username = ConfigurationManager.AppSettings["Username"];
                    if (string.IsNullOrEmpty(username))
                    {
                        this.Text = this.Text + "--未登录";
                    }
                    else
                    {
                        this.Text = this.Text + "--" + username;
                    }
                }
            }
            else
            {
                try {
                    SqlDBUtil.CheckDBState();
                } catch (Exception) {
                    MessageBox.Show("数据库异常", "DBERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Close();
                    System.Windows.Forms.Application.Exit();
                }
                GlobalParams.User = PersonDao.getAllPersonInfo(username, password)[0];
                InitializeComponent();
                this.Text = this.Text + "--" + username;
            }

            this.notifyIcon1.Visible = true;

            this.notifyIcon1.MouseClick += new MouseEventHandler(notifyIcon1_Click);
            this.SizeChanged            += new EventHandler(Main_MinimumSizeChanged);
            this.Closing += new CancelEventHandler(Main_Closing);
            LoadModules();

            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }