Example #1
0
 /// <summary>
 /// Impersonates the identity specified by <see cref="ApplicationIdentity"/>.
 /// </summary>
 public static System.Security.Principal.WindowsImpersonationContext Impersonate()
 {
     System.Security.Principal.WindowsPrincipal newPrin =
         new System.Security.Principal.WindowsPrincipal(ApplicationIdentity);
     System.Threading.Thread.CurrentPrincipal = newPrin;
     return ApplicationIdentity.Impersonate();
 }
Example #2
0
        private static bool IsRunAsAdmin()
        {
            var wi = System.Security.Principal.WindowsIdentity.GetCurrent();
            var wp = new System.Security.Principal.WindowsPrincipal(wi);

            return wp.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }
Example #3
0
        /// <summary>
        /// 以管理员身份重启本程序,成功或已有管理员权限,返回True
        /// </summary>
        /// <param name="Argument">启动参数,默认为空字符串</param>
        /// <param name="ShouldExit">指示调用进程是否应当退出</param>
        /// <returns>若已有管理员权限,返回True,若用户拒绝提权,返回false</returns>
        public static bool RunAsAdministrator(string Argument = "", bool ShouldExit = true)
        {
            uc_timer.ShouldPauseTopMost = true;

            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                bool Canceled = false;
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = Application.ExecutablePath;
                startInfo.Verb = "runas";
                startInfo.Arguments = Argument;
                try { Process.Start(startInfo); }
                catch (Exception) { Canceled = true; }
                if (Canceled == false)
                {
                    if (ShouldExit)
                        Application.Exit();
                    else
                        return true;
                }
            }
            else return true;
            return false;
        }
        public static bool IsAdmin()
        {
            System.Security.Principal.WindowsIdentity id = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal p = new System.Security.Principal.WindowsPrincipal(id);

            return p.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }
Example #5
0
 static void Main(string[] args)
 {
     /**
      * 当前用户是管理员的时候,直接启动应用程序
      * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
      */
     //获得当前登录的Windows用户标示
     System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
     //判断当前登录用户是否为管理员
     //如果不是管理员,则以管理员方式运行
     if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
     {
         //创建启动对象
         System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
         startInfo.UseShellExecute = true;
         startInfo.WorkingDirectory = Environment.CurrentDirectory;
         startInfo.FileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
         //设置启动动作,确保以管理员身份运行
         startInfo.Verb = "runas";
         try
         {
             System.Diagnostics.Process.Start(startInfo);
         }
         catch (Exception ex)
         {
             throw ex;
         }
         System.Environment.Exit(0);
     }
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new FrmMain(args));
 }
Example #6
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            bool isFirstInstance;


            /** 
             * 当前用户是管理员的时候,直接启动应用程序 
             * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行 
             */
            //获得当前登录的Windows用户标示  
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员  
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                // Please use a unique name for the mutex to prevent conflicts with other programs
                using (Mutex mtx = new Mutex(true, "Notify", out isFirstInstance))
                {
                    if (isFirstInstance)
                    {
                        //如果是管理员,则直接运行  
                        Application.Run(new Form1());
                    }
                    else
                    {
                        LogBuilder.buildLog("Already Running!");
                        //MessageBox.Show("Already Running!");
                        Application.Exit();
                    }
                } // releases the Mutex
                
            }
            else
            {
                //创建启动对象  
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName = Application.ExecutablePath;
                //设置启动动作,确保以管理员身份运行  
                startInfo.Verb = "runas";
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {
                    return;
                }
                //退出  
                Application.Exit();

                //Application.Run(new S2_0());
            }
        }
Example #7
0
        private static bool IsElevated()
        {
            System.Security.Principal.WindowsIdentity currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
            if (currentIdentity == null)
                return false;

            System.Security.Principal.WindowsPrincipal pricipal = new System.Security.Principal.WindowsPrincipal(currentIdentity);
            return pricipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }
Example #8
0
        static void Main(string[] args)
        {           
            #region Check if program is running as admin.
            System.Security.Principal.WindowsPrincipal user = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
            if (user.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator) != true)
            {
                int exitCode = 1;
                System.Windows.Forms.MessageBox.Show("You do not have administrative priviledges and cannot install this program.");
                Environment.Exit(exitCode);
            }
            #endregion

            #region Check if the resources have been set.
            if (Resources.logmeinDeployID == "" || Resources.spiceworksAuthKey == "" || Resources.spiceworksServer == "" || Resources.spiceworksPort == "" || Resources.spiceworksSiteName == "")
            {
                int exitCode = 1;
                System.Windows.Forms.MessageBox.Show("Resources have not been set. Recompile.");
                Environment.Exit(exitCode);
            }
            #endregion

            #region Create SupportInstaller directory in the user's temp directory.
            var temp = Directory.CreateDirectory(Path.GetTempPath() + "SupportInstaller\\");
            #endregion

            #region Extract installers.
            File.WriteAllBytes(temp.FullName + "logmein.msi", Support_Installer.Properties.Resources.logmein);
            File.WriteAllBytes(temp.FullName + "SpiceworksAgent.msi", Support_Installer.Properties.Resources.SpiceworksAgent);
            #endregion

            #region Run the LogMeIn and then the Spiceworks Agent installers and wait for them to exit.
            var logmein = Process.Start("msiexec.exe", "/i \"" + temp.FullName + "logmein.msi\" /quiet DEPLOYID=" + Resources.logmeinDeployID + " INSTALLMETHOD=5 FQDNDESC=0 /lp \"" + temp.FullName + "LogMeInLog.log\"");
            logmein.WaitForExit();
            var spiceworks = Process.Start("msiexec.exe", "/i \"" + temp.FullName + "SpiceworksAgent.msi\" SPICEWORKS_SERVER=\"" + Resources.spiceworksServer + "\" SPICEWORKS_AUTH_KEY=\"" + Resources.spiceworksAuthKey + "\" SPICEWORKS_PORT=" + Resources.spiceworksPort + " SPICEWORKS_SITE_LABEL=\"" + Resources.spiceworksSiteName + "\" ADDLOCAL=FeatureService /qn /norestart /log \"" + temp.FullName + "SpiceworksAgentLog.log\"");
            spiceworks.WaitForExit();
            #endregion

            #region Delete the installers.
            File.Delete(temp.FullName + "logmein.msi");
            File.Delete(temp.FullName + "SpiceworksAgent.msi");
            #endregion

            #region Set registry keys so LogMeIn does not show messages or tray icon.
            Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\LogMeIn\\V5\\Appearance", "KioskMode", "1", RegistryValueKind.DWord);
            Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\LogMeIn\\V5\\Appearance", "Language", "en", RegistryValueKind.String);
            Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\LogMeIn\\V5\\Gui", "EnableSystray", "0", RegistryValueKind.DWord);
            #endregion

            #region Restart the LogMeIn process so the above settings take effect.
            Process LMIRestart = new Process();
            LMIRestart.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            LMIRestart.StartInfo.FileName = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\LogMeIn", "InstallPath", "") + "\\x86\\LogMeIn.exe";
            LMIRestart.StartInfo.Arguments = "restart";
            LMIRestart.Start();
            #endregion
        }
Example #9
0
		public static bool IsCurrentlyRunningAsAdmin()
		{
			var isAdmin = false;
			var currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
			if (currentIdentity != null)
			{
				var pricipal = new System.Security.Principal.WindowsPrincipal(currentIdentity);
				isAdmin = pricipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
				pricipal = null;
			}
			return isAdmin;
		}
Example #10
0
 static void Main()
 {
     //获得当前登录的Windows用户标示  
     System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
     if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))  
     { 
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
     }
 }
Example #11
0
        //设置开机自动登录
        public static void SetAutoRun(string fileName, bool isAutoRun)
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            RegistryKey reg = null;
            try
            {
                if (!System.IO.File.Exists(fileName))
                {
                    throw new Exception("可执行文件不存在");
                }
                string name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
                reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                //reg = reg.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if (reg == null)
                {
                    reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    //Run = reg.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                }
                if (isAutoRun)
                {
                    reg.SetValue(name, fileName);
                }

                else
                {
                    //reg.SetValue(name, false);
                    //if (reg.GetValue(name) == null)
                    //{
                    //    return;
                    //}
                    reg.SetValue(name, false);
                }
            }
            catch (Exception ex)
            {

                throw new Exception(ex.ToString());
            }
            finally
            {
                if (reg != null)
                {
                    reg.Close();
                }
            }
        }
Example #12
0
        static void Main(String[] Args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            /** 
             * 当前用户是管理员的时候,直接启动应用程序 
             * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行 
             */
            //获得当前登录的Windows用户标示  
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员  
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是管理员,则直接运行  
                Application.Run(new Form1(Args));
            }
            else
            {
                //创建启动对象  
                //String str;
                //str = Args[0];
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName = Application.ExecutablePath;
                startInfo.Arguments = Args[0];
                //设置启动动作,确保以管理员身份运行  
                startInfo.Verb = "runas";
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {
                    return;
                }
                //退出  
                Application.Exit();


                //Application.Run(new Form1());
            }
        }
Example #13
0
        static void Main(string[] Args)
        {
            try
            {
                //获得当前登录的Windows用户标示
                System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();

                Application.SetCompatibleTextRenderingDefault(false);
                Process intance = RunningIntance();  //调用检查函数
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                //判断当前登录用户是否为管理员
                if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    //如果是管理员,则直接运行
                    Application.EnableVisualStyles();
                    if (intance == null)    //不存在相同的程序
                    {
                        Application.Run(new FormWIFI());
                    }
                    else  //存在相同的程序
                    {
                        HandleRunningInstance(intance);
                    }

                }
                else
                {
                    //创建启动对象
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    //设置运行文件
                    startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
                    //设置启动参数
                    startInfo.Arguments = String.Join(" ", Args);
                    //设置启动动作,确保以管理员身份运行
                    startInfo.Verb = "runas";
                    //如果不是管理员,则启动UAC
                    System.Diagnostics.Process.Start(startInfo);
                    //退出
                    System.Windows.Forms.Application.Exit();
                }

            }
            catch
            { }
        }
Example #14
0
        static void Main(string[] Args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            /**
             * 当前用户是管理员的时候,直接启动应用程序
             * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
             */
            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            //创建Windows用户主题
            Application.EnableVisualStyles();

            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是管理员,则直接运行

                Application.EnableVisualStyles();
                const string dbPath = "./local.db";
                //Application.Run(new LoginForm(dbPath));
                Application.Run(new LoginForm(dbPath));
            }
            else
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                //设置运行文件
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
                //设置启动参数
                startInfo.Arguments = String.Join(" ", Args);
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                //如果不是管理员,则启动UAC
                System.Diagnostics.Process.Start(startInfo);
                //退出
                System.Windows.Forms.Application.Exit();
            }
        }
Example #15
0
        public Logger()
        {
            // Display System information
            StringBuilder systeminfo_sb = new StringBuilder(string.Empty);

            systeminfo_sb.Append("========================================\r\n");

            try
            {
                var    win_reg     = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
                string productName = (string)win_reg.GetValue("ProductName");

                systeminfo_sb.AppendFormat("Operation System: {0}\r\n", productName);
            }
            catch (Exception exc)
            {
                systeminfo_sb.AppendFormat("Operation System: Could not retrieve. [Exception: {0}]\r\n", exc.Message);
            }

            systeminfo_sb.AppendFormat("System Architecture: " + (Environment.Is64BitOperatingSystem ? "64 bit" : "32 bit") + "\r\n");

            systeminfo_sb.AppendFormat("Environment OS Version: {0}\r\n", Environment.OSVersion);


            systeminfo_sb.AppendFormat("System Directory: {0}\r\n", Environment.SystemDirectory);
            systeminfo_sb.AppendFormat("Processor Count: {0}\r\n", Environment.ProcessorCount);
            systeminfo_sb.AppendFormat("User DomainName: {0}\r\n", Environment.UserDomainName);
            systeminfo_sb.AppendFormat("User Name: {0}\r\n", Environment.UserName);

            systeminfo_sb.AppendFormat("SystemPageSize: {0}\r\n", Environment.SystemPageSize);
            systeminfo_sb.AppendFormat("Environment Version: {0}\r\n", Environment.Version);

            System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            systeminfo_sb.AppendFormat("Is Elevated: {0}\r\n", principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator));
            systeminfo_sb.AppendFormat("Aurora Assembly Version: {0}\r\n", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
            systeminfo_sb.AppendFormat("Aurora File Version: {0}\r\n", System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion);

            systeminfo_sb.Append("========================================\r\n");

            LogLine(systeminfo_sb.ToString(), Logging_Level.None, false);
        }
Example #16
0
        public Sandbox()
        {
            System.Security.Principal.WindowsPrincipal wp = new
                System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());

            CheckProcess proc = new CheckProcess();
            if ((Util.GetModuleHandle("SbieDll.dll").ToInt32() != 0)
                         || (proc.IsProcessRunning("npfmsg"))
                        || (Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\", false)
                        .GetValue("ProductID").ToString() == "76487-640-1457236-23837")
                        || (System.Windows.Forms.Application.StartupPath == "C:\\analyzer\\scan") ||
                        (proc.IsProcessRunning("joeboxserver")) || (proc.IsProcessRunning("joeboxcontrol")) ||
                        (wp.Identity.Name == "HANS\\Hanuele Baser") ||
                        (wp.Identity.Name == "Sepp-PC\\Sepp") ||
                        (wp.Identity.Name == "John-PC\\John"))
            {
                new AntiFound();
            }
            //System.GC.Collect();
        }
Example #17
0
        static public bool IsUserAdministrator()
        {
            bool isAdmin;

            try
            {
                System.Security.Principal.WindowsIdentity  user      = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(user);
                isAdmin = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
            }
            catch (UnauthorizedAccessException)
            {
                isAdmin = false;
            }
            catch (Exception)
            {
                isAdmin = false;
            }
            return(isAdmin);
        }
Example #18
0
        public static string GetStaffId()
        {
            string domain = Environment.UserDomainName;
            //string domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;

            string loginName = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name;

            string         username    = loginName.Substring(loginName.IndexOf('\\') + 1);
            DirectoryEntry domainEntry = new DirectoryEntry("LDAP://" + domain);

            DirectorySearcher searcher = new DirectorySearcher(domainEntry);

            searcher.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))";
            SearchResult   result = searcher.FindOne();
            DirectoryEntry entry  = result.GetDirectoryEntry();

            string account = entry.Properties["sAMAccountName"].Value.ToString();

            return(account);
        }
Example #19
0
        public static bool IsDomainAdmin(IntPtr p_token)
        {
            var DomainName = GetDomainName();

            if (string.IsNullOrEmpty(DomainName))
            {
                return(false);
            }
            var d  = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(new System.DirectoryServices.ActiveDirectory.DirectoryContext(System.DirectoryServices.ActiveDirectory.DirectoryContextType.Domain, DomainName));
            var de = d.GetDirectoryEntry();

            byte[] domainSidArray  = de.Properties["objectSid"].Value as byte[];
            var    domainSid       = new System.Security.Principal.SecurityIdentifier(domainSidArray, 0);
            var    domainAdminsSid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.AccountDomainAdminsSid, domainSid);

            var wi = new System.Security.Principal.WindowsIdentity(p_token);
            var wp = new System.Security.Principal.WindowsPrincipal(wi);

            return(wp.IsInRole(domainAdminsSid));
        }
Example #20
0
 static void Main(params string[] Args)
 {
     System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
     if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
     {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
     }
     else
     {
         System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
         startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; // 获取当前可执行文件的路径及文件名
         //以下 Args 为启动本程序的对应的参数
         startInfo.Arguments = String.Join(" ", Args);
         startInfo.Verb      = "runas";
         System.Diagnostics.Process.Start(startInfo);
     }
 }
Example #21
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            /**
             * 当前用户是管理员的时候,直接启动应用程序
             * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
             */
            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是管理员,则直接运行
                Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("为了设置启动项,此程序必须以管理员权限运行。", "需要管理员权限", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                //设置运行文件
                startInfo.FileName = Application.ExecutablePath;
                //设置启动参数
                //startInfo.Arguments = String.Join(" ", Args);
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                try
                {
                    //如果不是管理员,则启动UAC
                    System.Diagnostics.Process.Start(startInfo);
                    //退出
                    Application.Exit();
                }
                catch
                {
                }
            }
        }
Example #22
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

#if DEBUG
            Application.Run(new FormMain());
#else
            //当前用户是管理员的时候,直接启动应用程序
            //如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是管理员,则直接运行
                Application.Run(new FormMain());
            }
            else
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.UseShellExecute  = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName         = Application.ExecutablePath;
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {
                    return;
                }
                //退出
                Application.Exit();
            }
#endif
        }
Example #23
0
        /// <summary>
        /// Zum Test der Authorisierung ist soll der Zugriff auf folgende Methode nur für
        /// "Testgruppe" möglich sein.
        /// </summary>
        /// <returns></returns>

        //[System.Security.Permissions.PrincipalPermission(System.Security.Permissions.SecurityAction.Demand, Role="Testgruppe")]
        public List <Filedescriptor> GetAllFileDescriptors_AdminsOnly()
        {
            var lst = new List <Filedescriptor>();

            var principal = new System.Security.Principal.WindowsPrincipal(ServiceSecurityContext.Current.WindowsIdentity);

            Debug.WriteLine("Operation wird ausgeführt als: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
            Debug.WriteLine("Operation wurde aufgerufen von: " + ServiceSecurityContext.Current.WindowsIdentity.Name);
            //Debug.Assert(principal.IsInRole(Gruppe), "Benutzer sollte zu Gruppe der Administratoren gehören, um diese Operation aufzurufen- er tut es aber nicht!");

            var perm = new System.Security.Permissions.PrincipalPermission(principal.Identity.Name, Gruppe);

            //perm.Demand();

            foreach (var file in Directory.GetFiles(_root))
            {
                lst.Add(GetFileDescriptor(Path.GetFileName(file)));
            }

            return(lst);
        }
Example #24
0
        /// <summary>
        /// Checks to see if the current user is an administrator.
        /// </summary>
        /// <returns>True, if the user is an administrator.</returns>
        public static bool IsUserAdministrator()
        {
            bool isAdmin;

            try
            {
                System.Security.Principal.WindowsIdentity user = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(user);
                isAdmin = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
            }
            catch (System.Security.SecurityException)
            {
                isAdmin = false;
            }
            catch (System.UnauthorizedAccessException)
            {
                isAdmin = false;
            }

            return isAdmin;
        }
        protected void Application_Start()
        {
            var testGroup = Environment.GetEnvironmentVariable("TEST_GROUP") ?? "WebUsers";

            var identity = System.Security.Principal.WindowsIdentity.GetCurrent();

            System.Diagnostics.Debug.WriteLine("Identity is " + identity.Name);
            var principal = new System.Security.Principal.WindowsPrincipal(identity);

            System.Diagnostics.Debug.WriteLine("Principal " + principal.Identity.Name + " is in role: " + principal.IsInRole(testGroup));
            if (!principal.IsInRole(testGroup))
            {
                throw new UnauthorizedAccessException("Access is denied.");
            }

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
 static void Main(string[] args)
 {
     if (args.Length == 1 && args[0] == "--admin")
     {
         string      currentPath = "\"" + Path.Combine(System.Environment.CurrentDirectory, "Wallpaper_Assistant.exe") + "\"";
         RegistryKey rk          = Registry.LocalMachine;
         RegistryKey rk2         = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
         rk2.SetValue("WallpaperAssistant", currentPath);
         rk2.Close();
         rk.Close();
     }
     else
     {
         System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
         System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
         if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
         {
             ProcessStartInfo startInfo = new ProcessStartInfo
             {
                 WorkingDirectory = System.Environment.CurrentDirectory,
                 FileName         = Process.GetCurrentProcess().MainModule.FileName,
                 Arguments        = "--admin"
             };
             Process.Start(startInfo);
         }
         else
         {
             ProcessStartInfo startInfo = new ProcessStartInfo
             {
                 UseShellExecute  = true,
                 WorkingDirectory = System.Environment.CurrentDirectory,
                 FileName         = Process.GetCurrentProcess().MainModule.FileName,
                 Arguments        = "--admin",
                 Verb             = "runas"
             };
             Process.Start(startInfo);
         }
         Environment.Exit(0);
     }
 }
Example #27
0
        static void Main()
        {
#if DEBUG
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormService());
#else
            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            //创建Windows用户主题
            Application.EnableVisualStyles();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            #region 必须以管理员权限运行
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                Application.SetCompatibleTextRenderingDefault(false);
                AutoRun();//设置开机自启动
                Application.Run(new FormService());
            }
            else
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                //设置运行文件
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
                //设置启动参数
                //startInfo.Arguments = String.Join(" ", Args);
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                //如果不是管理员,则启动UAC
                System.Diagnostics.Process.Start(startInfo);

                AutoRun();//设置开机自启动
                //退出
                Application.Exit();
            }
            #endregion 必须以管理员权限运行
#endif
        }
Example #28
0
        static void Main(string[] Args)
        {
            /** 
             * 当前用户是管理员的时候,直接启动应用程序 
             * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行 
             */
            //获得当前登录的Windows用户标示  
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            //创建Windows用户主题  
            Application.EnableVisualStyles();

            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员  
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是管理员,则直接运行  

                Application.EnableVisualStyles();
                Application.Run(new CMD());
            }
            else
            {
                try //在选择是否使用管理员登陆时 如果用户点击否代码[System.Diagnostics.Process.Start(startInfo);]异常
                {
                    //创建启动对象  
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    //设置运行文件  
                    startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
                    //设置启动参数  
                    startInfo.Arguments = String.Join(" ", Args);
                    //设置启动动作,确保以管理员身份运行  
                    startInfo.Verb = "runas";
                    //如果不是管理员,则启动UAC  
                    System.Diagnostics.Process.Start(startInfo);
                    //退出  
                    System.Windows.Forms.Application.Exit();
                }
                catch { }
            }
        }
Example #29
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            /**
             * The user is the administrator of time, direct start application
             * If not the administrator, use the startup object start program, using run as administrator to ensure
             */
            //Get the current logged on user labeled Windows
            System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //Judge whether the currently logged in user.
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //If the administrator, is directly run
                Application.Run(new OpenForensics());
            }
            else
            {
                //Create a startup object
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.UseShellExecute  = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName         = Application.ExecutablePath;
                //Set the start action, make sure to run as Administrator
                startInfo.Verb = "runas";
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {
                    return;
                }
                //Sign out
                Application.Exit();
            }
        }
Example #30
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //get admin privalages
            System.Security.Principal.WindowsPrincipal pricipal =
                     new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
            bool hasAdministrativeRight = pricipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);

            if (!hasAdministrativeRight)
            {
                RunElevated(Application.ExecutablePath);
                //this.Close();
                Application.Exit();
            }
            else
            {
                //we have admin privalages
                Application.Run(new BackTrack());
            }
        }
Example #31
0
        static void Main(string[] Args)
        {
            #if DEBUG
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainDialog());
            #else
            /**
             * 当前用户是管理员的时候,直接启动应用程序
             * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
             */
            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            Application.EnableVisualStyles();

            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainDialog());
            }
            else
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                //设置运行文件
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
                //设置启动参数
                startInfo.Arguments = String.Join(" ", Args);
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                //如果不是管理员,则启动UAC
                System.Diagnostics.Process.Start(startInfo);
                //退出
                System.Windows.Forms.Application.Exit();
            }
            #endif
        }
Example #32
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //get admin privalages
            System.Security.Principal.WindowsPrincipal pricipal =
                new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
            bool hasAdministrativeRight = pricipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);

            if (!hasAdministrativeRight)
            {
                RunElevated(Application.ExecutablePath);
                //this.Close();
                Application.Exit();
            }
            else
            {
                //we have admin privalages
                Application.Run(new BackTrack());
            }
        }
        private void btnSync_Click(object sender, EventArgs e)
        {
            string Name  = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name;
            string Name1 = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            string Name2 = System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName;

            using (var context = new PrincipalContext(ContextType.Domain, "tenf.loc"))
            {
                using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                        Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
                        Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
                        Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
                        Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
                        Console.WriteLine();
                    }
                }
            }
        }
Example #34
0
        /// <summary>
        /// 确定当前主体是否属于具有指定 Administrator 的 Windows 用户组
        /// </summary>
        /// <returns>如果当前主体是指定的 Administrator 用户组的成员,则为 true;否则为 false。</returns>
        public bool IsAdministrator()
        {
            bool result;

            try
            {
                System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                result = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);

                //http://www.cnblogs.com/Interkey/p/RunAsAdmin.html
                //AppDomain domain = Thread.GetDomain();
                //domain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                //WindowsPrincipal windowsPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
                //result = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch
            {
                result = false;
            }
            return(result);
        }
 /// <summary>
 /// 判斷當前用戶是否是管理員
 /// </summary>
 /// <returns>返回Boolean值</returns>
 public static bool IsCurrentUserAdmin()
 {
     try
     {
         AppDomain domain = System.Threading.Thread.GetDomain();
         domain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
         System.Security.Principal.WindowsPrincipal principal = (System.Security.Principal.WindowsPrincipal)System.Threading.Thread.CurrentPrincipal;
         bool user = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
         if (user)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch
     {
         return(false);
     }
 }
Example #36
0
        public static bool IsUserAdministrator()
        {
            //bool value to hold our return value
            bool isAdmin;

            try
            {
                //get the currently logged in user
                System.Security.Principal.WindowsIdentity  user      = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(user);
                isAdmin = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
            }
            catch (System.UnauthorizedAccessException)
            {
                isAdmin = false;
            }
            catch (System.Exception)
            {
                isAdmin = false;
            }
            return(isAdmin);
        }
Example #37
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                return;
            }

            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            Application.EnableVisualStyles();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //Application.EnableVisualStyles();
                //Application.Run(new UpdateBackground());
                //UpdateBackground updater = new UpdateBackground();
                Update update = new Update(args[0], args[1]);
                System.Windows.Forms.Application.Exit();
            }
            else
            {
                try
                {
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    startInfo.FileName  = System.Windows.Forms.Application.ExecutablePath;
                    startInfo.Verb      = "runas";
                    startInfo.Arguments = "-force";
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    System.Windows.Forms.Application.Exit();
                }
            }
        }
Example #38
0
        // Throw error messages if any required files are missing due to user error
        private static bool CheckRequiredFiles()
        {
            bool            success = true;
            Action <string> error   = (string input) => { Console.WriteLine(pre + "Missing File: {0}", input); };

            // Check privilege
            bool IsAdmin = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);

            if (!IsAdmin)
            {
                Console.WriteLine(pre + "This program needs to be run as an administrator to be able to host the HTTP and Pipes servers responsible for its operation. Please relaunch as an administrator.");
                success = false;
            }

            // Check files
            if (!File.Exists(CgSDKHandlerDir))
            {
                error("CgSDK Handler program");
                success = false;
            }
            if (!File.Exists("./CgSDK.x64_2015.dll"))
            {
                error("CgSDK library");
                success = false;
            }
            if (!File.Exists("./CgSDK_Interop.dll"))
            {
                error("CgSDK Interoperability library");
                success = false;
            }
            if (!File.Exists("./Newtonsoft.Json.dll"))
            {
                error("Newtonsoft JSON library");
                success = false;
            }

            return(success);
        }
Example #39
0
 private void 右键修复ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
     if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
     {
         //var exePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.FriendlyName);
         var exePath = Application.ExecutablePath;
         #region  注册鼠标右键
         using (RegistryKey classesroot = Registry.ClassesRoot)
         {
             using (RegistryKey star = classesroot.OpenSubKey("*"))
             {
                 using (RegistryKey Shell = star.OpenSubKey("Shell", true))
                 {
                     using (RegistryKey TODO = Shell.CreateSubKey("TODO"))
                     {
                         using (RegistryKey command = TODO.CreateSubKey("Command"))
                         {
                             command.SetValue(null, string.Format("{0} %1", exePath));
                             command.Close();
                         }
                         TODO.Close();
                     }
                     Shell.Close();
                 }
                 star.Close();
             }
             classesroot.Close();
         }
         #endregion
     }
     else
     {
         MessageBox.Show("右键上传文件修复需要管理员权限,请用管理员权限运行本程序修复");
         return;
     }
 }
Example #40
0
        static void Main()
        {
            Boolean createdNew;                                                                                            //返回是否赋予了使用线程的互斥体初始所属权

            System.Threading.Mutex instance = new System.Threading.Mutex(true, wapp.SysConfig.SystemName, out createdNew); //同步基元变量
            //赋予了线程初始所属权,也就是首次使用互斥体
            if (!createdNew)
            {
                return;
            }
            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是管理员,则直接运行
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                wapp.SysConfig.NewSysConfig();
                FormLogin fmLogin = new FormLogin();
                Application.Run(fmLogin);
                instance.ReleaseMutex();
            }
            else
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                //设置运行文件
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                //如果不是管理员,则启动UAC
                System.Diagnostics.Process.Start(startInfo);
                //退出
                System.Windows.Forms.Application.Exit();
            }
        }
Example #41
0
        public static void AssertAdministratorPrivileges()
        {
            //http://stackoverflow.com/questions/1089046/in-net-c-test-if-process-has-administrative-privileges

            //bool value to hold our return value
            bool isAdmin;

            try
            {
                //get the currently logged in user
                var user      = System.Security.Principal.WindowsIdentity.GetCurrent();
                var principal = new System.Security.Principal.WindowsPrincipal(user);
                isAdmin = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
            }
            catch (Exception)
            {
                isAdmin = false;
            }
            if (!isAdmin)
            {
                throw new Exception("You will need to run the tests with Administrator Privileges");
            }
        }
        //make sure that the user has the role
        public bool isAutorized(String roles)
        {
            bool isAutorized = false;

            string[] tab = roles.Split(';');
            foreach (var role in tab)
            {
                try
                {
                    bool UserIsInGroup = new System.Security.Principal.WindowsPrincipal(new System.Security.Principal.WindowsIdentity(Environment.UserName)).IsInRole(role);
                    if (UserIsInGroup)
                    {
                        isAutorized = true;
                        break;
                    }
                }
                catch (System.Exception ex)
                {
                }
            }

            return(isAutorized);
        }
Example #43
0
 /// <summary>
 /// Checks to see if the currently running instance of the sprite editor
 /// is associated with the .scn file extension.
 /// </summary>
 /// <remarks>Currently only attempts to check/associate if the currently
 /// logged in user is a windows administrator.  Have not fully
 /// investigated whether you really need unrestricted access to the registry
 /// to create/edit the required registry keys (in HKEY_CLASSES_ROOT), or
 /// if there is a way to do the association as a limited user. In
 /// the mean time, we will err on the side of caution.</remarks>
 static void VerifyScnRegistry()
 {
     System.Security.Principal.WindowsIdentity  winIdent     = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal winPrincipal = new System.Security.Principal.WindowsPrincipal(winIdent);
     if (winPrincipal.IsInRole(
             System.Security.Principal.WindowsBuiltInRole.Administrator))
     {
         FileAssociationHelper file = new FileAssociationHelper(".scn");
         if (!file.IsOpener || !file.IsEditor)
         {
             DialogResult res = System.Windows.Forms.MessageBox.Show(
                 "This application is currently not associated with the .scn file extension.\n\nWould you like it to be?",
                 "File Association",
                 MessageBoxButtons.YesNo,
                 MessageBoxIcon.Question,
                 MessageBoxDefaultButton.Button1);
             if (res == DialogResult.Yes)
             {
                 file.Associate();
             }
         }
     }
 }
Example #44
0
        private void InitWifiState()
        {
            bool result = WifiOperator.WifiStateQuery();

            if (result)
            {
                IsWifiOpened = true;
                Message      = "Wifi已启动";
            }
            else
            {
                IsWifiOpened = false;
                Message      = "Wifi未启动";
            }

            System.Security.Principal.WindowsIdentity  wid        = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal printcipal = new System.Security.Principal.WindowsPrincipal(wid);
            IsAdmin = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator));
            if (!IsAdmin)
            {
                Message = "请用管理员权限运行";
            }
        }
Example #45
0
        public MainWindow()
        {
            DataContext = new MainWindowModel();

            var pricipal = new System.Security.Principal.WindowsPrincipal(
                System.Security.Principal.WindowsIdentity.GetCurrent());

            if (pricipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                RegistryKey registrybrowser = Registry.LocalMachine.OpenSubKey
                                                  (@"Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
                var currentValue = registrybrowser.GetValue("*");
                if (currentValue == null || (int)currentValue != 0x00002af9)
                {
                    registrybrowser.SetValue("*", 0x00002af9, RegistryValueKind.DWord);
                }
            }
            else
            {
                this.Title += " (The first time to run with the rights of the administrator)";
            }
            InitializeComponent();
        }
Example #46
0
        public static void Main()
        {
            /**
             * if the current operation is done by an administrator, run it directly
             * if not, ask for the administrator's authority;
             */
            //get the current user ID;
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            Application.EnableVisualStyles();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);

            //whether the current operation is executed by administrators or not;
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //if this were run by administrators, run it directly;
                Application.Run(new MainForm());
            }
            else
            {
                //build up the booting object;
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.UseShellExecute  = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName         = Application.ExecutablePath;
                //make sure this is run by administrator;
                startInfo.Verb = "runas";
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {
                    return;
                }
                Application.Exit();
            }
        }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //直接运行
                Application.Run(new Form1());
            }
            else
            {
                //启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
                {
                    UseShellExecute  = true,
                    WorkingDirectory = Environment.CurrentDirectory,
                    FileName         = Application.ExecutablePath,
                    //确保以管理员身份运行
                    Verb = "runas"
                };
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {
                    return;
                }
                //退出
                Application.Exit();
            }
        }
Example #48
0
 /// <summary>
 ///以管理员的权限启动应用程序
 /// </summary>
 static void StartBySystemUser()
 {
     /**
       * 当前用户是管理员的时候,直接启动应用程序
       * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
       */
     //获得当前登录的Windows用户标示
     System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
     //判断当前登录用户是否为管理员
     if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
     {
         //如果是管理员,则直接运行
         Application.Run(new Service());
     }
     else
     {
         //创建启动对象
         System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
         startInfo.UseShellExecute = true;
         startInfo.WorkingDirectory = Environment.CurrentDirectory;
         startInfo.FileName = Application.ExecutablePath;
         //设置启动动作,确保以管理员身份运行
         startInfo.Verb = "runas";
         try
         {
             System.Diagnostics.Process.Start(startInfo);
         }
         catch
         {
             return;
         }
         //退出
         Application.Exit();
     }
 }
Example #49
0
        private void RunAsAdministrator()
        {
            /** 
            * 当前用户是管理员的时候,直接启动应用程序 
            * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行 
            */
            //获得当前登录的Windows用户标示 
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            //创建Windows用户主题 
            System.Windows.Forms.Application.EnableVisualStyles();

            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员 
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {                
                //如果是管理员,则直接运行 
                MainWindow main = new MainWindow();
                main.Show();                         
            }
            else
            {                
                //创建启动对象 
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                //设置运行文件 
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;                
                //设置启动参数 
                //startInfo.Arguments = String.Join(" ", Args);
                //设置启动动作,确保以管理员身份运行 
                startInfo.Verb = "runas";
                //如果不是管理员,则启动UAC 
                System.Diagnostics.Process.Start(startInfo);
                //退出 
                this.Shutdown();
                //System.Windows.Forms.Application.Exit();
            } 
        }
Example #50
0
        static void Main()
        {
            var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            var principal = new System.Security.Principal.WindowsPrincipal(identity);

            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {

                SAF.Foundation.ServiceModel.ServiceManager.Instance = new SAFServiceManager();

                SAF.Framework.Controls.SplashScreen.ShowSplashScreen("正在启动服务管理器");

                System.Globalization.CultureInfo zhHans = new System.Globalization.CultureInfo("zh-Hans");
                System.Threading.Thread.CurrentThread.CurrentCulture = zhHans;
                System.Threading.Thread.CurrentThread.CurrentUICulture = zhHans;

                DevExpress.UserSkins.BonusSkins.Register();
                DevExpress.Utils.AppearanceObject.DefaultFont = new Font("Segoe UI", 9);
                DevExpress.Skins.SkinManager.EnableFormSkins();

                UserLookAndFeel.Default.SetSkinStyle("Office 2013");
                ProgressService.SkinName = "Office 2013";

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Application.Run(new Shell());
            }
            else
            {
                var startInfo = Process.GetCurrentProcess().StartInfo;
                startInfo.FileName = System.Reflection.Assembly.GetEntryAssembly().Location;
                startInfo.Verb = "runas";
                Process.Start(startInfo);
            }
        }
Example #51
0
        /// <summary>
        /// <para>Check if the app was started as administrator or restart it with those permissions</para>
        /// <para>This method has to be called during the initialization process because otherwise the app will be restarted when trying to perform an action that requires administrator priviliges</para>
        /// </summary>
        /// <returns>
        /// <para>Whether administrator privileges are possible and requested</para>
        /// <para>When the user cancels UAC or some other error occurs this will return false.</para>
        /// </returns>
        public bool RequireAdministrator()
        {
            bool isAdmin = false;
            System.Security.Principal.WindowsIdentity winId = System.Security.Principal.WindowsIdentity.GetCurrent();
            if (winId != null)
                isAdmin = new System.Security.Principal.WindowsPrincipal(winId).IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);

            if (isAdmin)
                return true;

            Process me = Process.GetCurrentProcess();
            ProcessStartInfo procStart = new ProcessStartInfo();
            procStart.FileName = me.MainModule.FileName;
            procStart.UseShellExecute = true;
            procStart.Verb = "runas";	// run as Admin

            this.Log.LogLineDate("Requiring admin privileges...", Trigger.Log.Type.Other);

            try
            {
                if (Process.Start(procStart) == null)
                    return false;
                Process.GetCurrentProcess().Kill();
                return true;
            }
            catch (System.ComponentModel.Win32Exception e)
            {
                if (e.NativeErrorCode != 1223)		// 1223 = user aborted UAC
                    throw;
            }
            return false;
        }
Example #52
0
 /// <summary>
 /// Checks to see if the currently running instance of the sprite editor
 /// is associated with the .scn file extension.
 /// </summary>
 /// <remarks>Currently only attempts to check/associate if the currently
 /// logged in user is a windows administrator.  Have not fully
 /// investigated whether you really need unrestricted access to the registry
 /// to create/edit the required registry keys (in HKEY_CLASSES_ROOT), or
 /// if there is a way to do the association as a limited user. In
 /// the mean time, we will err on the side of caution.</remarks>
 static void VerifyScnRegistry()
 {
     System.Security.Principal.WindowsIdentity winIdent = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal winPrincipal = new System.Security.Principal.WindowsPrincipal(winIdent);
     if (winPrincipal.IsInRole(
         System.Security.Principal.WindowsBuiltInRole.Administrator))
     {
         FileAssociationHelper file = new FileAssociationHelper(".scn");
         if (!file.IsOpener || !file.IsEditor)
         {
             DialogResult res = System.Windows.Forms.MessageBox.Show(
                 "This application is currently not associated with the .scn file extension.\n\nWould you like it to be?",
                 "File Association",
                  MessageBoxButtons.YesNo,
                  MessageBoxIcon.Question,
                   MessageBoxDefaultButton.Button1);
             if (res == DialogResult.Yes)
             {
                 file.Associate();
             }
         }
     }
 }
Example #53
0
        static void Main(string[] args)
        {
            //Application.StartupPath + @"\CSSIM.exe"
            //RegistryKey HCROOT = Registry.ClassesRoot;
            //RegistryKey HCR_CSSIM=HCROOT.CreateSubKey("CSSIM");
            //HCROOT.Close();

            /**
            * 当前用户是管理员的时候,直接启动应用程序
            * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
            */
            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            //创建Windows用户主题
            Application.EnableVisualStyles();

            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员

            Dictionary<string, string> HrefMap = new Dictionary<string, string>();

            string[] arg_array = { };
            if (args.Length > 0)
            {
                args = args[0].Split(':');
                arg_array = args[1].Split('&');
            }

            if (arg_array != null)
            {

                foreach (string item in arg_array)
                {
                    if (item != null)
                    {
                        string[] items = item.Split('=');
                        if (items.Length == 2)
                        {
                            HrefMap.Add(items[0].ToString(), items[1].ToString());
                        }

                    }
                }
                /*if (HrefMap.ContainsKey("UD"))
                {
                    MessageBox.Show(HrefMap["UD"].ToString());
                }
                if (HrefMap.ContainsKey("PD"))
                {
                    MessageBox.Show(HrefMap["PD"].ToString());
                }
                if (HrefMap.ContainsKey("SD"))
                {
                    MessageBox.Show(HrefMap["SD"].ToString());
                }*/
            }

            Cursor.Current = Cursors.WaitCursor;
            Process instance = RunningInstance();
            if (instance == null)
            {
                //System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
                //if (addressList.Length > 1)
                //{
                //    LocalHostIP = addressList[1];
                //    //Console.WriteLine(addressList[1].ToString());
                //}
                //else
                //{
                //    LocalHostIP = addressList[0];
                //    //Console.WriteLine(addressList[1].ToString());
                //}

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                try
                {
                    Application.Run(new MainForm());
                }
                catch (Exception)
                {
                    MessageBox.Show("对不起,调用系统Win32API错误,请重新启动应用程序!");
                    Application.DoEvents();
                    Application.Exit();
                }

                /*//判断当前登录用户是否为管理员
                if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    //如果是管理员,则直接运行

                    Application.EnableVisualStyles();
                    try
                    {
                        Application.Run(new MainForm());
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("对不起,调用系统Win32API错误,请重新启动应用程序!");
                        Application.DoEvents();
                        Application.Exit();
                    }
                }
                else
                {
                    //创建启动对象
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    //设置运行文件
                    startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
                    //设置启动参数
                    startInfo.Arguments = String.Join(" ", args);
                    //设置启动动作,确保以管理员身份运行
                    startInfo.Verb = "runas";
                    //如果不是管理员,则启动UAC
                    System.Diagnostics.Process.Start(startInfo);
                    //退出
                    System.Windows.Forms.Application.Exit();
                }*/
            }
            else
            {
                HandleRunningInstance(instance);
                string sendText = HrefMap["SD"].ToString();
                int WINDOW_HANDLER = FindWindow(null, @"CSS&IM");
                byte[] sarr = System.Text.Encoding.Default.GetBytes(sendText);
                int len = sarr.Length;
                COPYDATASTRUCT cds;
                cds.dwData = (IntPtr)100;
                cds.lpData = sendText;
                cds.cbData = len + 1;
                SendMessage(WINDOW_HANDLER, WM_COPYDATA, 0, ref cds);
                //Util.HrefOpenFriendEventMethod(HrefMap["SD"].ToString());
                //MessageBox.Show("abc");
            }
        }
Example #54
0
		public static EAccountResult CreateAccount(ref AccountData account) {
			EAccountResult result = EAccountResult.Success;
			PostResult postResult;

			PostRequest mClient = new PostRequest("http://ragnarokonline.fr/inscription/index.php", "http://ragnarokonline.fr/inscription/index.php");
			mClient.Type = PostRequest.PostTypeEnum.Get;
			postResult = mClient.Post();
			// apply cookies
			mClient.Cookies = postResult.Cookies;

			// visit register page (need to fetch new cookies)
			mClient.Url = "http://ragnarokonline.fr/inscription/inscrire.php";
			mClient.UrlReferer = "http://ragnarokonline.fr/inscription/inscrire.php";
			postResult = mClient.Post();
			// apply cookies..
			mClient.Cookies = postResult.Cookies;

			// download captcha
			mClient.Url = "http://ragnarokonline.fr/inscription/securimage/securimage_show.php";
			postResult = mClient.Post();
			// apply cookies.. again
			//mClient.Cookies = postResult.Cookies;
			string captchaPath = Path.GetTempFileName();
			File.Delete(captchaPath);
			captchaPath += ".png";
			File.WriteAllBytes(captchaPath, postResult.ResponseData);

			// open captcha
			Process p = Process.Start(captchaPath);
			Console.Write("\t\tCaptcha code: ");
			account.CaptchaCode = Console.ReadLine();

			// Only if we have admin rights, we may kill the process
			System.Security.Principal.WindowsPrincipal pricipal = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
			if (pricipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator) == true) {
				try {
					if (p.CloseMainWindow() == false) {
						// fall trough
						throw new Exception("Failed to close captcha image process");
					}
				} catch (Exception ex) {
					// Failed to close.. so try minimize it
					try {
						System.Windows.Forms.Form frm = (System.Windows.Forms.Form)System.Windows.Forms.Form.FromHandle(p.MainWindowHandle);
						if (frm != null) {
							frm.WindowState = System.Windows.Forms.FormWindowState.Minimized;
						}
					} catch {
						// Nothing worked.. damn it
						// only native code may help now, but just to kill or minimize a process.. no way
					}
				}
			}

			mClient.Url = "http://ragnarokonline.fr/inscription/verifMail.php";
			mClient.Cookies = postResult.Cookies;
			mClient.PostItems.Add("email", account.Email);
			mClient.PostItems.Add("name", account.Prename);
			mClient.PostItems.Add("surname", account.Name);
			mClient.PostItems.Add("jour", account.BirthDay.ToString());
			mClient.PostItems.Add("mois", account.BirthMonth.ToString());
			mClient.PostItems.Add("annee", account.BirthYear.ToString());
			mClient.PostItems.Add("sexe", "1"); // Männlich
			mClient.PostItems.Add("captcha_code", account.CaptchaCode);

			postResult = mClient.Post();

			Regex re = new Regex("&resultat=([^&]*)&login=([^&]*)&pass=([^&]*)");
			Match match = re.Match(postResult.ResponseString);
			if (match.Success == false) {
				return CreateAccount(ref account);
			}

			account.Login = match.Groups[2].Captures[0].Value;
			account.Password = match.Groups[3].Captures[0].Value;

			int requestResult = int.Parse(match.Groups[1].Captures[0].Value);
			result = (EAccountResult)requestResult;


			return result;
		}
Example #55
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="createRunspaceEventArg"></param>
        /// <exception cref="InvalidOperationException">
        /// 1. InitialSessionState cannot be null.
        /// 2. Non existent InitialSessionState provider for the shellID
        /// </exception>
        private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createRunspaceEventArg)
        {
            if (createRunspaceEventArg == null)
            {
                throw PSTraceSource.NewArgumentNullException("createRunspaceEventArg");
            }
            RemoteDataObject<PSObject> rcvdData = createRunspaceEventArg.ReceivedData;
            Dbg.Assert(rcvdData != null, "rcvdData must be non-null");

            // set the PSSenderInfo sent in the first packets
            // This is used by the initial session state configuration providers like Exchange.
            if (Context != null)
            {
#if !CORECLR // TimeZone Not In CoreCLR
                _senderInfo.ClientTimeZone = Context.ClientCapability.TimeZone;
#endif
            }

            _senderInfo.ApplicationArguments = RemotingDecoder.GetApplicationArguments(rcvdData.Data);

            // Get Initial Session State from custom session config suppliers
            // like Exchange.
            ConfigurationDataFromXML configurationData =
                PSSessionConfiguration.LoadEndPointConfiguration(_configProviderId,
                    _initParameters);
            // used by Out-Of-Proc (IPC) runspace.
            configurationData.InitializationScriptForOutOfProcessRunspace = _initScriptForOutOfProcRS;
            // start with data from configuration XML and then override with data
            // from EndPointConfiguration type.
            _maxRecvdObjectSize = configurationData.MaxReceivedObjectSizeMB;
            _maxRecvdDataSizeCommand = configurationData.MaxReceivedCommandSizeMB;

            DISCPowerShellConfiguration discProvider = null;

            if (String.IsNullOrEmpty(configurationData.ConfigFilePath))
            {
                _sessionConfigProvider = configurationData.CreateEndPointConfigurationInstance();
            }
            else
            {
                System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal(_senderInfo.UserInfo.WindowsIdentity);

                Func<string, bool> validator = (role) => windowsPrincipal.IsInRole(role);

                discProvider = new DISCPowerShellConfiguration(configurationData.ConfigFilePath, validator);
                _sessionConfigProvider = discProvider;
            }

            // exchange of ApplicationArguments and ApplicationPrivateData is be done as early as possible
            // (i.e. to let the _sessionConfigProvider bail out if it can't comply with client's versioning request)
            PSPrimitiveDictionary applicationPrivateData = _sessionConfigProvider.GetApplicationPrivateData(_senderInfo);

            InitialSessionState rsSessionStateToUse = null;

            if (configurationData.SessionConfigurationData != null)
            {
                try
                {
                    rsSessionStateToUse =
                        _sessionConfigProvider.GetInitialSessionState(configurationData.SessionConfigurationData, _senderInfo, _configProviderId);
                }
                catch (NotImplementedException)
                {
                    rsSessionStateToUse = _sessionConfigProvider.GetInitialSessionState(_senderInfo);
                }
            }
            else
            {
                rsSessionStateToUse = _sessionConfigProvider.GetInitialSessionState(_senderInfo);
            }

            if (null == rsSessionStateToUse)
            {
                throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.InitialSessionStateNull, _configProviderId);
            }

            rsSessionStateToUse.ThrowOnRunspaceOpenError = true;

            // this might throw if the sender info is already present
            rsSessionStateToUse.Variables.Add(
                new SessionStateVariableEntry(RemoteDataNameStrings.SenderInfoPreferenceVariable,
                _senderInfo,
                Remoting.PSRemotingErrorInvariants.FormatResourceString(
                    RemotingErrorIdStrings.PSSenderInfoDescription),
                ScopedItemOptions.ReadOnly));

            // check if the current scenario is Win7(client) to Win8(server). Add back the PSv2 version TabExpansion
            // function if necessary.
            Version psClientVersion = null;
            if (_senderInfo.ApplicationArguments != null && _senderInfo.ApplicationArguments.ContainsKey("PSversionTable"))
            {
                var value = PSObject.Base(_senderInfo.ApplicationArguments["PSversionTable"]) as PSPrimitiveDictionary;
                if (value != null)
                {
                    if (value.ContainsKey("WSManStackVersion"))
                    {
                        var wsmanStackVersion = PSObject.Base(value["WSManStackVersion"]) as Version;
                        if (wsmanStackVersion != null && wsmanStackVersion.Major < 3)
                        {
                            // The client side is PSv2. This is the Win7 to Win8 scenario. We need to add the PSv2 
                            // TabExpansion function back in to keep the tab expansion functionable on the client side.
                            rsSessionStateToUse.Commands.Add(
                                new SessionStateFunctionEntry(
                                    RemoteDataNameStrings.PSv2TabExpansionFunction,
                                    RemoteDataNameStrings.PSv2TabExpansionFunctionText));
                        }
                    }
                    if (value.ContainsKey("PSVersion"))
                    {
                        psClientVersion = PSObject.Base(value["PSVersion"]) as Version;
                    }
                }
            }

            if (!string.IsNullOrEmpty(configurationData.EndPointConfigurationTypeName))
            {
                // user specified a type to load for configuration..use the values from this type.
                _maxRecvdObjectSize = _sessionConfigProvider.GetMaximumReceivedObjectSize(_senderInfo);
                _maxRecvdDataSizeCommand = _sessionConfigProvider.GetMaximumReceivedDataSizePerCommand(_senderInfo);
            }
            SessionDataStructureHandler.TransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = _maxRecvdObjectSize;
            // MaximumReceivedDataSize is not set for session transport manager...see the constructor
            // for more info.

            Guid clientRunspacePoolId = rcvdData.RunspacePoolId;
            int minRunspaces = RemotingDecoder.GetMinRunspaces(rcvdData.Data);
            int maxRunspaces = RemotingDecoder.GetMaxRunspaces(rcvdData.Data);
            PSThreadOptions threadOptions = RemotingDecoder.GetThreadOptions(rcvdData.Data);
#if !CORECLR // No ApartmentState In CoreCLR
            ApartmentState apartmentState = RemotingDecoder.GetApartmentState(rcvdData.Data);
#endif
            HostInfo hostInfo = RemotingDecoder.GetHostInfo(rcvdData.Data);

            if (_runspacePoolDriver != null)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceAlreadyExists,
                    _runspacePoolDriver.InstanceId);
            }

#if !UNIX
            bool isAdministrator = _senderInfo.UserInfo.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
#else
            bool isAdministrator = false;
#endif

            ServerRunspacePoolDriver tmpDriver = new ServerRunspacePoolDriver(
                clientRunspacePoolId,
                minRunspaces,
                maxRunspaces,
                threadOptions,
#if !CORECLR // No ApartmentState In CoreCLR
                apartmentState,
#endif
                hostInfo,
                rsSessionStateToUse,
                applicationPrivateData,
                configurationData,
                this.SessionDataStructureHandler.TransportManager,
                isAdministrator,
                Context.ServerCapability,
                psClientVersion,
                _configurationName);

            // attach the necessary event handlers and start the driver.
            Interlocked.Exchange(ref _runspacePoolDriver, tmpDriver);
            _runspacePoolDriver.Closed += HandleResourceClosing;
            _runspacePoolDriver.Start();
        }
        public void RemoveConsole()
        {
            Trace.WriteLine("Installer::RemoveConsole");

            SetOutput(_isPassive, _isPassive && _isForced);
            try
            {
                System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    RemoveElevated();
                    return;
                }

                List<GitInstallation> installations = null;

                // use the custom installation path if supplied
                if (!String.IsNullOrEmpty(_customPath))
                {
                    if (!Directory.Exists(_customPath))
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: custom path does not exist: '{0}'. U_U", _customPath);
                        Pause();

                        Result = ResultValue.InvalidCustomPath;
                        return;
                    }

                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Removing from custom path: '{0}'.", _customPath);

                    // if the custom path points to a git location then treat it properly
                    GitInstallation installation;
                    if (Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows64v2, out installation)
                        || Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v2, out installation)
                        || Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v1, out installation))
                    {
                        Trace.Write("   Git found: " + installation.Path);

                        // track known Git installtations
                        installations = new List<GitInstallation>();
                        installations.Add(installation);
                    }
                }
                // since no custom installation path was supplied, use default logic
                else
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Looking for Git installation(s)...");

                    if (Where.FindGitInstallations(out installations))
                    {
                        foreach (var installation in installations)
                        {
                            Console.Out.WriteLine("  {0}", installation.Path);
                        }
                    }
                }

                if (installations == null)
                {
                    Console.Out.WriteLine();
                    Console.Error.WriteLine("Fatal: Git was not detected, unable to continue. U_U");
                    Pause();

                    Result = ResultValue.GitNotFound;
                    return;
                }

                Configuration.Type types = Configuration.Type.Global | Configuration.Type.System;

                Configuration.Type updateTypes;
                if (SetGitConfig(installations, GitConfigAction.Unset, types, out updateTypes))
                {
                    if ((updateTypes & Configuration.Type.System) == Configuration.Type.System)
                    {
                        Console.Out.WriteLine();
                        Console.Out.WriteLine("Updated your /etc/gitconfig [git config --system]");
                    }
                    else
                    {
                        Console.Out.WriteLine();

                        // updating /etc/gitconfig should not fail installation when forced
                        if (!_isForced)
                        {
                            // only 'fatal' when not forced
                            Console.Error.Write("Fatal: ");

                            Result = ResultValue.GitConfigSystemFailed;
                            return;
                        }

                        Console.Error.WriteLine("Unable to update your /etc/gitconfig correctly.");
                    }

                    if ((updateTypes & Configuration.Type.Global) == Configuration.Type.Global)
                    {
                        Console.Out.WriteLine("Updated your ~/.gitconfig [git config --global]");
                    }
                    else
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: Unable to update your ~/.gitconfig correctly.");

                        Result = ResultValue.GitConfigGlobalFailed;
                        return;
                    }
                }

                List<string> cleanedFiles;
                foreach (var installation in installations)
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Removing from '{0}'.", installation.Path);

                    if (CleanFiles(installation.Libexec, out cleanedFiles))
                    {
                        foreach (var file in cleanedFiles)
                        {
                            Console.Out.WriteLine("  {0}", file);
                        }

                        Console.Out.WriteLine("        {0} file(s) cleaned", cleanedFiles.Count);
                    }
                    else if (_isForced)
                    {
                        Console.Error.WriteLine("  removal failed. U_U");
                    }
                    else
                    {
                        Console.Error.WriteLine("  removal failed. U_U");
                        Pause();

                        Result = ResultValue.RemovalFailed;
                        return;
                    }
                }

                if (Directory.Exists(UserBinPath))
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Removing from '{0}'.", UserBinPath);

                    if (CleanFiles(UserBinPath, out cleanedFiles))
                    {
                        foreach (var file in cleanedFiles)
                        {
                            Console.Out.WriteLine("  {0}", file);
                        }

                        Console.Out.WriteLine("        {0} file(s) cleaned", cleanedFiles.Count);
                    }
                    else if (_isForced)
                    {
                        Console.Error.WriteLine("  removal failed. U_U");
                    }
                    else
                    {
                        Console.Error.WriteLine("  removal failed. U_U");
                        Pause();

                        Result = ResultValue.RemovalFailed;
                        return;
                    }
                }

                if (CygwinPath != null && Directory.Exists(CygwinPath))
                {
                    if (CleanFiles(CygwinPath, out cleanedFiles))
                    {
                        foreach (var file in cleanedFiles)
                        {
                            Console.Out.WriteLine("  {0}", file);
                        }

                        Console.Out.WriteLine("        {0} file(s) cleaned", cleanedFiles.Count);
                    }
                }

                // all necissary content has been deployed to the system
                Result = ResultValue.Success;

                Console.Out.WriteLine();
                Console.Out.WriteLine("Success! {0} was removed! ^_^", Program.Title);
                Pause();
            }
            finally
            {
                SetOutput(true, true);
            }
        }
        public void DeployConsole()
        {
            SetOutput(_isPassive, _isPassive && _isForced);
            try
            {
                System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    DeployElevated();
                    return;
                }

                List<GitInstallation> installations = null;

                // use the custom installation path if supplied
                if (!String.IsNullOrEmpty(_customPath))
                {
                    if (!Directory.Exists(_customPath))
                    {
                        Program.LogEvent("No Git installation found, unable to continue deployment.", EventLogEntryType.Error);
                        Console.Out.WriteLine();
                        Program.WriteLine($"Fatal: custom path does not exist: '{_customPath}'. {FailFace}");
                        Pause();

                        Result = ResultValue.InvalidCustomPath;
                        return;
                    }

                    Console.Out.WriteLine();
                    Console.Out.WriteLine($"Deploying to custom path: '{_customPath}'.");

                    // if the custom path points to a git location then treat it properly
                    GitInstallation installation;
                    if (Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows64v2, out installation)
                        || Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v2, out installation)
                        || Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v1, out installation))
                    {
                        Git.Trace.WriteLine($"   Git found: '{installation.Path}'.");

                        // track known Git installations
                        installations = new List<GitInstallation>();
                        installations.Add(installation);
                    }

                    Program.LogEvent($"Custom path deployed to: '{_customPath}'", EventLogEntryType.Information);
                }
                // since no custom installation path was supplied, use default logic
                else
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Looking for Git installation(s)...");

                    if (Where.FindGitInstallations(out installations))
                    {
                        foreach (var installation in installations)
                        {
                            Console.Out.WriteLine($"  {installation.Path}");
                        }
                    }
                }

                if (installations == null)
                {
                    Program.LogEvent("No Git installation found, unable to continue.", EventLogEntryType.Error);
                    Console.Out.WriteLine();
                    Program.WriteLine("Fatal: Git was not detected, unable to continue. {FailFace}");
                    Pause();

                    Result = ResultValue.GitNotFound;
                    return;
                }

                List<string> copiedFiles;
                foreach (var installation in installations)
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine($"Deploying from '{Program.Location}' to '{installation.Path}'.");

                    if (CopyFiles(Program.Location, installation.Libexec, FileList, out copiedFiles))
                    {
                        int copiedCount = copiedFiles.Count;

                        foreach (var file in copiedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }

                        // copy help documents
                        if (Directory.Exists(installation.Doc)
                            && CopyFiles(Program.Location, installation.Doc, DocsList, out copiedFiles))
                        {
                            copiedCount += copiedFiles.Count;

                            foreach (var file in copiedFiles)
                            {
                                Console.Out.WriteLine($"  {file}");
                            }
                        }

                        Program.LogEvent($"Deployment to '{installation.Path}' succeeded.", EventLogEntryType.Information);
                        Console.Out.WriteLine($"     {copiedCount} file(s) copied");
                    }
                    else if (_isForced)
                    {
                        Program.LogEvent($"Deployment to '{installation.Path}' failed.", EventLogEntryType.Warning);
                        Program.WriteLine($"  deployment failed. {FailFace}");
                    }
                    else
                    {
                        Program.LogEvent($"Deployment to '{installation.Path}' failed.", EventLogEntryType.Error);
                        Program.WriteLine($"  deployment failed. {FailFace}");
                        Pause();

                        Result = ResultValue.DeploymentFailed;
                        return;
                    }
                }

                Console.Out.WriteLine();
                Console.Out.WriteLine($"Deploying from '{Program.Location}' to '{UserBinPath}'.");

                if (!Directory.Exists(UserBinPath))
                {
                    Directory.CreateDirectory(UserBinPath);
                }

                if (CopyFiles(Program.Location, UserBinPath, FileList, out copiedFiles))
                {
                    int copiedCount = copiedFiles.Count;

                    foreach (var file in copiedFiles)
                    {
                        Console.Out.WriteLine($"  {file}");
                    }

                    if (CopyFiles(Program.Location, UserBinPath, DocsList, out copiedFiles))
                    {
                        copiedCount = copiedFiles.Count;

                        foreach (var file in copiedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }
                    }

                    Program.LogEvent($"Deployment to '{UserBinPath}' succeeded.", EventLogEntryType.Information);
                    Console.Out.WriteLine($"     {copiedCount} file(s) copied");
                }
                else if (_isForced)
                {
                    Program.LogEvent($"Deployment to '{UserBinPath}' failed.", EventLogEntryType.Warning);
                    Program.WriteLine($"  deployment failed. {FailFace}");
                }
                else
                {
                    Program.LogEvent($"Deployment to '{UserBinPath}' failed.", EventLogEntryType.Error);
                    Program.WriteLine($"  deployment failed. {FailFace}");
                    Pause();

                    Result = ResultValue.DeploymentFailed;
                    return;
                }

                if (CygwinPath != null && Directory.Exists(CygwinPath))
                {
                    if (CopyFiles(Program.Location, CygwinPath, FileList, out copiedFiles))
                    {
                        int copiedCount = copiedFiles.Count;

                        foreach (var file in copiedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }

                        if (CopyFiles(Program.Location, CygwinPath, DocsList, out copiedFiles))
                        {
                            copiedCount = copiedFiles.Count;

                            foreach (var file in copiedFiles)
                            {
                                Console.Out.WriteLine($"  {file}");
                            }
                        }

                        Program.LogEvent($"Deployment to '{CygwinPath}' succeeded.", EventLogEntryType.Information);
                        Console.Out.WriteLine($"     {copiedCount} file(s) copied");
                    }
                    else if (_isForced)
                    {
                        Program.LogEvent($"Deployment to '{CygwinPath}' failed.", EventLogEntryType.Warning);
                        Program.WriteLine($"  deployment failed. {FailFace}");
                    }
                    else
                    {
                        Program.LogEvent($"Deployment to '{CygwinPath}' failed.", EventLogEntryType.Error);
                        Program.WriteLine($"  deployment failed. {FailFace}");
                        Pause();

                        Result = ResultValue.DeploymentFailed;
                        return;
                    }
                }

                Configuration.Type types = Configuration.Type.Global;

                Configuration.Type updateTypes;
                if (SetGitConfig(installations, GitConfigAction.Set, types, out updateTypes))
                {
                    if ((updateTypes & Configuration.Type.Global) == Configuration.Type.Global)
                    {
                        Console.Out.WriteLine("Updated your ~/.gitconfig [git config --global]");
                    }
                    else
                    {
                        Console.Out.WriteLine();
                        Program.WriteLine("Fatal: Unable to update your ~/.gitconfig correctly.");

                        Result = ResultValue.GitConfigGlobalFailed;
                        return;
                    }
                }

                // all necessary content has been deployed to the system
                Result = ResultValue.Success;

                Program.LogEvent($"{Program.Title} v{Program.Version.ToString(3)} successfully deployed.", EventLogEntryType.Information);
                Console.Out.WriteLine();
                Console.Out.WriteLine($"Success! {Program.Title} was deployed! {TadaFace}");
                Pause();
            }
            finally
            {
                SetOutput(true, true);
            }
        }
Example #58
0
 //判断权限
 public bool IslimitAccess()
 {
     //检查系统权限
     System.Security.Principal.WindowsIdentity wid = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal p = new System.Security.Principal.WindowsPrincipal(wid);
     bool isAdmin = (p.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator));
     if (isAdmin == false)
     {
         MessageBox.Show("您目前登录的账号不具有管理员权限,请确认后使用应用:)", "权限警告", MessageBoxButtons.OK, MessageBoxIcon.Stop);
         return true;
     }
     else
     {
         return false;
     }
 }
 public static bool IsAdministratorRun()
 {
     System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
     if (null != identity)
     {
         System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
         return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
     }
     return false;
 }
Example #60
0
        private void InitWifiState()
        {
            bool result = WifiOperator.WifiStateQuery();
            if(result)
            {
                IsWifiOpened = true;
                Message = "Wifi已启动";
            }
            else
            {
                IsWifiOpened = false;
                Message = "Wifi未启动";
            }

            System.Security.Principal.WindowsIdentity wid = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal printcipal = new System.Security.Principal.WindowsPrincipal(wid);
            IsAdmin = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator));
            if (!IsAdmin)
            {
                Message = "请用管理员权限运行";
            }
        }