Exemplo n.º 1
0
        private void NTAccess()
        {
            IntPtr token = new IntPtr();
            IntPtr dupToken = new IntPtr();
            //if (WIN32.Win32API.LogonUser("BATCHWEB", "SVIGI-11", "HEXTRADIFERENTE",
            if (WIN32.Win32API.LogonUser("DOTNETADMIN", "SVWEB02-07", "P@ELL@59",
                DotNet.Tools.WIN32.Win32API.LogonTypes.NewCredentials,
                DotNet.Tools.WIN32.Win32API.LogonProviders.Default, out token))
            {
                int ok = WIN32.Win32API.DuplicateToken(token, 2, ref dupToken);
            }
            System.Security.Principal.WindowsIdentity id = new System.Security.Principal.WindowsIdentity(dupToken);

            System.Security.Principal.WindowsImpersonationContext impersonatedUser = id.Impersonate();

            impersonatedUser.ToString();

            //System.Security.Principal.WindowsPrincipal p = new System.Security.Principal.WindowsPrincipal(id);
        }
 private void _get_access()
 {
     IntPtr _token = new IntPtr();
     if (Win32API.LogonUser(_user_name, _domain_name, _password,
         Win32API.LogonTypes.NewCredentials,
         Win32API.LogonProviders.Default,
         out _token))
     {
         _ok = true;
         Win32API.DuplicateToken(_token, 2, ref _main_token);
         _win_identity = new System.Security.Principal.WindowsIdentity(_main_token);
         _win_identity_context = _win_identity.Impersonate();
     }
     else
     {
         _ok = false;
         try
         {
             _error =
                 System.Runtime.InteropServices.Marshal.GetLastWin32Error().ToString();
         }
         catch (Exception ex) { }
     }
 }
Exemplo n.º 3
0
 /// <summary>
 /// public constructor
 /// </summary>
 /// <param name="upn_uname">UPN user name example : admin@WS01 , where 'WS01' is a domain name </param>
 /// <param name="password"> password </param>
 public AutomagicAdmin( string upn_uname, string password )
 {
     try
     {
         AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
         System.Security.Principal.WindowsIdentity idnt =
             new System.Security.Principal.WindowsIdentity(upn_uname, password );
         context = idnt.Impersonate();
     }
     catch (Exception)
     {
         context = null;
     }
 }
Exemplo n.º 4
0
        static void Main()
        {
            // Check OS since we are using dual-mode socket
            if (!Utils.IsWinVistaOrHigher())
            {
                MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Utils.ReleaseMemory(true);
            using (Mutex mutex = new Mutex(false, "Global\\Shadowsocks_" + Application.StartupPath.GetHashCode()))
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.ApplicationExit   += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.ApplicationExit += (sender, args) => HotKeys.Destroy();

                if (!mutex.WaitOne(0, false))
                {
                    Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
                    if (oldProcesses.Length > 0)
                    {
                        Process oldProcess = oldProcesses[0];
                    }
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + "\n" +
                                    I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                                    I18N.GetString("Shadowsocks is already running."));
                    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))
                {
                    var process  = System.Diagnostics.Process.GetCurrentProcess();
                    var filename = process.MainModule.FileName;
                    //创建启动对象
                    var p = new System.Diagnostics.Process();
                    p.StartInfo.UseShellExecute  = true;
                    p.StartInfo.WorkingDirectory = new FileInfo(filename).DirectoryName;
                    p.StartInfo.FileName         = filename;
                    //设置启动动作,确保以管理员身份运行
                    p.StartInfo.Verb = "runas";
                    try { p.Start(); } catch { }
                    //退出
                    Environment.Exit(0);
                }

                Directory.SetCurrentDirectory(Application.StartupPath);
#if DEBUG
                Logging.OpenLogFile();

                // truncate privoxy log file while debugging
                string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
                if (File.Exists(privoxyLogFilename))
                {
                    using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
                }
#else
                Logging.OpenLogFile();
#endif
                _controller     = new NewShadowsocksController();
                _viewController = new NewMenuViewController(_controller);
                HotKeys.Init();
                _controller.Start();
                Application.Run();
            }
        }
Exemplo n.º 5
0
        private void button1_Click(object sender, EventArgs e)
        {
            System.Security.Principal.WindowsIdentity currentUser =
                System.Security.Principal.WindowsIdentity.GetCurrent();

            bool animalProductsradio = radioButton1.Checked;
            bool vegetablesradio     = radioButton2.Checked;
            bool fruitsradio         = radioButton3.Checked;

            if (animalProductsradio)
            {
                string sql = "select ERSGroup_ID from " + schemaName + "ERSGroup_LU where ERSGroup_Username " +
                             "like '%" + currentUser.Name + "%' and [ERSGroup_ID] IN (" + apGroupId + ")";
                DataTable dt = GetData(sql);
                DataRow[] dr = dt.Select();

                if (dr.Length == 0)
                {
                    MessageBox.Show("You do not have access to the DB or this sector");
                }

                else
                {
                    newschemaName = "AnimalProductsCoSD.CoSD.";
                    string localSchemaName = GetSchemaName(newschemaName);
                    new Home(localSchemaName).Show();
                    Program.OpenDetailFormOnClose = true;

                    this.Close();
                }
            }

            if (vegetablesradio)
            {
                string    sql = "select ERSGroup_ID from " + "VegetablesCoSD.CoSD." + "ERSGroup_LU where ERSGroup_Username like '%" + currentUser.Name + "%' and [ERSGroup_ID] IN (" + vegGroupId + ")";
                DataTable dt  = GetData(sql);
                DataRow[] dr  = dt.Select();

                if (dr.Length == 0)
                {
                    MessageBox.Show("You do not have access to the DB or this sector");
                }

                else
                {
                    newschemaName = "VegetablesCoSD.CoSD.";
                    string localSchemaName = GetSchemaName(newschemaName);
                    new Home(localSchemaName).Show();
                    Program.OpenDetailFormOnClose = true;

                    this.Close();
                }
            }

            if (fruitsradio)
            {
                string    sql = "select ERSGroup_ID from " + "FruitCoSD.CoSD." + "ERSGroup_LU where ERSGroup_Username like '%" + currentUser.Name + "%' and [ERSGroup_ID] IN (" + fruitGroupId + ")";
                DataTable dt  = GetData(sql);
                DataRow[] dr  = dt.Select();

                if (dr.Length == 0)
                {
                    MessageBox.Show("You do not have access to the DB or this sector");
                }

                else
                {
                    newschemaName = "FruitCoSD.CoSD.";
                    string localSchemaName = GetSchemaName(newschemaName);
                    new Home(localSchemaName).Show();
                    Program.OpenDetailFormOnClose = true;

                    this.Close();
                }
            }
        }
Exemplo n.º 6
0
        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 <Installation> 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);
                        Program.Out.WriteLine();
                        Program.WriteLine($"Fatal: custom path does not exist: '{_customPath}'. {FailFace}");
                        Pause();

                        Result = ResultValue.InvalidCustomPath;
                        return;
                    }

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

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

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

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

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

                if (installations == null)
                {
                    Program.LogEvent("No Git installation found, unable to continue.", EventLogEntryType.Error);
                    Program.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)
                {
                    Program.Out.WriteLine();
                    Program.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)
                        {
                            Program.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)
                            {
                                Program.Out.WriteLine($"  {file}");
                            }
                        }

                        Program.LogEvent($"Deployment to '{installation.Path}' succeeded.", EventLogEntryType.Information);
                        Program.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;
                    }
                }

                Program.Out.WriteLine();
                Program.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)
                    {
                        Program.Out.WriteLine($"  {file}");
                    }

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

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

                    Program.LogEvent($"Deployment to '{UserBinPath}' succeeded.", EventLogEntryType.Information);
                    Program.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)
                        {
                            Program.Out.WriteLine($"  {file}");
                        }

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

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

                        Program.LogEvent($"Deployment to '{CygwinPath}' succeeded.", EventLogEntryType.Information);
                        Program.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;
                    }
                }

                ConfigurationLevel types = ConfigurationLevel.Global;

                ConfigurationLevel updateTypes;
                if (SetGitConfig(installations, GitConfigAction.Set, types, out updateTypes))
                {
                    if ((updateTypes & ConfigurationLevel.Global) == ConfigurationLevel.Global)
                    {
                        Program.Out.WriteLine("Updated your ~/.gitconfig [git config --global]");
                    }
                    else
                    {
                        Program.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);
                Program.Out.WriteLine();
                Program.Out.WriteLine($"Success! {Program.Title} was deployed! {TadaFace}");
                Pause();
            }
            finally
            {
                SetOutput(true, true);
            }
        }
 public override PMSSession AuthenticateUserCredentials(System.Security.Principal.WindowsIdentity identity)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 8
0
 public bool isAdmin()
 {
     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));
 }
Exemplo n.º 9
0
        private bool UserLoggedIn(out UIUserLogin loggedInUser)
        {
            loggedInUser = null;
            try
            {
                if (CurrentUser == null)
                {
                    string[] strLoginName = System.Web.HttpContext.Current.User.Identity.Name.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries);
                    string   domain       = strLoginName[0];
                    string   loginName    = strLoginName[1];

                    //Checking user in Database.
                    BLUserAdministration objBLUserAdministration = new BLUserAdministration();
                    ExceptionTypes       result = objBLUserAdministration.GetUserAccessPermission(loginName, null, null, null, out loggedInUser);
                    if (result == ExceptionTypes.ZeroRecords)
                    {
                        return(false);
                    }
                    if (result != (long)ExceptionTypes.Success)
                    {
                        return(false);
                    }
                    else
                    {
                        System.Security.Principal.WindowsIdentity             winIdnt = System.Web.HttpContext.Current.User.Identity as System.Security.Principal.WindowsIdentity;
                        System.Security.Principal.IdentityReferenceCollection grps    = winIdnt.Groups;
                        //Admin
                        if (IsUserInADGroup(grps, WebConfigData.AdminSID))
                        {
                            loggedInUser.IsAdminUser = true;
                        }

                        //OST
                        if (IsUserInADGroup(grps, WebConfigData.AdminOSTSID))
                        {
                            loggedInUser.IsAdmOSTUser = true;
                        }
                        if (IsUserInADGroup(grps, WebConfigData.ManagerOSTSID))
                        {
                            loggedInUser.IsMgrOSTUser = true;
                        }
                        if (IsUserInADGroup(grps, WebConfigData.ProcessorOSTSID))
                        {
                            loggedInUser.IsPrcrOSTUser = true;
                        }
                        if (IsUserInADGroup(grps, WebConfigData.ViewerOSTSID))
                        {
                            loggedInUser.IsVwrOSTUser = true;
                        }

                        //Eligibility
                        if (IsUserInADGroup(grps, WebConfigData.AdminEligSID))
                        {
                            loggedInUser.IsAdmEligUser = true;
                        }
                        if (IsUserInADGroup(grps, WebConfigData.ManagerEligSID))
                        {
                            loggedInUser.IsMgrEligUser = true;
                        }
                        if (IsUserInADGroup(grps, WebConfigData.ProcessorEligSID))
                        {
                            loggedInUser.IsPrcrEligUser = true;
                        }
                        if (IsUserInADGroup(grps, WebConfigData.ViewerEligSID))
                        {
                            loggedInUser.IsVwrEligUser = true;
                        }

                        //RPR
                        if (IsUserInADGroup(grps, WebConfigData.AdminRPRSID))
                        {
                            loggedInUser.IsAdmRPRUser = true;
                        }
                        if (IsUserInADGroup(grps, WebConfigData.ManagerRPRSID))
                        {
                            loggedInUser.IsMgrRPRUser = true;
                        }
                        if (IsUserInADGroup(grps, WebConfigData.ProcessorRPRSID))
                        {
                            loggedInUser.IsPrcrRPRUser = true;
                        }
                        if (IsUserInADGroup(grps, WebConfigData.ViewerRPRSID))
                        {
                            loggedInUser.IsVwrRPRUser = true;
                        }

                        if (loggedInUser.IsAdminUser == false &&
                            loggedInUser.IsAdmOSTUser == false &&
                            loggedInUser.IsAdmEligUser == false &&
                            loggedInUser.IsAdmRPRUser == false &&
                            loggedInUser.IsMgrOSTUser == false &&
                            loggedInUser.IsMgrEligUser == false &&
                            loggedInUser.IsMgrRPRUser == false &&
                            loggedInUser.IsPrcrOSTUser == false &&
                            loggedInUser.IsPrcrEligUser == false &&
                            loggedInUser.IsPrcrRPRUser == false &&
                            loggedInUser.IsVwrOSTUser == false &&
                            loggedInUser.IsVwrEligUser == false &&
                            loggedInUser.IsVwrRPRUser == false &&
                            loggedInUser.IsWebServiceUser == false &&
                            loggedInUser.IsMacroServiceUser == false
                            )
                        {
                            return(false);
                        }
                        else
                        {
                            CurrentUser = loggedInUser;
                        }
                    }
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="context"></param>
        /// <param name="wsFactory"></param>
        /// <param name="wsmHandler"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler, IAutomaticPostingFactory apFactory)
        {
            if (context.Request.Path == "/MesServiceStation")
            {
                Helperlog4.Info("新连接完成" + context.Request.Path.ToString());
                if (context.WebSockets.IsWebSocketRequest)
                {
                    System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
                    string usesid           = currentUser.User.ToString();
                    string customwebsocketS = context.Request.Query["username"];
                    //string username = usesid + "------Name";
                    if (!string.IsNullOrEmpty(customwebsocketS))
                    {
                        CustomWebSocket customwebsocket = customwebsocketS.ConvertToObject <CustomWebSocket>();
                        WebSocket       webSocket       = await context.WebSockets.AcceptWebSocketAsync();

                        List <CustomWebSocket> CustomWebSocketList = new List <CustomWebSocket>();
                        CustomWebSocketList = wsFactory.Others(customwebsocket.Username);
                        if (CustomWebSocketList.Count > 0)
                        {
                            CustomWebSocket userWebSocket1 = new CustomWebSocket();
                            userWebSocket1 = CustomWebSocketList[0];
                            wsFactory.Remove(userWebSocket1.Username);
                            CustomWebSocket userWebSocket = new CustomWebSocket()
                            {
                                WebSocket = webSocket,
                                Username  = userWebSocket1.Username,
                                UseSid    = usesid,
                                Url       = context.Request.GetDisplayUrl(),
                                UserType  = userWebSocket1.UserType
                            };
                            wsFactory.Add(userWebSocket);
                            //await Heartbeat(wsFactory, wsmHandler);
                            Helperlog4.Info("重新连接返回值" + userWebSocket.ConvertToJson());
                            await wsmHandler.SendInitialMessages(userWebSocket);
                            await Listen(context, userWebSocket, wsFactory, wsmHandler, apFactory);
                        }
                        else
                        {
                            CustomWebSocket userWebSocket = new CustomWebSocket()
                            {
                                WebSocket = webSocket,
                                Username  = customwebsocket.Username,
                                UseSid    = usesid,
                                Url       = context.Request.GetDisplayUrl(),
                                UserType  = customwebsocket.UserType
                            };
                            wsFactory.Add(userWebSocket);

                            Helperlog4.Info("新连接返回值" + userWebSocket.ConvertToJson());
                            //await Heartbeat(wsFactory, wsmHandler);
                            await wsmHandler.SendInitialMessages(userWebSocket);
                            await Listen(context, userWebSocket, wsFactory, wsmHandler, apFactory);
                        }
                    }
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            }
            await _next(context);
        }
Exemplo n.º 11
0
        }//end method

        /// <summary>
        /// 读取注册中开票软件信息
        /// </summary>
        /// <returns></returns>
        public static List <SBConfigInfo> ReadPath(string NSRSBH, string FJH)
        {
            bool isInReg             = false;
            List <SBConfigInfo> list = new List <SBConfigInfo>();

            // 读取注册表
            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))
                {
                    string[] strs = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\fwkp.exe\", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl).GetSubKeyNames();
                    if (strs != null)
                    {
                        foreach (string name in strs)
                        {
                            SBConfigInfo sb = new SBConfigInfo();
                            isInReg = true;
                            RegistryKey regRead;
                            regRead = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\fwkp.exe\" + name, RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl);
                            if (regRead.GetValue("code") != null && regRead.GetValue("machine") != null && regRead.GetValue("code").ToString().ToUpper().Trim().Equals(NSRSBH.ToUpper().Trim()) && regRead.GetValue("machine").ToString().Trim().Equals(FJH.Trim()) &&
                                regRead.GetValue("Path") != null)
                            {
                                sb.Path = regRead.GetValue("Path").ToString();
                                if (regRead.GetValue("orgcode") != null)
                                {
                                    sb.DQBM = regRead.GetValue("orgcode").ToString();
                                }
                                else
                                {
                                    sb.DQBM = "";
                                }
                                if (regRead.GetValue("Version") != null)
                                {
                                    sb.KPVersion = regRead.GetValue("Version").ToString();
                                }
                                else
                                {
                                    sb.KPVersion = "";
                                }
                                list.Add(sb);
                            }
                        }
                    }
                    else
                    {
                        Logging.Log4NetHelper.Error(typeof(RegisterHelper), Message.ReadRegistryFailed);
                        return(new List <SBConfigInfo>());
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Log4NetHelper.Error(typeof(RegisterHelper), Message.GetRegistryFailed + ex.Message + System.Environment.NewLine + ex.StackTrace);
                return(new List <SBConfigInfo>());
            }

            if (list.Count == 0 && isInReg)
            {
                Logging.Log4NetHelper.Error(typeof(RegisterHelper), Message.AdministratorFailed);
            }
            return(list);
        }
Exemplo n.º 12
0
        private void btnLogin_Click(System.Object sender, System.EventArgs e)
        {
            #region Disable Code
            //Check login information from database
            //			ACMSLogic.User oUser = new User();
            //			bool chkUserLogin = false;
            //
            //			chkUserLogin = System.Convert.ToBoolean(oUser.Login(txtUsername.Text, txtPassword.Text));
            //
            //			if (chkUserLogin)
            //			{
            //				if (cmbModule.Text == "ACMS Branch")
            //				{
            //					//Show AMCS Branch
            //					if (modInitForms.fBranch == null)
            //					{
            //						modInitForms.fBranch = new frmBranch();
            //						modInitForms.fBranch.initData(oUser);
            //						modInitForms.fBranch.Show();
            //					}
            //
            //					modInitForms.fLogin.Hide();
            //				}
            //
            //				if (cmbModule.Text == "ACMS POS")
            //				{
            //					//Show AMCS POS
            //					if (modInitForms.fPOS == null)
            //					{
            //						modInitForms.fPOS = new frmPOS();
            //						modInitForms.fPOS.Show();
            //					}
            //
            //					modInitForms.fLogin.Hide();
            //				}
            //
            //				if (cmbModule.Text == "ACMS Staff")
            //				{
            //					//Show AMCS POS
            //					if (modInitForms.fStaff == null)
            //					{
            //						modInitForms.fStaff = new frmStaff();
            //						modInitForms.fStaff.Show();
            //					}
            //
            //					modInitForms.fLogin.Hide();
            //				}
            //			}
            //			else
            //			{
            //				MessageBox.Show(this, "Incorrect username and password, please try again");
            //			}
            #endregion
            //DateTime start = DateTime.Now;
            if (this.txtUsername.Text == "" | this.txtPassword.Text == "")
            {
                ACMS.Utils.UI.ShowErrorMessage(this, "Empty Username & Password!", "Error");
            }

            else
            {
                try
                {
                    ACMSLogic.Login.Login login = new ACMSLogic.Login.Login();
                    //Do.Employee emplogin = login.GetEmployeeByIdAndPassword(this.txtUsername.Text, this.txtPassword.Text);

                    //MessageBox.Show(this, emplogin.Id.ToString()+" "+emplogin.Department.Id+" "+emplogin.RightsLevel.RightsLevelEntrys.Count.ToString());

                    //Rp.EmployeeRepository er = new Rp.EmployeeRepository();
                    Do.Employee emp = login.GetEmployeeByIdAndPassword(this.txtUsername.Text, this.txtPassword.Text);                    //er.GetEmployeeByIdAndPassword(this.txtUsername.Text, this.txtPassword.Text);

                    System.Security.Principal.WindowsIdentity userLogin = System.Security.Principal.WindowsIdentity.GetCurrent();

                    if (login.Check_Concurrent() == false)
                    {
                        ACMS.Utils.UI.ShowErrorMessage(this, "Number of Login Exceed Users Limit!", "Authorisation");
                    }
                    else
                    {
                        //Rp.TerminalUserRepository tup = new Rp.TerminalUserRepository();
                        if (emp != null)
                        {
                            Acms.Core.Domain.TerminalUser tu = login.GetTerminalUserByUserId(userLogin.Name) as Acms.Core.Domain.TerminalUser;                            //tup.GetTerminalUserByUserId(userLogin.Name) as Acms.Core.Domain.TerminalUser;

                            //Show AMCS Branch
                            bool Valid = numberUser();
                            //bool Valid = true;
                            if (emp.CanAccess("AB_LOGIN", tu.Branch.Id) && Valid)
                            {
                                //smell tandas code
                                ACMSDAL.TblTerminalUser UserLog = new TblTerminalUser();
                                UserLog.StrTerminalUserCode = userLogin.Name;
                                UserLog.UpdateSession(true, DateTime.Now);

                                modInitForms.fLogin.Hide();
                                ACMSLogic.User.BranchCode = tu.Branch.Id;
                                ACMSLogic.User.EmployeeID = emp.Id;
                                if (emp.Department != null)
                                {
                                    ACMSLogic.User.DepartmentID = emp.Department.Id;
                                }
                                if (emp.StrEmployeeName != null)
                                {
                                    ACMSLogic.User.EmployeeName = emp.StrEmployeeName;
                                }
                                if (emp.JobPosition.Id != null)
                                {
                                    ACMSLogic.User.JobPositionCode = emp.JobPosition.Id;
                                }
                                if (emp.RightsLevel != null)
                                {
                                    ACMSLogic.User.RightsLevelID = emp.RightsLevel.Id;
                                }
                                try
                                {
                                    ClassAttendance.CreateClassInstance();
                                    PackageCode.CreateUnLinkPackage();
                                }
                                catch (Exception ex)
                                {
                                    return;
                                }
                                ACMSLogic.User oUser = new User();

                                if (modInitForms.fBranch != null)
                                {
                                    modInitForms.fBranch.IsLogin = true;
                                    modInitForms.fBranch.Close();
                                    modInitForms.fBranch.Dispose();
                                    if (modInitForms.fStaff != null)
                                    {
                                        modInitForms.fStaff.Close();
                                        modInitForms.fStaff.Dispose();
                                    }
                                    if (modInitForms.fManager != null)
                                    {
                                        modInitForms.fManager.Close();
                                        modInitForms.fManager.Dispose();
                                    }
                                }
                                modInitForms.fBranch = new frmBranch(cmbLanguage.EditValue.ToString());
                                modInitForms.fBranch.SetEmployeeRecord(emp);
                                modInitForms.fBranch.SetTerminalUser(tu);
                                modInitForms.fBranch.OpenDayShift();

                                //						if (UnclosedShift == true)
                                //							MessageBox.Show("There is unclosed shift. Please close the shift.");

                                modInitForms.fBranch.initData(oUser);
                                modInitForms.fBranch.Show();

                                //DateTime end = DateTime.Now;
                                //TimeSpan diff = end.Subtract(start);
                                //MessageBox.Show(diff.TotalSeconds.ToString(),"Time");
                            }
                            else if (emp.CanAccess("AB_TIMECARD_LOGIN", tu.Branch.Id))
                            {
                                modInitForms.fLogin.Hide();
                                //Show AMCS Time Card
                                if (modInitForms.fTimeCard == null)
                                {
                                    modInitForms.fTimeCard = new frmTimeCard(tu.Branch.Id);
                                    modInitForms.fTimeCard.Show();
                                }
                            }
                            else
                            {
                                MessageBox.Show(this, "Invalid username and password or you don't have access to this Branch, please try again");
                            }
                        }
                        else
                        {
                            MessageBox.Show(this, "Invalid username and password, Please try again");
                        }
                    }
                }
                catch (Exception ex)
                {
                    return;
                }
            }
        }
Exemplo n.º 13
0
 public static string getUserSID()
 {
     System.Security.Principal.WindowsIdentity id = System.Security.Principal.WindowsIdentity.GetCurrent();
     return(id.User.ToString());
 }
Exemplo n.º 14
0
        /// <summary>
        /// mainForm窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mainForm_Load(object sender, EventArgs e)
        {
            //获取当前用户名和计算机名并写入日志
            textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "计算机名: " + System.Environment.UserDomainName + "\r\n");
            textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "当前用户: " + System.Environment.UserName + "\r\n");
            //检查当前用户权限
            System.Security.Principal.WindowsIdentity  wid        = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal printcipal = new System.Security.Principal.WindowsPrincipal(wid);
            textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "角色信息:" + printcipal.Identity.Name.ToString() + "\r\n");

            /*
             * bool isUser = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator));
             * if (isUser)
             *  textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "当前用户角色: Administrator" + "\r\n");
             * isUser = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.User));
             * if (isUser)
             *  textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "当前用户角色: User" + "\r\n");
             * isUser = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.AccountOperator));
             * if (isUser)
             *  textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "当前用户角色: AccountOperator" + "\r\n");
             * isUser = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.BackupOperator));
             * if (isUser)
             *  textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "当前用户角色: BackupOperator" + "\r\n");
             * isUser = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Guest));
             * if (isUser)
             *  textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "当前用户角色: Guest" + "\r\n");
             * isUser = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.PowerUser));
             * if (isUser)
             *  textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "当前用户角色: PowerUser" + "\r\n");
             * isUser = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.PrintOperator));
             * if (isUser)
             *  textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "当前用户角色: PrintOperator" + "\r\n");
             * isUser = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Replicator));
             * if (isUser)
             *  textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "当前用户角色: Replicator" + "\r\n");
             * isUser = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.SystemOperator));
             * if (isUser)
             *  textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "当前用户角色: SystemOperator" + "\r\n");
             */
            textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "当前用户需要文件写入和注册表操作权限,否则相关参数不起作用!" + "\r\n");

            //读取设置文件aliddns_config.xml
            if (readConfigFile())
            {
                string ExePath   = System.AppDomain.CurrentDomain.BaseDirectory;
                string updateExe = ExePath + "update.exe";
                if (checkUpdate == true)
                {
                    if (File.Exists(updateExe))
                    {
                        //执行update.exe
                    }
                    else
                    {
                        textBox_log.AppendText(System.DateTime.Now.ToString() + " " + "版本检测程序update.exe未找到,跳过版本检测! " + "\r\n");
                    }
                }

                //窗体根据参数判断是否最小化驻留系统托盘
                if (checkBox_minimized.Checked == true)
                {
                    this.ShowInTaskbar = false;                     //从状态栏清除
                    this.WindowState   = FormWindowState.Minimized; //窗体最小化
                    this.Hide();                                    //窗体隐藏
                }
                else if (checkBox_minimized.Checked == false)
                {
                    this.Show();                                 //窗体显示
                    this.WindowState   = FormWindowState.Normal; //窗体正常化
                    this.ShowInTaskbar = true;                   //从状态栏显示
                }

                //获取阿里云域名记录绑定IP
                //domainIP.Text = getAliDnsRecordDomainIP();
                //获取WAN口IP
                //localIP.Text = getWanIP();
                if (checkBox_autoBoot.Checked == true)
                {
                    updatePrepare();
                }
            }
            notifyIcon_sysTray_Update(); //监测网络状态、刷新系统托盘图标
        }
Exemplo n.º 15
0
        public static string getCurrentUser()
        {
            string retVal = System.Environment.MachineName;
            if (retVal.ToLower() == "k2")
                return retVal;
            if (retVal.ToLower() == "ks")
                return "simon";
            int i=0;
            loggedIn = false;
            if (!loginChecked)
                lastLoggedIn = false;
            System.Security.Principal.WindowsIdentity wi;
            try
            {
                System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("explorer");
                if (process.Length > 0)
                {
                    if (process[i].ProcessName.ToLower().CompareTo("explorer") == 0)
                    {
                        int access = 0X00000008;
                        HANDLE logonToken = IntPtr.Zero;
                        if (OpenProcessToken(process[i].Handle,access,ref logonToken))
                        {
                            wi = new System.Security.Principal.WindowsIdentity(logonToken);
                            retVal = wi.Name;
                            loggedIn = true;
                            if (!loginChecked)
                                lastLoggedIn = true;
                        }
                    }
                }
            }
            catch (Exception e) {}

            currentUser = retVal;
            loginChecked = true;
            return retVal;
        }
 protected WindowsIdentity(System.Security.Principal.WindowsIdentity identity)
 {
 }
Exemplo n.º 17
0
        public static void Main(String[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine(String.Format("Usage: {0} <extension|url> <progid>", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name));
                return;
            }

            try
            {
                String extension = args[0];
                String progid    = args[1];

                String regpath;
                if (extension.StartsWith("."))
                {
                    regpath = String.Format("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\{0}\\UserChoice", extension);
                }
                else
                {
                    regpath = String.Format("SOFTWARE\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\{0}\\UserChoice", extension);
                }

                Registry.CurrentUser.DeleteSubKey(regpath, false);
                RegistryKey regnode = Registry.CurrentUser.CreateSubKey(regpath);

                System.Security.Principal.WindowsIdentity user = System.Security.Principal.WindowsIdentity.GetCurrent();
                String sid = user.User.Value;

                long ftLastWriteTime;
                RegQueryInfoKey(regnode.Handle.DangerousGetHandle(), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, out ftLastWriteTime);
                DateTime time = DateTime.FromFileTime(ftLastWriteTime);
                time            = time.AddTicks(-(time.Ticks % 600000000));         //clamp to minute part (1min=600000000*100ns)
                ftLastWriteTime = time.ToFileTime();

                String regdate = ftLastWriteTime.ToString("x16");

                String experience = "user choice set via windows user experience {d18b6dd5-6124-4341-9318-804003bafa0b}";

                //Step1: String (Unicode with 0 terminator) from the following: extension, user sid, progid, last modification time for the registry node clamped to minute part, secret experience string
                //Step2: Lowercase
                byte[] bytes = Encoding.Unicode.GetBytes((extension + sid + progid + regdate + experience + "\0").ToLower());
                System.Security.Cryptography.MD5 md5Hash = System.Security.Cryptography.MD5.Create();
                //Step3: MD5
                byte[] md5 = md5Hash.ComputeHash(bytes);
                //Step4: Microsoft hashes from data and md5, xored together
                byte[] mshash1  = sub_1(bytes, md5);
                byte[] mshash2  = sub_2(bytes, md5);
                byte[] finalraw = xorbytes(mshash1, mshash2);
                //Step5: Base64
                String hash = System.Convert.ToBase64String(finalraw);

                regnode.SetValue("ProgId", progid);
                regnode.SetValue("Hash", hash);

                Console.WriteLine("Success");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error during operation:");
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 18
0
 private bool IsAdministrator()
 {
     System.Security.Principal.WindowsIdentity  wi = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal wp = new System.Security.Principal.WindowsPrincipal(wi);
     return(wp.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator));
 }
Exemplo n.º 19
0
        static void Main(string[] agrs)
        {
            //try
            //{
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (!File.Exists(Application.StartupPath + "\\bass.dll"))
            {
                MessageBox.Show("无法加载迷你音乐的某个组件,程序可能已经损坏,请重新安装迷你音乐。", "这里出现了一点错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                Process[] p = Process.GetProcessesByName("MusicPlayer");

                if (agrs.Length > 0)
                {
                    string agrsc = "";
                    for (int i = 0; i < agrs.Length; i++)
                    {
                        agrsc = agrsc + " " + agrs[i];
                    }
                    if (Path.GetExtension(agrsc.ToLower()) == ".mp3" || Path.GetExtension(agrsc.ToLower()) == ".wav" || agrsc.ToLower().Contains(".mp3") || agrsc.ToLower().Contains(".mpa") || agrsc.ToLower().Contains(".mpc") || agrsc.ToLower().Contains(".wav") || agrsc.ToLower().Contains(".wmv") || agrsc.ToLower().Contains(".wv") || Path.GetExtension(agrsc.ToLower()) == ".m4a" || agrsc.ToLower().Contains(".wma") || agrsc.ToLower().Contains(".midi") || agrsc.ToLower().Contains(".mid") || Path.GetExtension(agrsc.ToLower()) == ".mid" || Path.GetExtension(agrsc.ToLower()) == ".midi" || Path.GetExtension(agrsc.ToLower()) == ".ogg")
                    {
                        if (p.Length > 1)
                        {
                            WinMessageUntil.SendMessageToProcess("MusicPlayer", "music#" + agrsc.Remove(0, 1));
                        }
                        else
                        {
                            Application.Run(new FormMain(agrsc.Remove(0, 1)));
                        }
                    }
                    else if (agrs[0] == "-test" || agrs[0] == "/test")
                    {
                        string agrs80968 = agrs[10];
                    }
                    else if (agrs[0] == "-test2" || agrs[0] == "/test2")
                    {
                    }
                    else if (agrs[0] == "-?" || agrs[0] == "/?")
                    {
                        MessageBox.Show("命令行参数:\nMusicPlayer.exe <文件名>    打开支持的文件,\nMusicPlayer.exe /test1    测试1,\nMusicPlayer.exe /mvplayer    mv播放器测试,\nMusicPlayer.exe /errorrestart    错误报告测试,\nMusicPlayer.exe /assion    修改打开方式.", "信息:");
                    }
                    else if (agrs[0] == "-test1" || agrs[0] == "/test1")
                    {
                    }
                    else if (agrs[0] == "-mvplayer" || agrs[0] == "/mvplayer")
                    {
                    }
                    else if (agrs[0] == "-errorrestart" || agrs[0] == "/errorrestart")
                    {
                        Application.Run(new FormErrorReport(agrs[1]));
                    }
                    else if (agrs[0] == "-assion" || agrs[0] == "/assion")
                    {
                        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))
                        {
                            try
                            {
                                RegistryKey key = Registry.ClassesRoot;

                                #region 修改1
                                string[] openf = new string[12];
                                openf[0]  = "mp3";
                                openf[1]  = "wav";
                                openf[2]  = "lrc";
                                openf[3]  = "wma";
                                openf[4]  = "m4a";
                                openf[5]  = "flac";
                                openf[6]  = "ogg";
                                openf[8]  = "ra";
                                openf[9]  = "cd";
                                openf[10] = "mid";
                                openf[11] = "midi";
                                for (int i = 0; i < openf.Length; i++)
                                {
                                    if (openf[i] != "" && openf[i] != null)
                                    {
                                        RegistryKey m1 = key.OpenSubKey("MusicPlayer." + openf[i]);
                                        if (m1 == null)
                                        {
                                            m1 = key.CreateSubKey("MusicPlayer." + openf[i]);
                                            RegistryKey m1icon = m1.CreateSubKey("DefaultIcon");
                                            if (openf[i] == "mp3")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,7");
                                            }
                                            if (openf[i] == "m4a")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,10");
                                            }
                                            else if (openf[i] == "wav")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,8");
                                            }
                                            else if (openf[i] == "lrc")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,6");
                                            }
                                            else if (openf[i] == "wma")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,9");
                                            }
                                            else if (openf[i] == "wma")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,9");
                                            }
                                            else if (openf[i] == "cd")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,14");
                                            }
                                            else if (openf[i] == "ra")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,13");
                                            }
                                            else if (openf[i] == "flac")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,5");
                                            }
                                            else if (openf[i] == "mid")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,11");
                                            }
                                            else if (openf[i] == "midi")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,11");
                                            }
                                            else if (openf[i] == "ogg")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,12");
                                            }

                                            RegistryKey shell = m1.CreateSubKey("Shell");
                                            RegistryKey open  = shell.CreateSubKey("Open");
                                            if (openf[i] == "mp3" || openf[i] == "wma" || openf[i] == "m4a" || openf[i] == "wav")
                                            {
                                                open.SetValue("", "播放音乐(&O)");
                                            }
                                            else
                                            {
                                                open.SetValue("", "打开(&O)");
                                            }
                                            RegistryKey command = open.CreateSubKey("command");
                                            command.SetValue("", Application.StartupPath + "\\MusicPlayer.exe \"%1\"");
                                        }
                                        else
                                        {
                                            key.DeleteSubKeyTree("MusicPlayer." + openf[i]);
                                            m1 = key.CreateSubKey("MusicPlayer." + openf[i]);
                                            RegistryKey m1icon = m1.CreateSubKey("DefaultIcon");
                                            if (openf[i] == "mp3")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,7");
                                            }
                                            if (openf[i] == "m4a")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,10");
                                            }
                                            else if (openf[i] == "wav")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,8");
                                            }
                                            else if (openf[i] == "lrc")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,6");
                                            }
                                            else if (openf[i] == "wma")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,9");
                                            }
                                            else if (openf[i] == "wma")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,9");
                                            }
                                            else if (openf[i] == "cd")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,14");
                                            }
                                            else if (openf[i] == "ra")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,13");
                                            }
                                            else if (openf[i] == "flac")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,5");
                                            }
                                            else if (openf[i] == "mid")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,11");
                                            }
                                            else if (openf[i] == "midi")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,11");
                                            }
                                            else if (openf[i] == "ogg")
                                            {
                                                m1icon.SetValue("", Application.StartupPath + "\\MusicPlayer.Utils.dll,12");
                                            }

                                            RegistryKey shell = m1.CreateSubKey("Shell");
                                            RegistryKey open  = shell.CreateSubKey("Open");
                                            if (openf[i] == "mp3" || openf[i] == "wma" || openf[i] == "m4a" || openf[i] == "wav")
                                            {
                                                open.SetValue("", "播放音乐(&O)");
                                            }
                                            else
                                            {
                                                open.SetValue("", "打开(&O)");
                                            }
                                            RegistryKey command = open.CreateSubKey("command");
                                            command.SetValue("", Application.StartupPath + "\\MusicPlayer.exe \"%1\"");
                                        }

                                        RegistryKey m2 = key.OpenSubKey("." + openf[i], true);
                                        if (m2 != null)
                                        {
                                            key.DeleteSubKeyTree("." + openf[i]);
                                        }
                                        RegistryKey m4 = Registry.CurrentUser;
                                        RegistryKey m3 = m4.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\." + openf[i], true);
                                        if (m3 != null)
                                        {
                                            try
                                            {
                                                m4.DeleteSubKeyTree(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\." + openf[i]);
                                            }
                                            catch
                                            {
                                            }
                                        }
                                        m2 = key.CreateSubKey("." + openf[i]);
                                        RegistryKey m21 = m2.OpenSubKey("OpenWithProgIds", true);
                                        if (m21 == null)
                                        {
                                            m21 = m2.CreateSubKey("OpenWithProgIds");
                                            m21.SetValue("MusicPlayer." + openf[i], 0, RegistryValueKind.DWord);
                                        }
                                        else
                                        {
                                            m21.SetValue("MusicPlayer." + openf[i], 0, RegistryValueKind.DWord);
                                        }
                                        m2.SetValue("", "MusicPlayer." + openf[i]);
                                    }
                                    else
                                    {
                                    }
                                }

                                #endregion

                                SHChangeNotify(0x8000000, 0, IntPtr.Zero, IntPtr.Zero);
                            }
                            catch (Exception ee)
                            {
                                MessageBox.Show(ee.ToString(), "这里有个错误:" + ee.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            if (MessageBox.Show("修改默认打开方式需要修改注册表,这必须要系统管理员权限,请选择“重试”并在稍后弹出的对话框中选择“是”继续。如果不想修改,请选择“取消”。", "这里有个错误:", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)
                            {
                                //创建启动对象
                                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                                //设置运行文件
                                startInfo.FileName  = System.Windows.Forms.Application.ExecutablePath;
                                startInfo.Arguments = String.Join(" ", agrs);
                                startInfo.Verb      = "runas";
                                System.Diagnostics.Process.Start(startInfo);
                                System.Windows.Forms.Application.Exit();
                            }
                        }
                    }
                    else
                    {
                        if (File.Exists(agrsc))
                        {
                            MessageBox.Show("不支持的文件格式:\n" + Path.GetExtension(agrsc), "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            MessageBox.Show("命令行参数错误,未知的参数:\n" + agrsc + "\n输入 \"-?\" 了解更多。", "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    if (p.Length > 1)
                    {
                        WinMessageUntil.SendMessageToProcess("MusicPlayer", "show");
                    }
                    else
                    {
                        Application.Run(new FormMain());
                    }
                }
            }
            //}
            //catch (Exception ee)

            /*{
             *  if (Debugger.IsAttached)
             *      throw ee;
             *  MessageBox.Show("迷你音乐遇到错误需要关闭,给您带来不便深表歉意。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
             *  WriteLog(ee.Message, DateTime.Now.ToString(), ee.ToString());
             *  string time = Application.StartupPath + @"\MusicPlayerError_log_" + DateTime.Now.Minute + ".log";
             *  FileStream fs = new FileStream(time, FileMode.Create);
             *  fs.Write(System.Text.Encoding.Default.GetBytes("迷你音乐错误记录:"), 0, System.Text.Encoding.Default.GetBytes("迷你音乐错误记录:").Length);
             *  fs.Close();
             *  StreamWriter sw = new StreamWriter(time, true, System.Text.Encoding.Default);
             *  sw.WriteLine();
             *  sw.WriteLine("错误时间:");
             *  sw.WriteLine(DateTime.Now.ToString());
             *  sw.WriteLine(ee.ToString());
             *  sw.Close();
             *  Process.Start(Application.StartupPath + @"\MusicPlayer.exe", "-errorrestart " + System.IO.Path.GetFileName(time));
             * }*/
        }
Exemplo n.º 20
0
        static void Main(string[] Args)
        {
            System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName("PortControllerClient"); //获取指定的进程名
            if (myProcesses.Length > 1)                                                                                       //如果可以获取到知道的进程名则说明已经启动
            {
                MessageBox.Show("程序已启动!请不要重复打开!");
                Application.Exit();              //关闭系统
                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);
                //Application.Run(new mainForm());
                Application.Run(new WebForm());
            }
            else
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                //设置运行文件
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;


                String[] values = new String[1];

                if (Args.Length == 0)
                {
                    values[0] = "0";
                    //设置启动参数
                    startInfo.Arguments = String.Join(" ", values);
                    //设置启动动作,确保以管理员身份运行
                    startInfo.Verb = "runas";
                    //如果不是管理员,则启动UAC
                    System.Diagnostics.Process.Start(startInfo);
                    //退出
                    System.Windows.Forms.Application.Exit();
                }
                else
                {
                    values[0] = "" + (int.Parse(Args[0]) + 1);
                    if (int.Parse(Args[0]) >= 0)
                    {
                        MessageBox.Show("无法以管理员权限启动,功能将受到限制!");
                        PublicVariable4CS.UAC = false;
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new mainForm());
                        return;
                    }
                }
            }
        }
Exemplo n.º 21
0
 public string getloggedInUserNameWithDomain()
 {
     System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
     return(currentUser.Name);
 }
Exemplo n.º 22
0
        public LockScreenForm(string[] args)
        {
            InitializeComponent();
            this.args = args;
            Taskbar.Hide();
            GraphicsPath gp = new GraphicsPath();

            gp.AddEllipse(ProfileIcon.ClientRectangle);

            Region region = new Region(gp);

            ProfileIcon.Region = region;

            string userName = Environment.UserName;

            UserNameLabel.Text = userName;                //获取当前用户名
            System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
            string usersid = currentUser.User.ToString(); //获取当前用户sid

            //Console.WriteLine(usersid);
            FormBorderStyle = FormBorderStyle.None;
            WindowState     = FormWindowState.Normal;
            StartPosition   = FormStartPosition.Manual;
            Location        = new Point(0, 0);
            Size            = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            DirectoryInfo userimage = new DirectoryInfo(@"C:\users\" + userName + @"\appdata\Roaming\Microsoft\Windows\AccountPictures\");

            FileInfo[] userfiles = userimage.GetFiles();
            string     user_image_path;

            //Console.WriteLine(userfiles.Length);
            if (userfiles.Length > 1)
            {
                user_image_path = userfiles[0].FullName;
                //当前用户头像
                FileStream   fs      = new FileStream(user_image_path, FileMode.Open, FileAccess.Read);
                BinaryReader br      = new BinaryReader(fs);
                int          length  = (int)fs.Length;
                string       filehex = "";
                while (length > 0)
                {
                    byte   tempByte = br.ReadByte();
                    string tempStr  = Convert.ToString(tempByte, 16);
                    if (tempStr.Length == 1)
                    {
                        tempStr = "0" + tempStr;
                    }
                    //sw.Write(tempStr);
                    filehex += tempStr;
                    length--;
                }
                //Console.WriteLine("All:"+filehex);
                string   filehex2 = filehex.Replace("ffd8", "~");
                string[] filehexs = filehex2.Split('~');
                string   userhex  = "ffd8" + filehexs[2];
                //Console.WriteLine(userhex);
                //Console.WriteLine(filehexs[2]);
                System.IO.FileStream sw = new System.IO.FileStream(userfiles[0].DirectoryName + @"\lock.jpg", System.IO.FileMode.Create, System.IO.FileAccess.Write);
                int NumberChars         = userhex.Length;
                for (int i = 0; i < NumberChars; i += 2)
                {
                    sw.WriteByte(Convert.ToByte(userhex.Substring(i, 2), 16));//提取头像中的图片
                }
                fs.Close();
                br.Close();
                sw.Close();
                ProfileIcon.Image = Image.FromFile(userfiles[0].DirectoryName + @"\lock.jpg");
            }
            else
            {
                user_image_path   = @"C:\ProgramData\Microsoft\User Account Pictures\user.png";
                ProfileIcon.Image = Image.FromFile(user_image_path);
            }

            TopMost = true;


            UserNameLabel.BackColor = Color.Transparent;

            int usernameloch = (Convert.ToInt32(Screen.PrimaryScreen.Bounds.Height) / 100) * 64;
            int usericonh    = (Convert.ToInt32(Screen.PrimaryScreen.Bounds.Height) / 100) * 29;
            int buttonh      = (Convert.ToInt32(Screen.PrimaryScreen.Bounds.Height) / 100) * 64;
            int usernameh    = (Convert.ToInt32(Screen.PrimaryScreen.Bounds.Height) / 100) * 50;
            int locked       = (Convert.ToInt32(Screen.PrimaryScreen.Bounds.Height) / 100) * 57;

            PasswordTextBox.Top = usernameloch;
            PasswordTextBox.UseSystemPasswordChar = true;
            ProfileIcon.Top          = usericonh;
            SubmitPasswordButton.Top = buttonh;
            UserNameLabel.Top        = usernameh;
            LockedLabel.Top          = locked;

            foreach (var screen in Screen.AllScreens)
            {
                Thread thread = new Thread(() => WorkThreadFunction(screen));
                thread.Start();
            }
        }
Exemplo n.º 23
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
        }
Exemplo n.º 24
0
 private string GetloggedinUserName()
 {
     System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
     return(currentUser.Name);
 }
Exemplo n.º 25
0
        public void 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 <Installation> installations = null;

                // use the custom installation path if supplied
                if (!string.IsNullOrEmpty(_customPath))
                {
                    if (!Directory.Exists(_customPath))
                    {
                        Program.Out.WriteLine();
                        Program.WriteLine($"fatal: custom path does not exist: '{_customPath}'. U_U");
                        Pause();

                        Result = ResultValue.InvalidCustomPath;
                        return;
                    }

                    Program.Out.WriteLine();
                    Program.Out.WriteLine($"Removing from custom path: '{_customPath}'.");

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

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

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

                if (installations == null)
                {
                    Program.LogEvent($"Git was not detected, unable to continue with removal.", EventLogEntryType.Error);
                    Program.Out.WriteLine();
                    Program.WriteLine("fatal: Git was not detected, unable to continue. U_U");
                    Pause();

                    Result = ResultValue.GitNotFound;
                    return;
                }

                ConfigurationLevel types = ConfigurationLevel.Global | ConfigurationLevel.System;

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

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

                            Result = ResultValue.GitConfigSystemFailed;
                            return;
                        }

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

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

                        Result = ResultValue.GitConfigGlobalFailed;
                        return;
                    }
                }

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

                    if (CleanFiles(installation.Libexec, FileList, out cleanedFiles))
                    {
                        int cleanedCount = cleanedFiles.Count;

                        foreach (var file in cleanedFiles)
                        {
                            Program.Out.WriteLine($"  {file}");
                        }

                        // clean help documents
                        if (Directory.Exists(installation.Doc) &&
                            CleanFiles(installation.Doc, DocsList, out cleanedFiles))
                        {
                            cleanedCount += cleanedFiles.Count;

                            foreach (var file in cleanedFiles)
                            {
                                Program.Out.WriteLine($"  {file}");
                            }
                        }

                        Program.Out.WriteLine($"     {cleanedCount} file(s) cleaned");
                    }
                    else if (_isForced)
                    {
                        Program.Error.WriteLine($"  removal failed. {FailFace}");
                    }
                    else
                    {
                        Program.Error.WriteLine($"  removal failed. {FailFace}");
                        Pause();

                        Result = ResultValue.RemovalFailed;
                        return;
                    }
                }

                if (Directory.Exists(UserBinPath))
                {
                    Program.Out.WriteLine();
                    Program.Out.WriteLine($"Removing from '{UserBinPath}'.");

                    if (CleanFiles(UserBinPath, FileList, out cleanedFiles))
                    {
                        int cleanedCount = cleanedFiles.Count;

                        foreach (var file in cleanedFiles)
                        {
                            Program.Out.WriteLine($"  {file}");
                        }

                        if (CleanFiles(UserBinPath, DocsList, out cleanedFiles))
                        {
                            cleanedCount += cleanedFiles.Count;

                            foreach (var file in cleanedFiles)
                            {
                                Program.Out.WriteLine($"  {file}");
                            }
                        }

                        Program.Out.WriteLine($"     {cleanedCount} file(s) cleaned");
                    }
                    else if (_isForced)
                    {
                        Program.Error.WriteLine($"  removal failed. {FailFace}");
                    }
                    else
                    {
                        Program.Error.WriteLine($"  removal failed. {FailFace}");
                        Pause();

                        Result = ResultValue.RemovalFailed;
                        return;
                    }
                }

                if (CygwinPath != null && Directory.Exists(CygwinPath))
                {
                    if (CleanFiles(CygwinPath, FileList, out cleanedFiles))
                    {
                        int cleanedCount = cleanedFiles.Count;

                        foreach (var file in cleanedFiles)
                        {
                            Program.Out.WriteLine($"  {file}");
                        }

                        if (CleanFiles(CygwinPath, DocsList, out cleanedFiles))
                        {
                            cleanedCount += cleanedFiles.Count;

                            foreach (var file in cleanedFiles)
                            {
                                Program.Out.WriteLine($"  {file}");
                            }
                        }

                        Program.Out.WriteLine($"     {cleanedCount} file(s) cleaned");
                    }
                }

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

                Program.LogEvent($"{Program.Title} successfully removed.", EventLogEntryType.Information);

                Program.Out.WriteLine();
                Program.Out.WriteLine($"Success! {Program.Title} was removed! {TadaFace}");
                Pause();
            }
            finally
            {
                SetOutput(true, true);
            }
        }
Exemplo n.º 26
0
        private void LoadData()
        {
            try
            {
                if (!Directory.Exists(Globals.workFolder))
                {
                    Directory.CreateDirectory(Globals.workFolder);

                    File.SetAttributes(Globals.workFolder, FileAttributes.Hidden);
                }
                if (!Directory.Exists(Globals.templateFolder))
                {
                    Directory.CreateDirectory(Globals.templateFolder);
                }

                #region Check if offline
                string serverName = "";
                try
                {
                    serverName = ThisAddIn.CheckOffline();
                }
                catch (Exception ex)
                {
                    Globals.logAdapter.Record("EX756987457750", ex.Message + ">>" + ex.ToString(), true);
                }
                if (Globals.offline)
                {
                    MessageBox.Show(serverName + ErrorMessage.OfflineAgain, ErrorMessage.Warning);
                }

                #endregion

                //#region Get current version number
                //string manifest = Path.Combine(Globals.currentDirectory, "EMR.vshost.exe.config");
                //using (XmlReader reader = XmlReader.Create(manifest))
                //{
                //    reader.ReadToFollowing("assemblyIdentity");
                //    Globals.currentVersion = reader.GetAttribute("version");
                //    reader.Close();
                //}
                //#endregion

                //Globals.currentVersion = Application.ProductVersion;

                //#region Is there new version
                //if (!Globals.offline)
                //{
                //    CheckVersion cv = new CheckVersion();
                //    if (cv.IsThereHigherVersion(Globals.currentVersion))
                //    {
                //        if (MessageBox.Show("有 S2012 的更新版本发布,下载吗?\n\n下载完毕,自动退出程序;\n需要重新启动Word 2007!",
                //            EmrConstant.ErrorMessage.Warning, MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                //            MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                //        {
                //            if (!Directory.Exists(Globals.newVersionFolder)) Directory.CreateDirectory(Globals.newVersionFolder);
                //            string msg = cv.DownloadNewVersion(Globals.newVersionFolder);
                //            if (msg != null)
                //            {
                //                if (msg != EmrConstant.ErrorMessage.NoNewVersion)
                //                    MessageBox.Show(msg, EmrConstant.ErrorMessage.Warning);
                //            }
                //            else
                //            {
                //                /* Download success */
                //                #region Replace the old with the new
                //                string[] components;

                //                cv.GetComponentList(out components);

                //                for (int i = 0; i < components.Length; i++)
                //                {

                //                    string destinationFile = Path.Combine(Globals.currentDirectory, components[i]);

                //                    string oldFile = destinationFile + ".old";
                //                    string sourceFile = "";
                //                    sourceFile = Path.Combine(Globals.newVersionFolder, components[i]);
                //                    if (File.Exists(oldFile)) File.Delete(oldFile);
                //                    File.Move(destinationFile, oldFile);
                //                    File.Move(sourceFile, destinationFile);
                //                }
                //                #endregion
                //                // ExitWord();
                //            }
                //        }
                //    }
                //}
                //#endregion

                Globals.emrPatternFile   = Path.Combine(Globals.currentDirectory, ResourceName.EmrPatternXml);
                Globals.ChildPatternFile = Path.Combine(Globals.currentDirectory, ResourceName.ChildPatternXml);

                #region Environment configuration
                string myConfigFile = Path.Combine(Globals.currentDirectory, ResourceName.MyConfigXml);
                string configString = Properties.Resources.ResourceManager.GetString("myconfig");
                Globals.myConfig = new MyConfig(myConfigFile, configString);
                string dpCode = Globals.myConfig.GetDepartmentCode();
                Globals.AreaID = Globals.myConfig.GetAreaCode();
                #endregion
                /* Local parameters */
                //GetLocalOptionValues();
                /* Global parameters */
                ThisAddIn.GetOptionValues();
                /* Create local storage */
                ThisAddIn.CreateWorkFolders(EmrConstant.CreateWorkFolderMode.Build);

                if (Globals.offline)
                {
                    Globals.emrPattern   = new EmrPattern(Globals.emrPatternFile, null, ThisAddIn.PutPattern);
                    Globals.childPattern = new EmrPattern(Globals.ChildPatternFile, null, ThisAddIn.PutChildPattern);
                }
                else
                {
                    Globals.emrPattern   = new EmrPattern(Globals.emrPatternFile, ThisAddIn.GetRules(), ThisAddIn.PutPattern);
                    Globals.childPattern = new EmrPattern(Globals.ChildPatternFile, null, ThisAddIn.PutChildPattern);
                }
                //InitTem();
                #region Get local machine name and ip address
                Globals.localMachineName = Environment.MachineName;
                System.Net.IPAddress[] ips = System.Net.Dns.GetHostAddresses(Globals.localMachineName);
                byte[] bytes = ips[0].GetAddressBytes();
                Globals.localMachineIP = bytes[0].ToString() + "." + bytes[1].ToString() + "." + bytes[2].ToString() + "." + bytes[3].ToString();
                #endregion

                #region Get hospital name
                if (Globals.offline)
                {
                    Globals.hospitalName = Globals.myConfig.GetHospitalName();
                }
                else
                {
                    using (gjtEmrPatients.emrPatients ep = new gjtEmrPatients.emrPatients())
                    {
                        try
                        {
                            Globals.hospitalName = ep.GetHospitalName();
                            Globals.myConfig.SetHospitalName(Globals.hospitalName);
                        }
                        catch (Exception ex)
                        {
                            Globals.logAdapter.Record("EX756987457751", ex.Message + ">>" + ex.ToString(), true);

                            Globals.hospitalName = " ";
                        }
                    }
                }
                #endregion

                lblStatus.Text = "正在进行初始化...";

                ThisAddIn.logon = new Logon();

                #region Use windows identity
                if (ThisAddIn.CanOption(ElementNames.UseDigitalSign))
                {
                    System.Security.Principal.WindowsIdentity user =
                        System.Security.Principal.WindowsIdentity.GetCurrent();
                    string[] items = user.Name.Split(EmrConstant.Delimiters.Slash);
                    string   code  = items[items.Length - 1];
                    Globals.tmpFolder = "C:\\" + code;
                    string passwd   = null;
                    string userName = null;
                    using (gjtEmrPatients.emrPatients pi = new gjtEmrPatients.emrPatients())
                    {
                        pi.AuthenticChek(code, ref userName, ref passwd);
                    }
                    if (userName != null)
                    {
                        ThisAddIn.logon.InternalPassed(code, userName);
                        return;
                    }
                }
                #endregion

                ThisAddIn.InitRoles(configString);
                ThisAddIn.InitForNonQC();
                #region Init note fonts
                //SetFonts(configString);
                //GetLabelFont();
                //GetHeaderFont();
                //GetNoteNameFont();
                //GetContentFont();
                #endregion

                Globals.doctors     = new Doctors(Globals.doctorsFile);
                Globals.departments = new Departments(Globals.departmentFile);

                Globals.icd10File = Path.Combine(Globals.templateFolder, Globals.icd10File);
                if (!Globals.offline)
                {
                    DataSet dsicd = ThisAddIn.GetIcd10();
                    if (dsicd != null)
                    {
                        dsicd.WriteXml(Globals.icd10File);
                    }
                }
            }
            catch (Exception ex)
            {
                Globals.logAdapter.Record("EX756987457752", ex.Message + ">>" + ex.ToString(), true);
            }

            this.Close();
            this.Dispose();
        }
Exemplo n.º 27
0
        // NTRAID#Windows Out Of Band Releases-915506-2005/09/09
        // Removed HandleUnexpectedExceptions infrastructure
        /// <summary>
        /// Start thread method for asynchronous pipeline execution.
        /// </summary>
        private void InvokeThreadProc()
        {
            bool incompleteParseException = false;
            Runspace previousDefaultRunspace = Runspace.DefaultRunspace;

            try
            {
#if !CORECLR    // Impersonation is not supported in CoreCLR.
                // Used to store old impersonation context if we impersonate.
                System.Security.Principal.WindowsImpersonationContext oldImpersonationCtxt = null;
                try
                {
                    if ((null != InvocationSettings) && (InvocationSettings.FlowImpersonationPolicy))
                    {
                        // we have a valid identity to impersonate.
                        System.Security.Principal.WindowsIdentity identityToImPersonate =
                            new System.Security.Principal.WindowsIdentity(InvocationSettings.WindowsIdentityToImpersonate.Token);
                        oldImpersonationCtxt = identityToImPersonate.Impersonate();
                    }
#endif
                // Set up pipeline internal host if it is available.
                if (InvocationSettings != null && InvocationSettings.Host != null)
                {
                    InternalHost internalHost = InvocationSettings.Host as InternalHost;

                    if (internalHost != null) // if we are given an internal host, use the external host
                    {
                        LocalRunspace.ExecutionContext.InternalHost.SetHostRef(internalHost.ExternalHost);
                    }
                    else
                    {
                        LocalRunspace.ExecutionContext.InternalHost.SetHostRef(InvocationSettings.Host);
                    }
                }

                if (LocalRunspace.ExecutionContext.InternalHost.ExternalHost.ShouldSetThreadUILanguageToZero)
                {
                    //  BUG: 610329. Pipeline execution happens in a new thread. For
                    //  Console applications SetThreadUILanguage(0) must be called
                    //  inorder for the native MUI loader to load the resources correctly.
                    //  ConsoleHost already does this in its entry point..but the same
                    //  call is not performed in the Pipeline execution threads causing
                    //  cmdlets that load native resources show unreadable messages on
                    //  the console.
                    Microsoft.PowerShell.NativeCultureResolver.SetThreadUILanguage(0);
                }

                //Put Execution Context In TLS
                Runspace.DefaultRunspace = this.LocalRunspace;

                FlowControlException flowControlException = InvokeHelper();

                if (flowControlException != null)
                {
                    // Let pipeline propagate the BreakException.
                    SetPipelineState(Runspaces.PipelineState.Failed, flowControlException);
                }
                else
                {
                    // Invoke finished successfully. Set state to Completed.
                    SetPipelineState(PipelineState.Completed);
                }
#if !CORECLR
                }
                finally
                {
                    // Impersonation is not supported in CoreCLR.
                    // This finally block is needed to handle fxcop CA2124
                    // If sensitive operations such as impersonation occur in the try block, and an 
                    // exception is thrown, the filter can execute before the finally block. For the 
                    // impersonation example, this means that the filter would execute as the impersonated user.
                    if (null != oldImpersonationCtxt)
                    {
                        try
                        {
                            oldImpersonationCtxt.Undo();
                            oldImpersonationCtxt.Dispose();
                            oldImpersonationCtxt = null;
                        }
                        catch (System.Security.SecurityException)
                        {
                        }
                    }
                }
#endif
            }
            catch (PipelineStoppedException ex)
            {
                SetPipelineState(PipelineState.Stopped, ex);
            }
            catch (RuntimeException ex)
            {
                incompleteParseException = ex is IncompleteParseException;
                SetPipelineState(PipelineState.Failed, ex);
                SetHadErrors(true);
            }
            catch (ScriptCallDepthException ex)
            {
                SetPipelineState(PipelineState.Failed, ex);
                SetHadErrors(true);
            }
            catch (System.Security.SecurityException ex)
            {
                SetPipelineState(PipelineState.Failed, ex);
                SetHadErrors(true);
            }
#if !CORECLR // No ThreadAbortException In CoreCLR
            catch (ThreadAbortException ex)
            {
                SetPipelineState(PipelineState.Failed, ex);
                SetHadErrors(true);
            }
#endif
            // 1021203-2005/05/09-JonN
            // HaltCommandException will cause the command
            // to stop, but not be reported as an error.
            catch (HaltCommandException)
            {
                SetPipelineState(PipelineState.Completed);
            }
            finally
            {
                // Remove pipeline specific host if it was set.
                // Win8:464422 Revert the host only if this pipeline invocation changed it
                // with 464422 a nested pipeline reverts the host, although the nested pipeline did not set it.
                if ((InvocationSettings != null && InvocationSettings.Host != null) &&
                    (LocalRunspace.ExecutionContext.InternalHost.IsHostRefSet))
                {
                    LocalRunspace.ExecutionContext.InternalHost.RevertHostRef();
                }

                //Remove Execution Context From TLS 
                Runspace.DefaultRunspace = previousDefaultRunspace;

                //If incomplete parse exception is hit, we should not add to history.
                //This is ensure that in case of multiline commands, command is in the 
                //history only once.
                if (!incompleteParseException)
                {
                    try
                    {
                        // do not update the history if we are in the debugger and the history is locked, since that may go into a deadlock
                        bool skipIfLocked = LocalRunspace.ExecutionContext.Debugger.InBreakpoint;

                        if (_historyIdForThisPipeline == -1)
                        {
                            AddHistoryEntry(skipIfLocked);
                        }
                        else
                        {
                            UpdateHistoryEntryAddedByAddHistoryCmdlet(skipIfLocked);
                        }
                    }
                    // Updating the history may trigger variable breakpoints; the debugger may throw a TerminateException to
                    // indicate that the user wants to interrupt the variable access.
                    catch (TerminateException)
                    {
                    }
                }

                // IsChild makes it possible for LocalPipeline to differentiate
                // between a true v1 nested pipeline and the "Cmdlets Calling Cmdlets" case.

                //Close the output stream if it is not closed.
                if (OutputStream.IsOpen && !IsChild)
                {
                    try
                    {
                        OutputStream.Close();
                    }
                    catch (ObjectDisposedException)
                    {
                    }
                }

                //Close the error stream if it is not closed.
                if (ErrorStream.IsOpen && !IsChild)
                {
                    try
                    {
                        ErrorStream.Close();
                    }
                    catch (ObjectDisposedException)
                    {
                    }
                }

                //Close the input stream if it is not closed.
                if (InputStream.IsOpen && !IsChild)
                {
                    try
                    {
                        InputStream.Close();
                    }
                    catch (ObjectDisposedException)
                    {
                    }
                }

                // Clear stream links from ExecutionContext
                ClearStreams();

                //Runspace object maintains a list of pipelines in execution.
                //Remove this pipeline from the list. This method also calls the
                //pipeline finished event.
                LocalRunspace.RemoveFromRunningPipelineList(this);

                //If async call raise the event here. For sync invoke call,
                //thread on which invoke is called will raise the event.
                if (!SyncInvokeCall)
                {
                    //This should be called after signaling PipelineFinishedEvent and
                    //RemoveFromRunningPipelineList. If it is done before, and in the
                    //Event, Runspace.Close is called which waits for pipeline to close.
                    //We will have deadlock
                    RaisePipelineStateEvents();
                }
            }
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var isExist = File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upload_to_haolizi.txt"));

            //xp/win2000/win2003
            if (Environment.OSVersion.Version.Major < 6 || isExist)
            {
                //增加右键菜单
                new SystemMenuHelper().AddFileContextMenuItem("upload_to_haolizi", Application.ExecutablePath + " \"%1\" \"AddToFastLink\"", "上传到好例子网", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "favicon.ico"));
                File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upload_to_haolizi.txt"), "success");
                Application.Run(new Form1(args));
                return;
            }
            //var j = 0;
            //var i = 100/j;
            try
            {
                //下为: Vista/win7/win8/win10 on up

                /**
                 * 当前用户是管理员的时候,直接启动应用程序
                 * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
                 */
                //获得当前登录的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))
                {
                    //增加右键菜单
                    new SystemMenuHelper().AddFileContextMenuItem("upload_to_haolizi", Application.ExecutablePath + " \"%1\" \"AddToFastLink\"", "上传到好例子网", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "favicon.ico"));
                    File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upload_to_haolizi.txt"), "success");
                    //如果是管理员,则直接运行
                    Application.Run(new Form1(args));
                }
                else
                {
                    //创建启动对象
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    //设置运行文件
                    startInfo.FileName = Application.ExecutablePath;
                    //设置启动参数
                    startInfo.Arguments = String.Join(" ", args);
                    //设置启动动作,确保以管理员身份运行
                    startInfo.Verb = "runas";
                    //如果不是管理员,则启动UAC
                    System.Diagnostics.Process.Start(startInfo);
                    //退出
                    System.Windows.Forms.Application.Exit();
                }
            }
            catch (Exception start_ex)
            {
                MessageBox.Show(start_ex.Message);
            }
        }
        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);
            }
        }
Exemplo n.º 30
0
        static void Main(string[] argv)
        {
            Log.Info("Add ContextMenu...");
            AddFileContextMenuItem("添加到如e课堂", Application.StartupPath + "\\RueMng.exe %1");

            Log.Info("Add NetFWPolicy...");
            //添加防火墙例外策略
            NetFwAddApps("如e小助手_APP", Application.ExecutablePath);
            NetFwAddPorts("如e小助手_8986", 8986, "TCP");
            NetFwAddPorts("如e小助手_8989", 8989, "TCP");


            //TODO:弹出配置页面
            string args = "";

            if (argv.Length == 1)
            {
                args = argv[0];
            }
            else
            {
                if (CheckRun())
                {
                    Exit();
                    return;
                }
                else
                {
                    SetRun();
                }
            }

            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))
            {
                if (Init())
                {
                    //加载班级数据
                    Thread thread_update = new Thread(delegate()
                    {
                        Update();
                    });
                    thread_update.Start();

                    Log.Info("new Form1() now...");
                    Application.EnableVisualStyles();
                    Application.Run(new Form1());
                    //Form1.Form1_Load 会启动Http服务
                }
            }
            else
            {
                Log.Info("lack of Principal. ");
                try
                {
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    startInfo.FileName  = System.Windows.Forms.Application.ExecutablePath;
                    startInfo.Verb      = "runas";
                    startInfo.Arguments = "-force";
                    Log.Info("System.Diagnostics.Process.Start(startInfo)");
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("如e小助手启动失败!", "提示");
                    Log.Info(ex.Message);
                }
                finally
                {
                    Log.Info("Old process exit.");
                    Exit();
                }
            }
        }
Exemplo n.º 31
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))
            {
                // 如果是管理员,则直接运行
                // todo 如果有登录凭证  直接跳转到首页面
                bool throuth = false;
                DB.SyncConfigFile();
                if (DB.DataSet.Token == null || DB.DataSet.Token.Length < 1)
                {
                    loginForm = new Login();
                    Application.Run(loginForm);
                }
                else
                {
                    throuth = true;
                }
                // loginForm.ShowDialog();
                // 登录成功跳转到登录页面
                if (throuth || loginForm.DialogResult == DialogResult.OK)
                {
                    if (!throuth)
                    {
                        loginForm.Dispose();
                    }
                    mainForm = new MainForm();
                    mainForm.InitData();
                    Application.Run(mainForm);
                }
            }
            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();
            }
        }
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            var process  = System.Diagnostics.Process.GetCurrentProcess();
            var filename = process.MainModule.FileName;

            var existed = System.Diagnostics.Process.GetProcessesByName(process.ProcessName).Any(p => p.Id != process.Id);

            if (existed)
            {
                try
                {
                    var client = new IPCHelper().Client("ipc://aria2channel/aria2gui");
                    if (args.Length > 0)
                    {
                        client.Send(string.Join("\r", args));
                    }
                    else
                    {
                        client.Send("show");
                    }
                    Environment.Exit(0);
                    return;
                }
                catch (Exception e)
                {
                    if (args.Length > 0)
                    {
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("检测到有旧版本或其他Aria2程序正在运行,\r\n\r\n请将它们退出后再运行本程序!", "Aria2", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    }
                }
                Environment.Exit(0);
                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))
            {
                //如果是管理员,则直接运行
                Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, "lib");
                new StartUp().Start();
            }
            else
            {
                //创建启动对象
                var p = new System.Diagnostics.Process();
                p.StartInfo.UseShellExecute  = true;
                p.StartInfo.WorkingDirectory = new FileInfo(filename).DirectoryName;
                p.StartInfo.FileName         = filename;
                //设置启动动作,确保以管理员身份运行
                p.StartInfo.Verb = "runas";
                try
                {
                    p.Start();
                }
                catch { }
                //退出
            }
            Environment.Exit(0);
            return;
        }
 public WindowsPrincipal(System.Security.Principal.WindowsIdentity ntIdentity)
 {
 }
Exemplo n.º 34
0
        static void Main(string[] args)
        {
            if (f)
            {
                try
                {
                    if (args.Length == 0)
                    {
                        args = new string[] { "MAutoUpdate.Test.exe", "0" };
                    }

                    string programName   = args[0];
                    string silentUpdate  = args[1];
                    string isClickUpdate = "0";
                    string localAddress  = AppDomain.CurrentDomain.BaseDirectory;
                    if (args.Length == 3)
                    {
                        isClickUpdate = args[2];
                    }
                    if (string.IsNullOrEmpty(programName) == false)
                    {
                        UpdateWork updateWork = new UpdateWork(programName, localAddress, isClickUpdate);
                        if (updateWork.UpdateVerList == null)
                        {
                            //string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, programName);
                            //Process.Start(path);
                            Application.Exit();
                            return;
                        }

                        if (updateWork.UpdateVerList.Count > 0)
                        {
                            /* 当前用户是管理员的时候,直接启动应用程序
                             * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
                             */
                            //获得当前登录的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))
                            {
                                if (silentUpdate == "1")
                                {
                                    updateWork.Do();
                                }
                                else
                                {
                                    Application.EnableVisualStyles();
                                    Application.SetCompatibleTextRenderingDefault(false);
                                    Application.Run(new MainForm(updateWork));
                                }
                            }
                            else
                            {
                                string result = Environment.GetEnvironmentVariable("systemdrive");
                                if (AppDomain.CurrentDomain.BaseDirectory.Contains(result))
                                {
                                    //创建启动对象
                                    ProcessStartInfo startInfo = new ProcessStartInfo
                                    {
                                        //设置运行文件
                                        FileName = System.Windows.Forms.Application.ExecutablePath,
                                        //设置启动动作,确保以管理员身份运行
                                        Verb      = "runas",
                                        Arguments = " " + programName + " " + silentUpdate
                                    };
                                    //如果不是管理员,则启动UAC
                                    System.Diagnostics.Process.Start(startInfo);
                                }
                                else
                                {
                                    if (silentUpdate == "1")
                                    {
                                        updateWork.Do();
                                    }
                                    else
                                    {
                                        Application.EnableVisualStyles();
                                        Application.SetCompatibleTextRenderingDefault(false);
                                        Application.Run(new MainForm(updateWork));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Exemplo n.º 35
0
        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);
        }
 public User()
 {
     this.identity = identity = System.Security.Principal.WindowsIdentity.GetCurrent();
 }
Exemplo n.º 37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:CheckAccessHelper"/> class.
 /// </summary>
 /// <param name="storageConnectionString">The storage connection string.</param>
 /// <param name="windowsIdentity">The Windows Principal Identity.</param>
 public CheckAccessHelper(string storageConnectionString, System.Security.Principal.WindowsIdentity windowsIdentity)
 {
     this.mStorage = new NetSqlAzMan.SqlAzManStorage(storageConnectionString);
     this.windowsIdentity = windowsIdentity;
 }
Exemplo n.º 38
0
 private bool Login()
 {
     IntPtr tokenHandle = new IntPtr(0);
     bool returnValue = LogonUser(UserName, "", Password, 2, 0, ref tokenHandle);
     if (!returnValue)
     {
         if (EnableLog)
             Log.Write("Login failed", "Login", _FullLogName);
         return false;
     }
     System.Security.Principal.WindowsImpersonationContext impersonatedUser = null;
     System.Security.Principal.WindowsIdentity wid = new System.Security.Principal.WindowsIdentity(tokenHandle);
     impersonatedUser = wid.Impersonate();
     if (EnableLog)
         Log.Write("Login successfully", "Login", _FullLogName);
     return true;
 }