Esempio n. 1
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));
 }
Esempio n. 2
0
        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);
        }
Esempio n. 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;
        }
Esempio n. 4
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);
        }
Esempio n. 5
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());
            }
        }
Esempio n. 6
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);
        }
Esempio n. 7
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
        }
Esempio n. 8
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;
		}
Esempio n. 9
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());
     }
 }
Esempio n. 10
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
            { }
        }
Esempio n. 11
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());
            }
        }
Esempio n. 12
0
        static void Main()
        {
            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 Form1());
            }
            else
            {
                //创建启动对象
                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
                {
                }
            }


            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());
        }
Esempio n. 13
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);
        }
Esempio n. 14
0
        static void Main()
        {
            try
            {
                //获得当前登录的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))
                {
                    //如果是管理员,则直接运行
                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((obj, args) => dumpHelper.TryDump("error.dmp"));
                    Application.EnableVisualStyles();
                    Application.Run(new MainForm());
                }
                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();
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.Show("程序发生严重错误!错误:" + ex.ToString(), "程序崩溃");
                LOG.WriteLog("程序发生严重错误!错误:" + ex.ToString());
                if (UIMessageBox.ShowAsk("程序崩溃,是否要发送服务信息给作者,以帮助作者更好的完善软件?"))
                {
                    sendMail.sendmail("*****@*****.**", "松之宅矿工", "*****@*****.**", "松之宅矿工QQ", "dump文件提交", string.Concat(System.AppDomain.CurrentDomain.BaseDirectory, "error.dmp"), "error.dmp", "smtp.126.com", "*****@*****.**", "VEABHRROROCBHXNQ");
                }
            }
        }
Esempio n. 15
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();
            }
        }
Esempio n. 16
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 MDserv());
            }
            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 MDserv());
        }
Esempio n. 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);
        }
Esempio n. 18
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);
     }
 }
Esempio n. 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));
        }
Esempio n. 20
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
                {
                }
            }
        }
        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);
        }
Esempio n. 22
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;
        }
Esempio n. 23
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 { }
            }
        }
Esempio n. 24
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
        }
Esempio n. 25
0
 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);
     }
 }
Esempio n. 26
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());
            }
        }
Esempio n. 27
0
 /// <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);
     }
 }
Esempio n. 28
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();
            }
        }
Esempio n. 29
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);
        }
Esempio n. 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());
            }
        }
Esempio n. 31
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);
        }
Esempio n. 32
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
        }
Esempio n. 33
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;
     }
 }
Esempio n. 34
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();
            }
        }
Esempio n. 35
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();
                }
            }
        }
Esempio n. 36
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();
        }
Esempio n. 37
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();
             }
         }
     }
 }
Esempio n. 38
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");
            }
        }
Esempio n. 39
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 = "请用管理员权限运行";
            }
        }
Esempio n. 40
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
            {
                //启动对象
                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();
            }
        }
Esempio n. 41
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();
            }
        }
Esempio n. 42
0
        static void Main()
        {
            try
            {
                //获得当前登录的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 MainForm());
                }
                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();
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.Show("程序发生严重错误!错误:" + ex.ToString(), "程序崩溃");
            }
        }
        //禁用边缘
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var  wi         = System.Security.Principal.WindowsIdentity.GetCurrent();
            var  wp         = new System.Security.Principal.WindowsPrincipal(wi);
            bool runAsAdmin = wp.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);

            if (!runAsAdmin)
            {
                MessageBox.Show("请以管理员模式启动");
                return;
            }

            try
            {
                RegistryKey rk  = Registry.LocalMachine;
                RegistryKey rk2 = rk.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows\EdgeUI", true);
                rk2.SetValue("AllowEdgeSwipe", 0);
                MessageBox.Show("禁止边缘启动成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "温馨提示");
            }
        }
Esempio n. 44
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);
            }
        }
Esempio n. 45
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();
     }
 }
Esempio n. 46
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();
            }
        }
Esempio n. 47
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;
 }
Esempio n. 49
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 = "请用管理员权限运行";
            }
        }
Esempio n. 50
0
        /// <summary>
        /// receives the login data, compares it to the one stored at the server and sends a response according to if the login is correct or not...
        /// </summary>
        /// <returns>true if login is successful</returns>
        private bool ReceiveLogin()
        {
            Socket sock = connectedSocket;
            #region read length from client request
            byte[] b = new byte[32];
            int k = sock.Receive(b, b.Length, 0);

            string rcv = "";

            for (int i = 0; i < k; i++)
                rcv += Convert.ToChar(b[i]);
            #endregion

            #region receive login data
            string result = "NOK";
            bool res = false;
            //rcv = DecryptString(rcv);
            string[] loginData = rcv.Split(new string[] { "::" }, StringSplitOptions.None);

            IntPtr pExistingTokenHandle;

            const int LOGON32_PROVIDER_DEFAULT = 0;
            // create token
            const int LOGON32_LOGON_INTERACTIVE = 2;
            //const int SecurityImpersonation = 2;

            string sDomain = "";
            // get handle to token

            bool bImpersonated = LogonUser(loginData[0], sDomain, loginData[1], LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out pExistingTokenHandle);

            bool bIsGroupie = false;

            if (bImpersonated)
            {
                System.Security.Principal.WindowsIdentity identity = new System.Security.Principal.WindowsIdentity(pExistingTokenHandle);

                // get the principal to test the user against a built-in role

                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);

                // check the user against BUILTIN\Administrator

                if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)
                    || principal.IsInRole(AUDIT_USER_GROUP))
                {
                    bIsGroupie = true;
                }
            }

            if (bImpersonated && bIsGroupie)
            {
                result = "OK";
                res = true;
            }
            else
            {
                result = "NOK";
                res = false;
            }
            //fo.SetStatusMsg("Recieved Login Data");
            #endregion

            #region send result back

            byte[] sender = System.Text.Encoding.ASCII.GetBytes(result);
            int msgLength = sender.Length;

            ASCIIEncoding asen = new ASCIIEncoding();
            byte[] msg = asen.GetBytes("" + msgLength);

            //sock.Send(msg, msg.Length, 0);

            //fo.SetStatusMsg("Sent Length: " + msg.Length);

            //Thread.Sleep(20);

            sock.Send(sender, sender.Length, 0);

            //fo.SetStatusMsg("Answer to login sent");

            return res;
            #endregion
        }
Esempio n. 51
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();
             }
         }
     }
 }
 static void Main(string[] args)
 {
     //first check to see if already running
     Regex myPatt = new Regex(@"\((.*)\)"); //extract process friendly name from full process
     Process myProc = Process.GetCurrentProcess();
     Match myMatch = myPatt.Match(myProc.ToString());
     String myProcFriendly = myMatch.Value.Substring(1, myMatch.Length - 2);//get rid of parentheses
     Process[] myProcArray = Process.GetProcessesByName(myProcFriendly);
     if (myProcArray.GetLength(0) > 1)
     {
         MessageBox.Show("This program is already running", DoTasksObj.mbCaption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         Environment.Exit(1);
     }
     System.Security.Principal.WindowsIdentity me = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal prin = new System.Security.Principal.WindowsPrincipal(me);
     if (!prin.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
     {//we are not an administrator user need to exit
         MessageBox.Show("This program must run under a Windows Administrator User", DoTasksObj.mbCaption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         Environment.Exit(1);
     }
     Log tcFileResizerLog = new Log(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\TA Utility 4TC TY11.log");
     if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\TA Utility 4TC TY10.log"))
         File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\TA Utility 4TC TY10.log");
     string hostUpgOrFormatCall;
     TrueCryptFile tcFileHDOld = new TrueCryptFile(); //setup object to hold original file information name path for Hard Drive
     TrueCryptFile tcFileTravOld = new TrueCryptFile();  //setup object to hold original file information name path for Traveler
     TasksBitField tasklist = new TasksBitField(); //setup object to hold flags of things to be done1
     DoTasksObj TcSoftware = new DoTasksObj();//setup object that has all methods to actually do stuff
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     if (args.Length == 0)
     {
         hostUpgOrFormatCall = "";
     }
     else
     {
         hostUpgOrFormatCall = args[0];
     }
     //hostUpgOrFormatCall = "hostupg"; //for debug purposes format hostupg May also need a change in SetFormatClsStartProcess for debug purposes
     GetTasksHI InfoFromUser = new GetTasksHI(tasklist, tcFileHDOld, tcFileTravOld,hostUpgOrFormatCall);
     if (hostUpgOrFormatCall != "hostupg")
     {//user usage or call to format so need to actually show dialog box for interaction
         InfoFromUser.ShowDialog();
         if (InfoFromUser.DialogResult != DialogResult.OK)
         {
             Environment.Exit(1);
         }
     }
     else
     {//have to upgrade host due to traveler insertion called from autoit start script
         Log.WritWTime("Host upgrade requested by parameter call");
         InfoFromUser.Check4HostUpgrade(); // sets up necessary flags for upgrade
         if (TrueCryptFilesNew.tcFileHDNewSize > 0)
         {
             Log.WritWTime("Host tpdata.tc to be upgraded, new size = " + TrueCryptFilesNew.tcFileHDNewSize.ToString() + "MB");
         }
     }
     Log.WritSection(string.Format("TaskList = 0x{0:X}", tasklist.taskList));
     tasklist.LogTasks();
     //Next  TC software object does tasklist
     //Environment.Exit(1);  //used to stop program here at the point where can examine Log but before and changes are done
     TcSoftware.DoTasks(tasklist,tcFileHDOld,tcFileTravOld);
 }
Esempio n. 53
0
        private static bool RunAsAdmin( string args )
        {
            // Run as admin if not already
            bool isAdmin = false;
            try {
                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) {
                // Do nothing, isAdmin is already false
            }
            if(!isAdmin) {
                // Relaunch as an admin

                var processStartInfo = new System.Diagnostics.ProcessStartInfo( );

                processStartInfo.FileName = Application.ExecutablePath;
                processStartInfo.WorkingDirectory = Environment.CurrentDirectory;
                processStartInfo.Verb = "runas";
                processStartInfo.Arguments = args;

                processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                processStartInfo.UseShellExecute = true;

                //System.Diagnostics.Process process = null;
                try {
                    var process = System.Diagnostics.Process.Start( processStartInfo );
                } catch(Exception ex) {
                    MessageBox.Show( string.Format( @"Error launching as admin: {0}", ex.Message ) );
                }
            }
            return isAdmin;
        }
Esempio n. 54
0
        public static void SetWindowsEventLog_UAC()
        {
            if ((Config.Settings.EventLog_WriteTo_WindowsApplicationLog == true) || (Config.Settings.ErrorLog_WriteTo_WindowsApplicationLog == true))
            {
                // check first if its possible to write to even log without being admin
                try
                {
                    DateTime now = DateTime.Now;
                    System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();

                    // Set the source name for writing log entries.
                    eventLog.Source = "BlobIM";

                    // Create an event ID to add to the event log
                    int eventID = 111;

                    // Write an entry to the event log.
                    eventLog.WriteEntry("Permission Check" + " - " + now + " \r\n This entry is created when BIM is started to verify if it has permissions to write to windows event log.",
                                        System.Diagnostics.EventLogEntryType.Information,
                                        eventID);

                    // Close the Event Log
                    eventLog.Close();
                }
                catch (Exception e)
                {
                    System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
                    bool administrativeMode = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);

                    if (!administrativeMode)
                    {
                        MessageBox.Show("Administrative Permissions Required \n You have selected in the BIM Configuration to have BIM Log Events to the Windows Event Log. \n It does not appear it is possible with the current user, BIM will now request Administrative Permissions to do so. ");
                        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                        startInfo.Verb = "runas";
                        startInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
                        try
                        {
                            System.Diagnostics.Process.Start(startInfo);
                            Application.Exit();
                            Environment.Exit(0);
                        }
                        catch (Exception ex)
                        {
                            Alerting.ErrorLogging.WriteTo_Log("Failed Running as Administrator", ex.ToString());
                            return;
                        }
                        return;
                    }
                    else
                    {
                        System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();
                        // Check if the event source exists. If not create it.
                        if (!System.Diagnostics.EventLog.SourceExists("BlobIM"))
                        {
                            System.Diagnostics.EventLog.CreateEventSource("BlobIM", "Application");
                        }
                    }
                }

            }
        }
        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);
            }
        }
 private bool IsInAdmin()
 {
     System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
     return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
 }
        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);
            }
        }
Esempio n. 58
0
 internal static void ThrowIfNotAdministrator()
 {
     System.Security.Principal.WindowsIdentity currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(currentIdentity);
     if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
     {
         string message = g_resourceMgr.GetString("ErrorElevationNeeded");
         throw new InvalidOperationException(message);
     }
 }
Esempio n. 59
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;
		}
Esempio n. 60
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();
        }