public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); //Create a windowsidentity object representing the current user WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); //Create a windowsprincipal object representing the current user WindowsPrincipal currentprincipal = new WindowsPrincipal(currentIdentity); //Set the security policy context to windows security System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); //hide the subtract and multiply button if user is not and Administrator if(!currentprincipal.IsInRole(WindowsBuiltInRole.Administrator)) { subtractButton.Visible = false; multiplyButton.Visible = false; } //hide the add button if user is not in Users group if(!currentprincipal.IsInRole(WindowsBuiltInRole.User)) { addButton.Visible = false; } //Hide the Divide button if the user is not named CPhilips if(!(currentIdentity.Name.ToLower() == Environment.MachineName.ToLower() + @"\rafa&pri")) { divideButton.Visible = false; } }
/// <summary> /// 检查是否是管理员身份 /// </summary> private void CheckAdministrator() { var wi = WindowsIdentity.GetCurrent(); var wp = new WindowsPrincipal(wi); bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator); if (!runAsAdmin) { // It is not possible to launch a ClickOnce app as administrator directly, // so instead we launch the app as administrator in a new process. var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase); // The following properties run the new process as administrator processInfo.UseShellExecute = true; processInfo.Verb = "runas"; // Start the new process try { Process.Start(processInfo); } catch { MessageBox.Show("没有管理员权限\n请右键该程序之后点击“以管理员权限运行”"); } // Shut down the current process Environment.Exit(0); } }
private static bool IsRunAsAdministrator() { var wi = WindowsIdentity.GetCurrent(); var wp = new WindowsPrincipal(wi); return wp.IsInRole(WindowsBuiltInRole.Administrator); }
/// <summary>Checks if the current process has the necessary permissions to a folder. This allows "custom" elevation of limited users -- allowing them control over normally restricted folders.</summary> /// <param name="folder">The full path to the folder to check.</param> /// <returns>True if the user has permission, false if not.</returns> static bool HaveFolderPermissions(string folder) { try { const FileSystemRights RightsNeeded = FileSystemRights.Traverse | FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.ListDirectory | FileSystemRights.CreateFiles | FileSystemRights.CreateDirectories | FileSystemRights.Modify; //Read, ExecuteFile, Write, Delete FileSystemSecurity security = Directory.GetAccessControl(folder); var rules = security.GetAccessRules(true, true, typeof(NTAccount)); var currentuser = new WindowsPrincipal(WindowsIdentity.GetCurrent()); FileSystemRights RightsHave = 0; FileSystemRights RightsDontHave = 0; foreach (FileSystemAccessRule rule in rules) { // First check to see if the current user is even in the role, if not, skip if (rule.IdentityReference.Value.StartsWith("S-1-")) { var sid = new SecurityIdentifier(rule.IdentityReference.Value); if (!currentuser.IsInRole(sid)) continue; } else { if (!currentuser.IsInRole(rule.IdentityReference.Value)) continue; } if (rule.AccessControlType == AccessControlType.Deny) RightsDontHave |= rule.FileSystemRights; else RightsHave |= rule.FileSystemRights; } // exclude "RightsDontHave" RightsHave &= ~RightsDontHave; //Note: We're "XOR"ing with RightsNeeded to eliminate permissions that // "RightsHave" and "RightsNeeded" have in common. Then we're // ANDing that result with RightsNeeded to get permissions in // "RightsNeeded" that are missing from "RightsHave". The result // should be 0 if the user has RightsNeeded over the folder (even // if "RightsHave" has flags that aren't present in the // "RightsNeeded" -- which can happen because "RightsNeeded" isn't // *every* possible flag). // Check if the user has full control over the folder. return ((RightsHave ^ RightsNeeded) & RightsNeeded) == 0; } catch { return false; } }
public static bool IsUserAdministrator() { bool isAdmin; WindowsIdentity user = null; try { //get the currently logged in user user = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(user); isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); } catch (UnauthorizedAccessException) { isAdmin = false; } catch (Exception) { isAdmin = false; } finally { if (user != null) user.Dispose(); } return isAdmin; }
public void Execute() { PrintHeader(); var id = WindowsIdentity.GetCurrent(); Console.WriteLine("Identity Id: " + id.Name); var account = new NTAccount(id.Name); var sid = account.Translate(typeof(SecurityIdentifier)); Console.WriteLine("SecurityIdentifier (sid): " + sid.Value); foreach (var group in id.Groups.Translate(typeof(NTAccount))) Console.WriteLine("InGroup: " + group); var principal = new WindowsPrincipal(id); var localAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); Console.WriteLine("IsInRole(localAdmin): " + principal.IsInRole(localAdmins)); var domainAdmins = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, id.User.AccountDomainSid); Console.WriteLine("IsInRole(domainAdmin): " + principal.IsInRole(domainAdmins)); Console.WriteLine(); // be aware for desktop/local accounts User Account Control (UAC from Vista) strips user of admin rights, // unless the process was run elevated "as Admin". }
private static bool IsRunningAsRoot() { if (MonoHelper.RunningOnMono) { return MonoHelper.RunningAsRoot; } try { // Этот код также работает под Mono/Linux, но есть сомнения, что под любой платформой var user = WindowsIdentity.GetCurrent(); if (user != null) { var principal = new WindowsPrincipal(user); return principal.IsInRole(WindowsBuiltInRole.Administrator); } } catch (Exception) { } return false; }
public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity); System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); if (!currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) { subtractButton.Visible = false; multiplyButton.Visible = false; } if (!currentPrincipal.IsInRole(WindowsBuiltInRole.User)) addButton.Visible = false; if (!(currentIdentity.Name.ToLower() == System.Environment.MachineName.ToLower() + @"\donal")) divideButton.Visible = false; }
public static bool IsInRole(string role) { var windowsIdentity = WindowsIdentity.GetCurrent(); if (windowsIdentity == null) return false; var principal = new WindowsPrincipal(windowsIdentity); return principal.IsInRole(role); }
private bool HaveAdminRights() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); }
ConsoleHostRawUserInterface(ConsoleHostUserInterface mshConsole) : base() { defaultForeground = ForegroundColor; defaultBackground = BackgroundColor; parent = mshConsole; // cacheKeyEvent is a value type and initialized automatically // add "Administrator: " prefix into the window title, but don't wait for it to finish // (we may load resources which can take some time) Task.Run(() => { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { string prefix = ConsoleHostRawUserInterfaceStrings.WindowTitleElevatedPrefix; // check using Regex if the window already has Administrator: prefix // (i.e. from the parent console process) string titlePattern = ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate; titlePattern = Regex.Escape(titlePattern) .Replace(@"\{1}", ".*") .Replace(@"\{0}", Regex.Escape(prefix)); if (!Regex.IsMatch(this.WindowTitle, titlePattern)) { this.WindowTitle = StringUtil.Format(ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate, prefix, this.WindowTitle); } } }); }
public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, System.ServiceModel.Channels.Message message) { WindowsPrincipal currentlyPrincipal = null; if (ServiceSecurityContext.Current != null && ServiceSecurityContext.Current.WindowsIdentity != null) { currentlyPrincipal = new WindowsPrincipal(ServiceSecurityContext.Current.WindowsIdentity); } string action = OperationContext.Current.IncomingMessageHeaders.Action; if (!string.IsNullOrEmpty(action)) { var actions = action.Split('/'); string methodName = actions[actions.Length - 1]; string serviceName = actions[actions.Length - 2]; if (!this.authorizationCheckStrategy.IsAuthorized(serviceName, methodName, currentlyPrincipal)) { var logMessage = new StringBuilder(); var endpointMsg = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; logMessage.Append("Access Denied"); logMessage.AppendFormat("Service: {0}, Method:{1}", serviceName, methodName).AppendLine(); logMessage.AppendFormat("Client IP: {0}:{1}", endpointMsg.Address, endpointMsg.Port).AppendLine(); logMessage.AppendFormat("Currently Principal: {0}", currentlyPrincipal.Identity.Name).AppendLine(); var accessDeniedException = new SecurityAccessDeniedException(); _logger.LogWarning(logMessage.ToString()); throw accessDeniedException; } } var ticket = Guid.NewGuid(); _logger.Debug(string.Format("{0} BeforeInvoke {1}, Method {2}", DateTime.Now, ticket, message.Headers.Action)); return ticket; }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); bool isAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent()) .IsInRole(WindowsBuiltInRole.Administrator) ? true : false; if (!isAdmin) { MessageBox.Show("You need admin privileges to run this application,\n" + "this is required to start/stop the service"); Application.Current.Shutdown(-1); } bool servicePresent = ServiceController.GetServices().Any(service => { bool result = service.ServiceName.Contains("JarvisService"); service.Close(); return result; }); if(!servicePresent) { MessageBox.Show("Jarvis service was not correctly installed on your system, please run setup again."); Shutdown(-1); } }
static void adminCheck() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { const string message = "Running this program as Administrator causes problems with steam..."; const string caption = "Steam Launcher"; var result = MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Information); if (result == DialogResult.OK) { Environment.Exit(0); } else { Environment.Exit(0); } } else { start(); } }
public void calculateUserGroupBasedOnWindowsIdentity() { Action<UserGroup> testMappings = (expectedUserGroup)=> { var identity = WindowsIdentity.GetCurrent(); Assert.NotNull(identity); var principal = new WindowsPrincipal(identity); Assert.NotNull(principal); Assert.AreEqual(identity.AuthenticationType, "NTLM"); var defaultUserGroup = windowsAuthentication.calculateUserGroupBasedOnWindowsIdentity(identity); Assert.AreEqual(expectedUserGroup, defaultUserGroup); }; testMappings(UserGroup.None); //create a copy of the current values before changing them in the test below var tmConfig_ReaderGroup = tmConfig.WindowsAuthentication.ReaderGroup; var tmConfig_EditorGroup = tmConfig.WindowsAuthentication.EditorGroup; var tmConfig_AdminGroup = tmConfig.WindowsAuthentication.AdminGroup; tmConfig.WindowsAuthentication.ReaderGroup = "Users"; testMappings(UserGroup.Reader); tmConfig.WindowsAuthentication.ReaderGroup = tmConfig_ReaderGroup; tmConfig.WindowsAuthentication.EditorGroup = "Users"; testMappings(UserGroup.Editor); tmConfig.WindowsAuthentication.EditorGroup = tmConfig_EditorGroup; tmConfig.WindowsAuthentication.AdminGroup = "Users"; testMappings(UserGroup.Admin); tmConfig.WindowsAuthentication.AdminGroup = tmConfig_AdminGroup; }
public CounterControl() { // Check user is Administrator and has granted UAC elevation permission to run this app var userIdent = WindowsIdentity.GetCurrent(); var userPrincipal = new WindowsPrincipal(userIdent); IsRunningAsAdministrator = userPrincipal.IsInRole(WindowsBuiltInRole.Administrator); }
/// <summary> /// Returns whether the application runs with admin rights or not. /// </summary> public static bool CheckAdmin() { var id = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(id); return principal.IsInRole(WindowsBuiltInRole.Administrator); }
public bool IsAuthorized(string service, string method, WindowsPrincipal principal) { if (WebOperationContext.Current == null) { return true; } else { var methodInfo = CurrentEndpoint.Contract.ContractType.GetMethod(method); var attrs = methodInfo.GetCustomAttributes(typeof(TokenRequiredAttribute), false); if (attrs == null || attrs.Length == 0) { return true; } else { string token = WebOperationContext.Current.IncomingRequest.Headers.Get("Authorization-OAuth2"); if (string.IsNullOrEmpty(token)) { return false; } else { return oauth2.VerifyAccessToken(token); } } } }
private static bool isAdministrator() { SimpleLogger.Instance().WriteLine("Checking privileges..."); WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); }
public void Interface () { WindowsPrincipal wp = new WindowsPrincipal (WindowsIdentity.GetAnonymous ()); IPrincipal p = (wp as IPrincipal); AssertNotNull ("IPrincipal", p); }
/// <summary> /// Elevate application rights to Administrator. This will cause a UAC box to pop up. /// </summary> /// <param name="createWindow">Run the elevated process in a new window.</param> /// <returns>True or false depending on succesful elevation.</returns> public bool ElevateRights(bool createWindow) { try { WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); if (isAdmin) { return true; } else { // basically: give this application admin rights ProcessStartInfo psiElev = new ProcessStartInfo(); psiElev.Verb = "runas"; psiElev.UserName = null; psiElev.Password = null; psiElev.FileName = Assembly.GetExecutingAssembly().Location; psiElev.CreateNoWindow = createWindow; Process pElev = Process.Start(psiElev); return true; } } catch (Exception) { return false; } }
private void CheckUAC() { WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); if (!pricipal.IsInRole(WindowsBuiltInRole.Administrator)) { buttonInstallFiles.Enabled = false; buttonUninstallFiles.Enabled = false; buttonInstallFolders.Enabled = false; buttonUninstallFolders.Enabled = false; MessageBox.Show("UAC is preventing this action to complete. Restarting as administrator."); ProcessStartInfo processInfo = new ProcessStartInfo(); processInfo.Verb = "runas"; processInfo.FileName = Application.ExecutablePath; try { Process.Start(processInfo); Application.Exit(); } catch (Win32Exception) { //Do nothing. Probably the user canceled the UAC window } } }
private void Apply_Click(object sender, RoutedEventArgs e) { Config.IconSize = (int)Math.Round(slIconSize.Value); Config.GridMaximumCols = (int)Math.Round(slGridCols.Value); Config.GridMaximumRows = (int)Math.Round(slGridRows.Value); Config.HideDelay = (int)Math.Round(slHideDelay.Value); Config.PopupDelay = (int)Math.Round(slPopupDelay.Value); Config.HoverEnabled = (int)Math.Round(slHoverEnabled.Value) != 0; Config.HoverTextEnabled = (int)Math.Round(slHoverTextEnabled.Value) != 0; Config.HoverHideDelay = (int)Math.Round(slHoverHideDelay.Value); Config.HoverMoveDealy = (int)Math.Round(slHoverMoveDelay.Value); Config.HoverPopupDelay = (int)Math.Round(slHoverPopupDelay.Value); var id = WindowsIdentity.GetCurrent(); var wPrincipal = new WindowsPrincipal(id); if (wPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) { Config.Save(); } else { var myProcess = new ProcessStartInfo(System.Windows.Forms.Application.ExecutablePath); myProcess.Verb = "runas"; myProcess.Arguments = string.Format("-p {0} {1} {2} {3} {4} {5} {6} {7} {8} {9}", Config.IconSize, Config.GridMaximumCols, Config.GridMaximumRows, Config.HideDelay, Config.PopupDelay, Config.HoverEnabled, Config.HoverHideDelay, Config.HoverMoveDealy, Config.HoverPopupDelay, Config.HoverTextEnabled); Process.Start(myProcess); Close(); } }
static void Main() { WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator); if (hasAdministrativeRight == false) { ProcessStartInfo processInfo = new ProcessStartInfo(); //создаем новый процесс processInfo.Verb = "runas"; //в данном случае указываем, что процесс должен быть запущен с правами администратора processInfo.FileName = Application.ExecutablePath; //указываем исполняемый файл (программу) для запуска try { Process.Start(processInfo); //пытаемся запустить процесс } catch (Win32Exception) { //Ничего не делаем, потому что пользователь, возможно, нажал кнопку "Нет" в ответ на вопрос о запуске программы в окне предупреждения UAC (для Windows 7) } Application.Exit(); //закрываем текущую копию программы (в любом случае, даже если пользователь отменил запуск с правами администратора в окне UAC) } else //имеем права администратора, значит, стартуем { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } }
public int Set(int index) { Process newProcess = ProcessesList[index]; if (newProcess.StartInfo.UseShellExecute) { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); canRun = principal.IsInRole(WindowsBuiltInRole.Administrator); } if (canRun) { if (SelectedProcess == null || newProcess.MainWindowHandle != SelectedProcess.MainWindowHandle) { if (SelectedProcess != null) SelectedProcess.Exited -= new EventHandler(ExitCallback); if (SelectedProcess != null && newProcess.Id != SelectedProcess.Id) ShowWindow(newProcess.MainWindowHandle); SelectedProcess = newProcess; SelectedProcess.EnableRaisingEvents = true; SelectedProcess.Exited += new EventHandler(ExitCallback); } return SelectedProcess.Id; } WindowClosedEvent(true, "Run as Administrator!"); return -1; }
public static bool CheckUserRights(string userLogin, string rightName) { string programName = WebConfigurationManager.AppSettings["progName"]; bool flag = false; SqlParameter pProgramName = new SqlParameter() { ParameterName = "program_name", Value = programName, DbType = DbType.AnsiString }; SqlParameter pRightName = new SqlParameter() { ParameterName = "sys_name", Value = rightName, DbType = DbType.AnsiString }; DataTable dt = new DataTable(); dt = ExecuteQueryStoredProcedure(sp, "getUserGroupSid", pProgramName, pRightName); if (dt.Rows.Count > 0) { DataRow dr = dt.Rows[0]; string sid = dr["sid"].ToString(); try { WindowsIdentity wi = new WindowsIdentity(userLogin); WindowsPrincipal wp = new WindowsPrincipal(wi); SecurityIdentifier grpSid = new SecurityIdentifier(sid); flag = wp.IsInRole(grpSid); } catch (Exception ex) { flag = false; } } return flag; }
private void mainForm_Load(object sender, EventArgs e) { WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator); if (!hasAdministrativeRight) { // relaunch the application with admin rights string fileName = Assembly.GetExecutingAssembly().Location; ProcessStartInfo processInfo = new ProcessStartInfo(); processInfo.Verb = "runas"; processInfo.FileName = fileName; try { Process.Start(processInfo); } catch (Win32Exception) { this.Close(); } return; } this.BringToFront(); updateStats(); }
public static bool IsAdministrator() { var winId = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(winId); return principal.IsInRole(WindowsBuiltInRole.Administrator); }
private static bool IsAdmin() { WindowsIdentity id = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(id); bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); return isAdmin; }
/// <summary> /// This routine should be called automatically by the MSI during setup, but it can also be called using: /// "installutil.exe Archiver.dll" /// </summary> /// <param name="savedState">State dictionary passed in by the installer code</param> public override void Install (IDictionary savedState) { #region Check to make sure we're in an Administrator role WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent()); if (wp.IsInRole(WindowsBuiltInRole.Administrator) == false) { MessageBox.Show("You must be an Administrator to install Rtp or run it for the first time.", "Administrator Privileges Required", MessageBoxButtons.OK, MessageBoxIcon.Stop); Application.Exit(); } #endregion #region Uninstall in case we weren't uninstalled cleanly before IDictionary state = new Hashtable(); Uninstall(state); if (state.Count != 0) Commit(state); state = null; #endregion #region Call base.Install base.Install(savedState); #endregion #region Install the Event Logs ArchiveServiceEventLog.Install(); #endregion #region Create PerfCounters PCInstaller.Install(); #endregion #region Save the fact that we're installed to the registry Installed = true; #endregion }
protected override bool IsAuthorized(HttpActionContext actionContext) { System.Security.Principal.WindowsPrincipal user = actionContext.RequestContext.Principal as System.Security.Principal.WindowsPrincipal; if (user.IsInRole(WindowsBuiltInRole.Administrator)) { return(true); } if (user.IsInRole(WindowsBuiltInRole.PowerUser)) { return(true); } return(base.IsAuthorized(actionContext)); }
/// Handles error by accepting the error message /// Displays the page on which the error occured public static void WriteError(string errorMessage) { myUser = new WindowsPrincipal(WindowsIdentity.GetCurrent()); string path = Salaries.Configuration.CryptographyClass.getSettingsWithoutDecode(ERROR_FOLDER); //sa am grija cum fac cu calea - pentru ca trebuie sa mearga si din directorul radacina si din alte foldere InterfataSalarii, Administrare //daca vreau sa mearga si in celelalte proiecte - trebui sa fac proiect separat path += "\\" + DateTime.Today.ToString("dd-MM-yy") + ".txt"; if (!File.Exists(path)) { File.Create(path).Close(); } using (StreamWriter w = File.AppendText(path)) { w.WriteLine(); string err = errorMessage; w.Write("{0} - {1} - {2}", DateTime.Now.ToString("dd.MM.yyyy HH:mm"), myUser.Identity.Name, err); w.Flush(); w.Close(); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); /** * 当前用户是管理员的时候,直接启动应用程序 * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行 */ //获得当前登录的Windows用户标示 System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); //判断当前登录用户是否为管理员 if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) { //如果是管理员,则直接运行 Application.Run(new FrmMain()); } 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(); } }
static void Main(string[] args) { System.Security.Principal.WindowsIdentity wid = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal printcipal = new System.Security.Principal.WindowsPrincipal(wid); Console.WriteLine(printcipal.Identity.AuthenticationType); using (Impersonator i = new Impersonator("andy2", ".", "andy2")) { Console.WriteLine(WindowsIdentity.GetCurrent().Name); System.Security.Principal.WindowsIdentity wid2 = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal printcipal2 = new System.Security.Principal.WindowsPrincipal(wid2); Console.WriteLine(printcipal2.Identity.AuthenticationType); bool isAdmin = (printcipal2.IsInRole(@"BUILTIN\Administrators")); Console.WriteLine(isAdmin); } //WindowsIdentity.Impersonate(IntPtr.Zero); //Console.WriteLine(WindowsIdentity.GetCurrent().Name); //System.Security.Principal.WindowsIdentity wid = System.Security.Principal.WindowsIdentity.GetCurrent(); // System.Security.Principal.WindowsPrincipal printcipal = new System.Security.Principal.WindowsPrincipal(wid); // bool isAdmin = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)); // Console.WriteLine(isAdmin); }
//get user from ldap authentification public string GetUserNameFromLdap() { //PrincipalContext ctx = new PrincipalContext(ContextType.Domain); //UserPrincipal user = UserPrincipal.Current; //string displayName = user.DisplayName; string Name = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name; string igo = System.Environment.UserName; string qlf = Environment.GetEnvironmentVariable("USERNAME"); string Taric = System.Security.Principal.WindowsIdentity.GetCurrent().Name; PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // find current user UserPrincipal user = UserPrincipal.Current; if (user != null) { string loginName = user.SamAccountName; // or whatever you mean by "login name" } return(Name); }
public static string getAccount() { string name = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name; string domain = ""; if (name.StartsWith("KMHK")) { domain = "kmhk.local"; } else if (name.StartsWith("KMAS")) { domain = "kmas.local"; } string str = name.Substring(name.IndexOf('\\') + 1); DirectoryEntry searchRoot = new DirectoryEntry("LDAP://" + domain); SearchResult searchResult = new DirectorySearcher(searchRoot) { Filter = "(&(objectClass=user)(sAMAccountName=" + str + "))" }.FindOne(); DirectoryEntry directoryEntry = searchResult.GetDirectoryEntry(); return(directoryEntry.Properties["sAMAccountName"].Value.ToString()); }
private void Page_Load(object sender, System.EventArgs e) { CreateJavascriptVar(); lunaID = this.GetCurrentMonth(); Salaries.Business.Luni l = new Salaries.Business.Luni(this.GetAngajator(), lunaID); this.dataStartLunaActiva = l.Data; this.dataEndLunaActiva = dataStartLunaActiva.AddMonths(1).AddDays(-1); angajatorID = this.GetAngajator(); Salaries.Business.Luni salLuni = new Salaries.Business.Luni(angajatorID); lunaActiva = salLuni.GetLunaActiva().LunaId; /*if (ButtonImport.Value.Equals("Import pontaj")) * tdTemplate.InnerHtml = "<a target=_blank href='Templates\\TemplatePontaj.xls'>template pontaj</a>"; * else * tdTemplate.InnerHtml = "<a target=_blank href='Templates\\TemplateSituatieLunara.xls'>template situatie lunara</a>";*/ actionImportDelegatiiLuna = ((System.Web.UI.HtmlControls.HtmlInputHidden)Page.FindControl("ActionImportDelegatiiLunaValue")).Value; Salaries.Business.NomenclatorTipAbsente tipAbs = new Salaries.Business.NomenclatorTipAbsente(); sirTipuri = tipAbs.GetDetaliiTipuriAbsente(); //user-ul loginat user = new WindowsPrincipal(WindowsIdentity.GetCurrent()); if (!IsPostBack) { lblMesajImport.Text = ""; } else { } System.IO.StreamWriter swRez = new System.IO.StreamWriter(Server.MapPath("Templates\\RezultateImport.txt"), false); swRez.WriteLine(); swRez.Close(); GetIdTipAbsente(); HandleActions(); }
public static bool QP() { /** * 当前用户是管理员的时候,直接启动应用程序 * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行 */ //获得当前登录的Windows用户标示 System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); //创建Windows用户主题 Application.EnableVisualStyles(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); //判断当前登录用户是否为管理员 if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) { //如果是管理员,则直接运行 Application.EnableVisualStyles(); return(true); } else { //创建启动对象 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); //设置运行文件 startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; //设置启动参数 startInfo.Arguments = String.Join("", new string[0]); //设置启动动作,确保以管理员身份运行 startInfo.Verb = "runas"; //如果不是管理员,则启动UAC System.Diagnostics.Process.Start(startInfo); //退出 System.Windows.Forms.Application.Exit(); } return(false); }
private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { //se obtine tipul de autentificare la aplicatie string authentication = Salaries.Configuration.CryptographyClass.getSettingsWithoutDecode("authentication"); //virtual path string path = Page.Request.FilePath; char separator = '/'; string [] pathArr = path.Split(separator); int nr = pathArr.Length; //autentificare de tip windows if (authentication == "1") { //user-ul loginat user = new WindowsPrincipal(WindowsIdentity.GetCurrent()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], user)) { ErrHandler.MyErrHandler.WriteError("EditAngajat_Recrutori.aspx - autentificare windows fara drepturi - " + user.Identity.Name); Server.Transfer("../Unauthorized.aspx"); } } //autenticiare cu user si parola else { try { string nume = Session["Nume"].ToString(); string parola = Session["Parola"].ToString(); int angajatorId = int.Parse(Session["AngajatorId"].ToString()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], nume, parola, angajatorId)) { ErrHandler.MyErrHandler.WriteError("EditAngajat_Recrutori.aspx - autentificare user name fara drepturi - " + nume + ", " + angajatorId); Server.Transfer("../Unauthorized.aspx"); } } catch (Exception exc) { Response.Redirect("../index.aspx"); } } } idAngajat = Convert.ToInt32(Request.QueryString["id"]); string myCmd = Request.QueryString["cmd"]; mainTable.Attributes.Add("width", "100%"); mainTable.Attributes.Add("height", "100%"); mainTable.Attributes.Add("border", "0"); mainTable.Attributes.Add("cellpadding", "0"); mainTable.Attributes.Add("cellspacing", "0"); TableRow myRow; TableRow mySecondRow; TableCell myCell; // al doilea table.. care va contine 2 linii - taskuri si control centru Table secondTable = new Table(); secondTable.Attributes.Add("width", "100%"); secondTable.Attributes.Add("height", "100%"); secondTable.Attributes.Add("border", "0"); secondTable.Attributes.Add("cellpadding", "0"); secondTable.Attributes.Add("cellspacing", "0"); try { objAngajat = new Salaries.Business.Angajat(); objAngajat.AngajatId = idAngajat; objAngajat.LoadAngajat(); } catch (Exception ex) { Response.Write("Error loading employee data: <br>"); Response.Write(ex.Message); Response.End(); } // se adauga partea stanga myRow = new TableRow(); myCell = new TableCell(); myCell = new TableCell(); myCell.RowSpan = 3; myCell.Width = new Unit(310, UnitType.Pixel); myEditAngajatLeft = (EditAngajatLeft)LoadControl("../EditAngajatLeft.ascx"); myEditAngajatLeft.XmlSursa = "../Navigare/EditAngajat_LeftNavigation_Recrutori.xml"; myEditAngajatLeft.AngajatID = idAngajat; myEditAngajatLeft.objAngajat = objAngajat; myCell.Attributes.Add("valign", "top"); myCell.Controls.Add(myEditAngajatLeft); myRow.Cells.Add(myCell); // se adauga partea dreapta mySecondRow = new TableRow(); myCell = new TableCell(); EditAngajatUp myEditAngajatUp = (EditAngajatUp)LoadControl("../EditAngajatUp.ascx"); myCell.Attributes.Add("valign", "top"); myCell.Attributes.Add("height", "10"); myEditAngajatUp.AngajatID = idAngajat; myCell.Controls.Add(myEditAngajatUp); mySecondRow.Cells.Add(myCell); secondTable.Rows.Add(mySecondRow); // se adauga a doua linie din tabel.. ce contine controlul mySecondRow = new TableRow(); myCell = new TableCell(); myCell.Attributes.Add("valign", "top"); myCell.Attributes.Add("height", "100%"); myCell.Attributes.Add("align", "center"); Session["Recrutori"] = "Recrutori"; switch (myCmd) { case "date_personale": case null: EditAngajatDatePersonale myEditControl = (EditAngajatDatePersonale)LoadControl("../EditTasks/EditAngajatDatePersonale.ascx"); myEditControl.objAngajat = objAngajat; myCell.Controls.Add(myEditControl); break; // // Artiom Modificat //case "date_angajare": // // var control = LoadControl("EditTasks/EditAngajatDateAngajare.ascx"); // // EditAngajatDateAngajare myEditDateAngajatControl = (EditAngajatDateAngajare) control; // EditAngajatDateAngajare myEditDateAngajatControl = (EditAngajatDateAngajare)LoadControl("../EditTasks/EditAngajatDateAngajare.ascx"); // myEditDateAngajatControl.objAngajat = objAngajat; // myCell.Controls.Add(myEditDateAngajatControl); // break; case "istoric_carte_identitate": EditTasks.IstoricCartiIdentitate myIstoricCartiIdentitate = (EditTasks.IstoricCartiIdentitate)LoadControl("../EditTasks/IstoricCartiIdentitate.ascx"); myIstoricCartiIdentitate.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricCartiIdentitate); break; case "istoric_departamente": IstoricDepartamente myIstoricDepartamenteControl = (IstoricDepartamente)LoadControl("../EditTasks/IstoricDepartamente.ascx"); myIstoricDepartamenteControl.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricDepartamenteControl); break; case "fisa_postului": fisa_postului myfisapostului = (fisa_postului)LoadControl("../Comunicari/fisa_postului.ascx"); myfisapostului.objAngajat = objAngajat; myCell.Controls.Add(myfisapostului); break; case "change_poza": ChangePoza myChangePoza = (ChangePoza)LoadControl("../EditTasks/ChangePoza.ascx"); myChangePoza.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myChangePoza); break; case "istoric_functii": IstoricFunctii myIstoricFunctii = (IstoricFunctii)LoadControl("../EditTasks/IstoricFunctii.ascx"); myIstoricFunctii.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricFunctii); break; case "istoric_training": IstoricTraininguri myIstoricTraininguri = (IstoricTraininguri)LoadControl("../EditTasks/IstoricTraininguri.ascx"); myIstoricTraininguri.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricTraininguri); break; case "checkupuri": CheckupuriAngajat myCheckup = (CheckupuriAngajat)LoadControl("../EditTasks/CheckupuriAngajat.ascx"); myCheckup.AngajatID = objAngajat.AngajatId; myCheckup.SefID = objAngajat.SefId; myCell.Controls.Add(myCheckup); break; case "evaluari_psihologice": EvaluariPsihologiceAngajat myEval = (EvaluariPsihologiceAngajat)LoadControl("../EditTasks/EvaluariPsihologiceAngajat.ascx"); myEval.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myEval); break; case "istoric_referinte": ReferinteAngajat myReferinte = (ReferinteAngajat)LoadControl("../EditTasks/ReferinteAngajat.ascx"); myReferinte.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myReferinte); break; default: myCell.Text = "<img src=\"images/1x1.gif\" width=\"100%\" height=\"100%\">"; break; } mySecondRow.Cells.Add(myCell); secondTable.Rows.Add(mySecondRow); // se adauga al doilea tabel la primul myCell = new TableCell(); myCell.Controls.Add(secondTable); myCell.Attributes.Add("height", "100%"); myCell.Attributes.Add("width", "100%"); myRow.Cells.Add(myCell); mainTable.Rows.Add(myRow); }
private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { //se obtine tipul de autentificare la aplicatie string authentication = Salaries.Configuration.CryptographyClass.getSettingsWithoutDecode("authentication"); //daca utilizatorul nu are acces la aplicatie atunci este redirectat catre o pagina in care este afisat un mesaj de avertizare if (authentication == "0") { ErrHandler.MyErrHandler.WriteError("Index.aspx - utilizatorul nu are acces la aplicatie"); Response.Redirect("Unauthorized.aspx"); } //este sters tot din sesine Session.RemoveAll(); try { //se preia stringul de conexiune din web.config settings = Salaries.Configuration.ModuleConfig.GetSettings(); UtilitiesDb utilDb = new UtilitiesDb(settings.ConnectionString); //daca lipseste una din datele strinct necesare pentru conectare la baza, //utilizatorul este redirectat catre pagina pentru introducerea acestor valori string[] s = settings.ConnectionString.Split(';'); if ((s[2] == "data source=") || (s[4] == "initial catalog=") || (s[5] == "user id=") || (s[6] == "pwd=")) { Response.Redirect("AdminSetari.aspx"); } //se verifica daca se pot obtine date din baza de date int angajatorId = 0; try { //daca nu se pot atunci stringul de conexiune nu este corect si utilizatorul este redirectat pentru //introducerea unui string de conexiune corect Salaries.Business.AdminTari tari = new Salaries.Business.AdminTari(); int TaraID = int.Parse(tari.LoadInfoTari().Tables[0].Rows[0]["TaraID"].ToString()); } catch (Exception e1) { Response.Redirect("AdminSetari.aspx"); string msg = e1.Message; } //se selecteaza un angajator Salaries.Business.AdminAngajator angajator = new Salaries.Business.AdminAngajator(); try { //daca nu se poate face acest lucru atunci in baza nu exista angajatori si utilizatorul este //redirectat catre pagina pentru introducerea primului angajator angajatorId = int.Parse(angajator.LoadInfoAngajatori().Tables[0].Rows[0]["AngajatorID"].ToString()); } catch { Response.Redirect("Administrare/AdminPrimulAngajator.aspx"); } Session["AngajatorID"] = angajatorId.ToString(); Session["AngajatorDenumire"] = angajator.LoadInfoAngajatori().Tables[0].Rows[0]["Denumire"].ToString(); //autentificarea este de tip windows prin Active Directory if (authentication == "1") { //este preluat user-ul loginat user = new WindowsPrincipal(WindowsIdentity.GetCurrent()); //daca utilizatorul face parte din grupul HR if (Salaries.Business.Authentication.IsUserInHRgroup(user)) { Session["administrare_departamente"] = ""; Response.Redirect("Home.aspx"); } else { //daca user-ul faca parte din grupul de manageri if (Salaries.Business.Authentication.IsUserInManagersGroup(user)) { Response.Redirect("Managers/Managers.aspx"); } else { //daca user-ul faca parte din grupul de recrutori if (Salaries.Business.Authentication.IsUserInRecrutoriGroup(user)) { Response.Redirect("Recrutori/Recrutori.aspx"); } else { ErrHandler.MyErrHandler.WriteError("Index.aspx - autentificare windows fara drepturi - " + user.Identity.Name); Response.Redirect("Unauthorized.aspx"); } } } } //autentificarea este cu user si parola else { Response.Redirect("AdminUserParola.aspx"); } } catch (Exception ex) { string msg = ex.Message; } } }
private void Page_Load(object sender, System.EventArgs e) { settings = Salaries.Configuration.ModuleConfig.GetSettings(); Utilities.CreateTableHeader(tableCautareRapida, "Cautare rapida", "", "normal"); if (!IsPostBack) { //se obtine tipul de autentificare la aplicatie string authentication = Salaries.Configuration.CryptographyClass.getSettingsWithoutDecode("authentication"); //virtual path string path = Page.Request.FilePath; char separator = '/'; string [] pathArr = path.Split(separator); int nr = pathArr.Length; //autentificare de tip windows if (authentication == "1") { //user-ul loginat user = new WindowsPrincipal(WindowsIdentity.GetCurrent()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], user)) { ErrHandler.MyErrHandler.WriteError("SearchAngajati.aspx - autentificare windows fara drepturi - " + user.Identity.Name); Response.Redirect("Unauthorized.aspx"); } } //autentificare cu user si parola else { try { string nume = Session["Nume"].ToString(); string parola = Session["Parola"].ToString(); int angajatorId = int.Parse(Session["AngajatorId"].ToString()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], nume, parola, angajatorId)) { ErrHandler.MyErrHandler.WriteError("SearchAngajati.aspx - autentificare user parola fara drepturi - " + nume + ", " + angajatorId); Response.Redirect("Unauthorized.aspx"); } } catch (Exception exc) { Response.Redirect("index.aspx"); } } ListItem myItem = new ListItem("", "-1"); lstDepartamentSearch.Items.Add(myItem); UtilitiesDb utilDb = new UtilitiesDb(settings.ConnectionString); utilDb.CreateDepartamenteSelectBox(0, 0, lstDepartamentSearch); BindNationalitateCombo(); BindTaraDeOrigineCombo(); BindStudiiCombo(); BindTitulaturaCombo(); BindFunctieCombo(); BindCategorieCombo(); BindBancaCombo(); BindDataAngajareCombo(); BindPunctLucruCombo(); tableCautareAvansataVisible.Style.Add("display", "none"); //nu e niciunul vizibil tdDataFixaSearch.Style.Add("display", "none"); tdLunaSearch.Style.Add("display", "none"); tdIntervalSearch.Style.Add("display", "none"); lblBanca.Style.Add("display", "none"); lstBancaSearch.Style.Add("display", "none"); lblCopii.Style.Add("display", "none"); lstDeducereCopiiSearch.Style.Add("display", "none"); CreazaVarJavaScript(); } }
private static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()); if (!windowsPrincipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) { TopMostMessageBox.Show(EcoLanguage.getMsg(LangRes.NeedPrivilege, new string[0]), "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); System.Environment.Exit(0); return; } EcoGlobalVar.nullcontextMenuStrip = new ContextMenuStrip(); EcoGlobalVar.ECOAppRunMode = 1; AppInterProcess.OpenInterProcessShared(); int processID = AppInterProcess.getProcessID(Program.program_uid, Program.program_serverid, EcoGlobalVar.ECOAppRunMode); if (processID != 0) { AppInterProcess.CloseShared(); string processOwner = Program.GetProcessOwner(processID); string processOwner2 = Program.GetProcessOwner(Process.GetCurrentProcess().Id); if (processOwner.Equals(processOwner2)) { Program.setTopMost(processID); } else { TopMostMessageBox.Show(EcoLanguage.getMsg(LangRes.APPRunbyuser, new string[] { processOwner }), "Information", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } System.Environment.Exit(0); return; } AppInterProcess.setMyProcessID(Program.program_uid, Program.program_serverid, EcoGlobalVar.ECOAppRunMode); Program.setTopMost(Process.GetCurrentProcess().Id); int mySQLUseMajorVersionOnly = DevAccessCfg.GetInstance().getMySQLUseMajorVersionOnly(); DBMaintain.SetMySQLVersionRole(mySQLUseMajorVersionOnly); while (Program.LocalConsole_cfg() == -2) { } DBUrl.RUNMODE = 1; ClientAPI.SetBroadcastCallback(new CommonAPI.CommonAPI.DelegateOnBroadcast(EcoGlobalVar.receiveDashBoardFlgProc)); ClientAPI.SetClosedCallback(new CommonAPI.CommonAPI.DelegateOnClosed(EcoGlobalVar.ServerClosedProc)); Login.Login login = new Login.Login(); login.Icon = null; login.ShowDialog(); if (login.UserName == null) { Program.ExitApp(); return; } EcoGlobalVar.gl_StartProcessfThread(true); Application.CurrentCulture = System.Globalization.CultureInfo.CurrentUICulture; if (EcoGlobalVar.ECOAppRunMode == 1) { DBCacheStatus.DBSyncEventInit(false); DBCacheEventProcess.StartRefreshThread(false); DBCache.DBCacheInit(false); } if (ClientAPI.WaitDatasetReady(40000u) < 0) { TopMostMessageBox.Show(EcoLanguage.getMsg(LangRes.DB_waitready, new string[0]), "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); Program.ExitApp(); return; } EcoGlobalVar.DCLayoutType = ClientAPI.getRackLayout(); EcoGlobalVar.gl_maxZoneNum = CultureTransfer.ToInt32(ClientAPI.getKeyValue("MaxZoneNum")); EcoGlobalVar.gl_maxRackNum = CultureTransfer.ToInt32(ClientAPI.getKeyValue("MaxRackNum")); EcoGlobalVar.gl_maxDevNum = CultureTransfer.ToInt32(ClientAPI.getKeyValue("MaxDevNum")); EcoGlobalVar.gl_supportISG = (CultureTransfer.ToInt32(ClientAPI.getKeyValue("SupportISG")) > 0); EcoGlobalVar.gl_supportBP = (CultureTransfer.ToInt32(ClientAPI.getKeyValue("SupportBP")) > 0); EcoGlobalVar.TempUnit = CultureTransfer.ToInt32(ClientAPI.getKeyValue("TempUnit")); EcoGlobalVar.CurCurrency = ClientAPI.getKeyValue("CurCurrency"); EcoGlobalVar.co2kg = CultureTransfer.ToSingle(ClientAPI.getKeyValue("co2kg")); EcoGlobalVar.flgEnablePower = AppData.getDB_flgEnablePower(); EcoGlobalVar.RackFullNameFlag = CultureTransfer.ToInt32(ClientAPI.getKeyValue("RackFullNameFlag")); EcoGlobalVar.gl_PeakPowerMethod = DevAccessCfg.GetInstance().getPowerPeakMethod(); string valuePair = ValuePairs.getValuePair("UserID"); long l_id = System.Convert.ToInt64(valuePair); string valuePair2 = ValuePairs.getValuePair("UserName"); valuePair = ValuePairs.getValuePair("UserType"); int i_type = System.Convert.ToInt32(valuePair); valuePair = ValuePairs.getValuePair("UserRight"); int i_right = System.Convert.ToInt32(valuePair); string valuePair3 = ValuePairs.getValuePair("UserPortNM"); string valuePair4 = ValuePairs.getValuePair("UserDevice"); string valuePair5 = ValuePairs.getValuePair("UserGroup"); valuePair = ValuePairs.getValuePair("UserStatus"); ValuePairs.getValuePair("trial"); ValuePairs.getValuePair("remaining_days"); int i_status = System.Convert.ToInt32(valuePair); UserInfo userInfo = new UserInfo(l_id, valuePair2, "", i_status, i_type, i_right, valuePair3, valuePair4, valuePair5); EcoGlobalVar.gl_LoginUser = userInfo; EcoGlobalVar.gl_LoginUserUACDev2Port = (System.Collections.Generic.Dictionary <long, System.Collections.Generic.List <long> >)ClientAPI.RemoteCall(8, 1, "", 10000); if (EcoGlobalVar.gl_LoginUserUACDev2Port == null) { TopMostMessageBox.Show(EcoLanguage.getMsg(LangRes.DB_waitready, new string[0]), "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); Program.ExitApp(); return; } string para = "0230000\n" + userInfo.UserName; ClientAPI.RemoteCall(100, 1, para, 10000); MainForm.MainForm mainForm = new MainForm.MainForm(userInfo); EcoGlobalVar.gl_mainForm = mainForm; if (!EcoGlobalVar.gl_supportISG) { EcoGlobalVar.gl_monitorCtrl.FreshFlg_ISGPower = 0; EcoGlobalVar.gl_DashBoardCtrl.FreshFlg_ISGPower = 0; } EcoGlobalVar.gl_StopProcessfThread(); Program.IdleTimer_init(); Application.ApplicationExit += new System.EventHandler(Program.Application_ApplicationExit); System.AppDomain.CurrentDomain.ProcessExit += new System.EventHandler(Program.CurrentDomain_ProcessExit); Application.Run(mainForm); }
private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { //se obtine tipul de autentificare la aplicatie string authentication = Salaries.Configuration.CryptographyClass.getSettingsWithoutDecode("authentication"); //virtual path string path = Page.Request.FilePath; char separator = '/'; string [] pathArr = path.Split(separator); int nr = pathArr.Length; //autentificare de tip windows if (authentication == "1") { //user-ul loginat user = new WindowsPrincipal(WindowsIdentity.GetCurrent()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], user)) { ErrHandler.MyErrHandler.WriteError("Administrare.aspx - autentificare windows fara drepturi - " + user.Identity.Name); Response.Redirect("../Unauthorized.aspx"); } } //autentificare cu user si parola else { try { string nume = Session["Nume"].ToString(); string parola = Session["Parola"].ToString(); int angajatorId = int.Parse(Session["AngajatorId"].ToString()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], nume, parola, angajatorId)) { ErrHandler.MyErrHandler.WriteError("Administrare.aspx - autentificare user parola fara drepturi - " + nume + ", " + angajatorId); Response.Redirect("../Unauthorized.aspx"); } } catch (Exception exc) { Response.Redirect("../index.aspx"); } } } Response.Write(ConstrSirComenzi()); TableCell celulaMeniu = new TableCell(); celulaMeniu.Height = Unit.Point(570); celulaMeniu.Width = Unit.Point(190); celulaMeniu.BorderWidth = 0; celulaMeniu.HorizontalAlign = HorizontalAlign.Left; adminMeniu = ( AdminMeniu )LoadControl(Request.ApplicationPath + "/AdminMeniu.ascx"); adminMeniu.XmlSursa = "../Navigare/Administrare_Navigare.xml"; celulaMeniu.Controls.Add(adminMeniu); Table continut = new Table(); continut.HorizontalAlign = HorizontalAlign.Center; TableCell celulaContinut = new TableCell(); celulaContinut.VerticalAlign = VerticalAlign.Top; celulaContinut.Controls.Add(continut); TableRow randLiber = new TableRow(); randLiber.Cells.Add(new TableCell()); randLiber.Height = Unit.Point(20); continut.Rows.Add(randLiber); TableRow continutPagina = new TableRow(); continutPagina.Cells.Add(celulaMeniu); continutPagina.Cells.Add(celulaContinut); mainTable.Rows.Add(continutPagina); TableCell myCell = new TableCell(); TableRow myRow = new TableRow(); myRow.Cells.Add(myCell); continut.Rows.Add(myRow); string myCmd = Request.QueryString["cmd"]; switch (myCmd) { case "admin_banci": AdminBanci myAdminBanci = (AdminBanci)LoadControl("AdminBanci.ascx"); myCell.Controls.Add(myAdminBanci); break; case "admin_angajatori": case null: int idAngajator = Convert.ToInt32(Request.QueryString["id"]); // nu este editare angajator if (idAngajator == 0) { AdminAngajatori myAdminAngajatori = (AdminAngajatori)LoadControl("AdminAngajatori.ascx"); myCell.Controls.Add(myAdminAngajatori); } // este editre angajator else { AdminAngajatoriEdit myAdminAngajatori = (AdminAngajatoriEdit)LoadControl("AdminAngajatoriEdit.ascx"); myAdminAngajatori.idAngajator = idAngajator; myCell.Controls.Add(myAdminAngajatori); } break; case "admin_centrecost": AdminCentreCost myAdminCentreCost = (AdminCentreCost)LoadControl("AdminCentreCost.ascx"); myCell.Controls.Add(myAdminCentreCost); break; case "admin_tip_rapoarte": AdminTipuriRapoarte myAdminTipuriRapoarte = (AdminTipuriRapoarte)LoadControl("AdminTipuriRapoarte.ascx"); myCell.Controls.Add(myAdminTipuriRapoarte); break; case "admin_judete": AdminJudete myAdminjudete = (AdminJudete)LoadControl("AdminJudete.ascx"); myCell.Controls.Add(myAdminjudete); break; case "admin_tari": AdminTari myAdmintari = (AdminTari)LoadControl("AdminTari.ascx"); myCell.Controls.Add(myAdmintari); break; case "admin_titutalturi": AdminTitluriAngajati myAdmintitluriangajati = (AdminTitluriAngajati)LoadControl("AdminTitluriAngajati.ascx"); myCell.Controls.Add(myAdmintitluriangajati); break; case "admin_studii": AdminStudii myAdminStudii = (AdminStudii)LoadControl("AdminStudii.ascx"); myCell.Controls.Add(myAdminStudii); break; case "admin_functii": AdminFunctii myAdminFunctii = (AdminFunctii)LoadControl("AdminFunctii.ascx"); myCell.Controls.Add(myAdminFunctii); break; case "admin_traininguri": AdminTraininguri myAdminTraininguri = (AdminTraininguri)LoadControl("AdminTraininguri.ascx"); myCell.Controls.Add(myAdminTraininguri); break; case "admin_departamente": Session["administrare_departamente"] = "administrare_departamente"; AdminDepartamente myAdminDept = (AdminDepartamente)LoadControl("AdminDepartamente.ascx"); myCell.Controls.Add(myAdminDept); break; case "admin_invaliditati": AdminInvaliditati myAdminInv = (AdminInvaliditati)LoadControl("AdminInvaliditati.ascx"); myCell.Controls.Add(myAdminInv); break; case "admin_domenii_de_activitate": AdminDomeniiDeActivitate myAdminDomDeAct = (AdminDomeniiDeActivitate)LoadControl("AdminDomeniiDeActivitate.ascx"); myCell.Controls.Add(myAdminDomDeAct); break; case "admin_completare_carnete": AdminTipuriCompletareCarnete myAdminCompletareCarnete = (AdminTipuriCompletareCarnete)LoadControl("AdminTipuriCompletareCarnete.ascx"); myCell.Controls.Add(myAdminCompletareCarnete); break; // Adaugat de Anca Holostencu // Descriere: Tab-ul pentru administrarea caselor de asigurari si cel pentru variabilele globale case "admin_case_de_asigurari": myCell.Controls.Add((AdminCaseDeAsigurari)LoadControl("AdminCaseDeAsigurari.ascx")); break; case "admin_variabile_salarizare": myCell.Controls.Add((AdminVariabileGlobale)LoadControl("AdminVariabileGlobale.ascx")); break; //Adaugat: Lungu Andreea //Data: 02.11.2007 //Descriere: Modulul pentru gestiunea utilizatorilor aplicatiei. case "admin_utilizatori": myCell.Controls.Add((AdminUtilizatori)LoadControl("AdminUtilizatori.ascx")); break; //Adaugat: Lungu Andreea //Data: 02.11.2007 //Descriere: Modificarea parolei pentru utilizatorul curent al aplicatiei. case "admin_schimbare_parola": myCell.Controls.Add((AdminChangePassword)LoadControl("AdminChangePassword.ascx")); break; case "admin_utilizatori_nivele": myCell.Controls.Add((AdminUtilizatoriNivele)LoadControl("AdminUtilizatoriNivele.ascx")); break; case "edit_utilizator": myCell.Controls.Add((EditUtilizator)LoadControl("EditUtilizator.ascx")); break; } }
private void Page_Load(object sender, System.EventArgs e) { ErrHandler.MyErrHandler.WriteError("home.aspx"); if (!IsPostBack) { //se obtine tipul de autentificare la aplicatie string authentication = Salaries.Configuration.CryptographyClass.getSettingsWithoutDecode("authentication"); //virtual path string path = Page.Request.FilePath; char separator = '/'; string [] pathArr = path.Split(separator); int nr = pathArr.Length; //autentificare de tip windows if (authentication == "1") { //user-ul loginat user = new WindowsPrincipal(WindowsIdentity.GetCurrent()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], user)) { ErrHandler.MyErrHandler.WriteError("Home.aspx - autentificare windows fara drepturi - " + user.Identity.Name); Response.Redirect("Unauthorized.aspx"); } } //autentificare cu user si parola else { try { string nume = Session["Nume"].ToString(); string parola = Session["Parola"].ToString(); int angajatorId = int.Parse(Session["AngajatorId"].ToString()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], nume, parola, angajatorId)) { ErrHandler.MyErrHandler.WriteError("Home.aspx - autentificare user parola fara drepturi - " + nume + ", " + angajatorId); Response.Redirect("Unauthorized.aspx"); } } catch (Exception exc) { Response.Redirect("index.aspx"); } } //Setam session-ul pentru paginile de administrare din AddAngajat Session["AdminCategoriiAngajati_AddAngajat"] = 0; } string numberOfDigits = Salaries.Configuration.CryptographyClass.getSettingsWithoutDecode("numberOfDigits"); Salaries.Business.VariabileGlobale.numberInfoFormatWithDigits.NumberDecimalDigits = int.Parse(numberOfDigits); Salaries.Business.VariabileGlobale.numberInfoFormatWithoutDigits.NumberDecimalDigits = 0; //Variabilele de sesiune au valoare vida Session["ModificaSituatie"] = ""; Session["Recrutori"] = ""; }
private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { //se obtine tipul de autentificare la aplicatie string authentication = Salaries.Configuration.CryptographyClass.getSettingsWithoutDecode("authentication"); //virtual path string path = Page.Request.FilePath; char separator = '/'; string [] pathArr = path.Split(separator); int nr = pathArr.Length; //autentificare de tip windows if (authentication == "1") { //user-ul loginat user = new WindowsPrincipal(WindowsIdentity.GetCurrent()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], user)) { ErrHandler.MyErrHandler.WriteError("EditAngajat.aspx - autentificare windows fara drepturi - " + user.Identity.Name); Response.Redirect("Unauthorized.aspx"); } } //autentificare cu user si parola else { try { string nume = Session["Nume"].ToString(); string parola = Session["Parola"].ToString(); int angajatorId = int.Parse(Session["AngajatorId"].ToString()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], nume, parola, angajatorId)) { ErrHandler.MyErrHandler.WriteError("EditAngajat.aspx - autentificare user parola fara drepturi - " + nume + ", " + angajatorId); Response.Redirect("Unauthorized.aspx"); } } catch (Exception exc) { Response.Redirect("index.aspx"); } } } idAngajat = Convert.ToInt32(Request.QueryString["id"]); string myCmd = Request.QueryString["cmd"]; mainTable.Attributes.Add("width", "100%"); mainTable.Attributes.Add("height", "100%"); mainTable.Attributes.Add("border", "0"); mainTable.Attributes.Add("cellpadding", "0"); mainTable.Attributes.Add("cellspacing", "0"); TableRow myRow; TableRow mySecondRow; TableCell myCell; // al doilea table.. care va contine 2 linii - taskuri si control centru Table secondTable = new Table(); secondTable.Attributes.Add("width", "100%"); secondTable.Attributes.Add("height", "100%"); secondTable.Attributes.Add("border", "0"); secondTable.Attributes.Add("cellpadding", "0"); secondTable.Attributes.Add("cellspacing", "0"); try { objAngajat = new Salaries.Business.Angajat(); objAngajat.AngajatId = idAngajat; objAngajat.LoadAngajat(); } catch (Exception ex) { Response.Write("Error loading employee data: <br>"); Response.Write(ex.Message); Response.End(); } // se adauga partea stanga myRow = new TableRow(); myCell = new TableCell(); myCell = new TableCell(); myCell.RowSpan = 3; myCell.Width = new Unit(310, UnitType.Pixel); myEditAngajatLeft = (EditAngajatLeft)LoadControl("EditAngajatLeft.ascx"); myEditAngajatLeft.XmlSursa = "Navigare/EditAngajat_LeftNavigation.xml"; myEditAngajatLeft.AngajatID = idAngajat; myEditAngajatLeft.objAngajat = objAngajat; myCell.Attributes.Add("valign", "top"); myCell.Controls.Add(myEditAngajatLeft); myRow.Cells.Add(myCell); // se adauga partea dreapta mySecondRow = new TableRow(); myCell = new TableCell(); EditAngajatUp myEditAngajatUp = (EditAngajatUp)LoadControl("EditAngajatUp.ascx"); myCell.Attributes.Add("valign", "top"); myCell.Attributes.Add("height", "10"); myEditAngajatUp.AngajatID = idAngajat; myCell.Controls.Add(myEditAngajatUp); mySecondRow.Cells.Add(myCell); secondTable.Rows.Add(mySecondRow); // se adauga a doua linie din tabel.. ce contine controlul mySecondRow = new TableRow(); myCell = new TableCell(); myCell.Attributes.Add("valign", "top"); myCell.Attributes.Add("height", "100%"); myCell.Attributes.Add("align", "center"); switch (myCmd) { case "date_personale": case null: EditAngajatDatePersonale myEditControl = (EditAngajatDatePersonale)LoadControl("EditTasks/EditAngajatDatePersonale.ascx"); myEditControl.objAngajat = objAngajat; myCell.Controls.Add(myEditControl); break; case "date_angajare": //var control = LoadControl("EditTasks/EditAngajatDateAngajare.ascx"); //EditAngajatDateAngajare myEditDateAngajatControl = (EditAngajatDateAngajare) control; EditAngajatDateAngajare myEditDateAngajatControl = (EditAngajatDateAngajare)LoadControl("EditTasks/EditAngajatDateAngajare.ascx"); myEditDateAngajatControl.objAngajat = objAngajat; myCell.Controls.Add(myEditDateAngajatControl); break; case "istoric_departamente": IstoricDepartamente myIstoricDepartamenteControl = (IstoricDepartamente)LoadControl("EditTasks/IstoricDepartamente.ascx"); myIstoricDepartamenteControl.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricDepartamenteControl); break; case "contract_munca": contract_munca myContractMunca = (contract_munca)LoadControl("Comunicari/contract_munca.ascx"); myContractMunca.objAngajat = objAngajat; myCell.Controls.Add(myContractMunca); break; case "comunicare_prima": Comunicare_prima myComunicarePrima = (Comunicare_prima)LoadControl("Comunicari/Comunicare_prima.ascx"); myComunicarePrima.objAngajat = objAngajat; myCell.Controls.Add(myComunicarePrima); break; case "comunicare_majorare": comunicare_majorare myComunicareMajorare = (comunicare_majorare)LoadControl("Comunicari/Comunicare_majorare.ascx"); myComunicareMajorare.objAngajat = objAngajat; myCell.Controls.Add(myComunicareMajorare); break; case "comunicare_indexare": comunicare_indexare myComunicareIndexare = (comunicare_indexare)LoadControl("Comunicari/Comunicare_indexare.ascx"); myComunicareIndexare.objAngajat = objAngajat; myCell.Controls.Add(myComunicareIndexare); break; case "comunicare_indexare_majorare": comunicare_indexare_majorare myComunicareIM = (comunicare_indexare_majorare)LoadControl("Comunicari/Comunicare_indexare_majorare.ascx"); myComunicareIM.objAngajat = objAngajat; myCell.Controls.Add(myComunicareIM); break; case "comunicare_prelungire_cim": comunicare_prelungire_cim myComunicareCIM = (comunicare_prelungire_cim)LoadControl("Comunicari/Comunicare_prelungire_cim.ascx"); myComunicareCIM.objAngajat = objAngajat; myCell.Controls.Add(myComunicareCIM); break; case "fisa_postului": fisa_postului myfisapostului = (fisa_postului)LoadControl("Comunicari/fisa_postului.ascx"); myfisapostului.objAngajat = objAngajat; myCell.Controls.Add(myfisapostului); break; case "adeverintaMedicDeFamilie": adeverintaMedicDeFamilie myAdevMedicDeFamilie = (adeverintaMedicDeFamilie)LoadControl("Comunicari/adeverintaMedicDeFamilie.ascx"); myAdevMedicDeFamilie.objAngajat = objAngajat; myCell.Controls.Add(myAdevMedicDeFamilie); break; case "conturi_banca": ConturiBanca myConturiBanca = (ConturiBanca)LoadControl("EditTasks/ConturiBanca.ascx"); myConturiBanca.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myConturiBanca); break; case "change_poza": ChangePoza myChangePoza = (ChangePoza)LoadControl("EditTasks/ChangePoza.ascx"); myChangePoza.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myChangePoza); break; case "istoric_functii": IstoricFunctii myIstoricFunctii = (IstoricFunctii)LoadControl("EditTasks/IstoricFunctii.ascx"); myIstoricFunctii.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricFunctii); break; case "situatie_militara": SituatiiMilitare mySitMilitar = (SituatiiMilitare)LoadControl("EditTasks/SituatiiMilitare.ascx"); mySitMilitar.objAngajat = objAngajat; myCell.Controls.Add(mySitMilitar); break; case "istoric_training": IstoricTraininguri myIstoricTraininguri = (IstoricTraininguri)LoadControl("EditTasks/IstoricTraininguri.ascx"); myIstoricTraininguri.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricTraininguri); break; case "checkupuri": CheckupuriAngajat myCheckup = (CheckupuriAngajat)LoadControl("EditTasks/CheckupuriAngajat.ascx"); myCheckup.AngajatID = objAngajat.AngajatId; myCheckup.SefID = objAngajat.SefId; myCell.Controls.Add(myCheckup); break; case "evaluari_psihologice": EvaluariPsihologiceAngajat myEval = (EvaluariPsihologiceAngajat)LoadControl("EditTasks/EvaluariPsihologiceAngajat.ascx"); myEval.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myEval); break; case "istoric_referinte": ReferinteAngajat myReferinte = (ReferinteAngajat)LoadControl("EditTasks/ReferinteAngajat.ascx"); myReferinte.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myReferinte); break; case "pers_intretinere": PersoaneIntretinere myPersIntretinere = (PersoaneIntretinere)LoadControl("EditTasks/PersoaneIntretinere.ascx"); myPersIntretinere.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myPersIntretinere); break; case "istoric_schimbari": IstoricSchimbariDateAngajat myIstoricSchimbari = (IstoricSchimbariDateAngajat)LoadControl("EditTasks/IstoricSchimbariDateAngajat.ascx"); myIstoricSchimbari.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricSchimbari); break; case "istoric_concedii_odihna": IstoricConcediiOdihnaAngajat myIstoricCO = (IstoricConcediiOdihnaAngajat)LoadControl("EditTasks/IstoricConcediiOdihnaAngajat.ascx"); myIstoricCO.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricCO); break; case "istoric_concedii_medicale": IstoricConcediiMedicaleAngajat myIstoricCM = (IstoricConcediiMedicaleAngajat)LoadControl("EditTasks/IstoricConcediiMedicaleAngajat.ascx"); myIstoricCM.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricCM); break; case "istoric_permis_munca": IstoricPermiseMunca myIstoricPermiseMunca = (IstoricPermiseMunca)LoadControl("EditTasks/IstoricPermiseMunca.ascx"); myIstoricPermiseMunca.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricPermiseMunca); break; case "istoric_legitimatie_sedere": IstoricLegitimatiiSedere myIstoricLegitimatiiSedere = (IstoricLegitimatiiSedere)LoadControl("EditTasks/IstoricLegitimatiiSedere.ascx"); myIstoricLegitimatiiSedere.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricLegitimatiiSedere); break; case "istoric_NIF": IstoricNIFuri myIstoricNIFuri = (IstoricNIFuri)LoadControl("EditTasks/IstoricNIFuri.ascx"); myIstoricNIFuri.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricNIFuri); break; case "istoric_carte_identitate": IstoricCartiIdentitate myIstoricCartiIdentitate = (IstoricCartiIdentitate)LoadControl("EditTasks/IstoricCartiIdentitate.ascx"); myIstoricCartiIdentitate.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricCartiIdentitate); break; case "istoric_pasaport": IstoricPasapoarte myIstoricPasapoarte = (IstoricPasapoarte)LoadControl("EditTasks/IstoricPasapoarte.ascx"); myIstoricPasapoarte.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricPasapoarte); break; case "alerte_speciale": EditIstoricAlerte myEditIstoricAlerte = (EditIstoricAlerte)LoadControl("EditTasks/EditIstoricAlerte.ascx"); myEditIstoricAlerte.AngajatID = int.Parse(objAngajat.AngajatId.ToString()); myCell.Controls.Add(myEditIstoricAlerte); break; case "istoric_intreruperi_cim": IstoricSuspendariCIM myIstoricSusp = (IstoricSuspendariCIM)LoadControl("EditTasks/IstoricSuspendariCIM.ascx"); myIstoricSusp.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricSusp); break; case "istoric_tichete_de_masa": IstoricTicheteDeMasa myIstoricTichete = (IstoricTicheteDeMasa)LoadControl("EditTasks/IstoricTicheteDeMasa.ascx"); myIstoricTichete.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myIstoricTichete); break; case "nivel_angajat": NivelAngajat myNivel = (NivelAngajat)LoadControl("EditTasks/NivelAngajat.ascx"); myNivel.AngajatID = objAngajat.AngajatId; myCell.Controls.Add(myNivel); break; default: myCell.Text = "<img src=\"images/1x1.gif\" width=\"100%\" height=\"100%\">"; break; } mySecondRow.Cells.Add(myCell); secondTable.Rows.Add(mySecondRow); // se adauga al doilea tabel la primul myCell = new TableCell(); myCell.Controls.Add(secondTable); myCell.Attributes.Add("height", "100%"); myCell.Attributes.Add("width", "100%"); myRow.Cells.Add(myCell); mainTable.Rows.Add(myRow); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); if (mutex.WaitOne(TimeSpan.Zero, true)) { #if DEBUG Global.isDebug = true; #endif Global.Initialize(); string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Directory.SetCurrentDirectory(path); string logiDll = Path.Combine(path, "LogitechLed.dll"); if (File.Exists(logiDll)) { File.Delete(logiDll); } StringBuilder systeminfo_sb = new StringBuilder(string.Empty); systeminfo_sb.Append("\r\n========================================\r\n"); try { var win_reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); string productName = (string)win_reg.GetValue("ProductName"); systeminfo_sb.AppendFormat("Operation System: {0}\r\n", productName); } catch (Exception exc) { systeminfo_sb.AppendFormat("Operation System: Could not be retrieved. [Exception: {0}]\r\n", exc.Message); } systeminfo_sb.AppendFormat("System Architecture: " + (Environment.Is64BitOperatingSystem ? "64 bit" : "32 bit") + "\r\n"); systeminfo_sb.AppendFormat("Environment OS Version: {0}\r\n", Environment.OSVersion); systeminfo_sb.AppendFormat("System Directory: {0}\r\n", Environment.SystemDirectory); systeminfo_sb.AppendFormat("Executing Directory: {0}\r\n", Global.ExecutingDirectory); systeminfo_sb.AppendFormat("Launch Directory: {0}\r\n", Directory.GetCurrentDirectory()); systeminfo_sb.AppendFormat("Processor Count: {0}\r\n", Environment.ProcessorCount); //systeminfo_sb.AppendFormat("User DomainName: {0}\r\n", Environment.UserDomainName); //systeminfo_sb.AppendFormat("User Name: {0}\r\n", Environment.UserName); systeminfo_sb.AppendFormat("SystemPageSize: {0}\r\n", Environment.SystemPageSize); systeminfo_sb.AppendFormat("Environment Version: {0}\r\n", Environment.Version); System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); systeminfo_sb.AppendFormat("Is Elevated: {0}\r\n", principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)); systeminfo_sb.AppendFormat("Aurora Assembly Version: {0}\r\n", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version); systeminfo_sb.AppendFormat("Aurora File Version: {0}\r\n", System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion); systeminfo_sb.Append("========================================\r\n"); Global.logger.Info(systeminfo_sb.ToString()); string arg = ""; for (int arg_i = 0; arg_i < e.Args.Length; arg_i++) { arg = e.Args[arg_i]; switch (arg) { case ("-debug"): Global.isDebug = true; Global.logger.Info("Program started in debug mode."); break; case ("-silent"): isSilent = true; Global.logger.Info("Program started with '-silent' parameter"); break; case ("-ignore_update"): ignore_update = true; Global.logger.Info("Program started with '-ignore_update' parameter"); break; case ("-delay"): isDelayed = true; if (arg_i + 1 < e.Args.Length && int.TryParse(e.Args[arg_i + 1], out delayTime)) { arg_i++; } else { delayTime = 5000; } Global.logger.Info("Program started with '-delay' parameter with delay of " + delayTime + " ms"); break; case ("-install_logitech"): Global.logger.Info("Program started with '-install_logitech' parameter"); try { InstallLogitech(); } catch (Exception exc) { System.Windows.MessageBox.Show("Could not patch Logitech LED SDK. Error: \r\n\r\n" + exc, "Aurora Error"); } Environment.Exit(0); break; } } AppDomain currentDomain = AppDomain.CurrentDomain; if (!Global.isDebug) { currentDomain.UnhandledException += CurrentDomain_UnhandledException; } if (isDelayed) { System.Threading.Thread.Sleep((int)delayTime); } this.ShutdownMode = ShutdownMode.OnExplicitShutdown; //AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); if (Environment.Is64BitProcess) { currentDomain.AppendPrivatePath("x64"); } else { currentDomain.AppendPrivatePath("x86"); } Global.StartTime = Utils.Time.GetMillisecondsSinceEpoch(); Global.dev_manager = new DeviceManager(); Global.effengine = new Effects(); //Load config Global.logger.Info("Loading Configuration"); try { Global.Configuration = ConfigManager.Load(); } catch (Exception exc) { Global.logger.Error("Exception during ConfigManager.Load(). Error: " + exc); System.Windows.MessageBox.Show("Exception during ConfigManager.Load().Error: " + exc.Message + "\r\n\r\n Default configuration loaded.", "Aurora - Error"); Global.Configuration = new Configuration(); } Global.Configuration.PropertyChanged += (sender, eventArgs) => { ConfigManager.Save(Global.Configuration); }; Process.GetCurrentProcess().PriorityClass = Global.Configuration.HighPriority ? ProcessPriorityClass.High : ProcessPriorityClass.Normal; if (Global.Configuration.updates_check_on_start_up && !ignore_update) { string updater_path = System.IO.Path.Combine(Global.ExecutingDirectory, "Aurora-Updater.exe"); if (File.Exists(updater_path)) { try { ProcessStartInfo updaterProc = new ProcessStartInfo(); updaterProc.FileName = updater_path; updaterProc.Arguments = "-silent"; Process.Start(updaterProc); } catch (Exception exc) { Global.logger.Error("Could not start Aurora Updater. Error: " + exc); } } } Global.logger.Info("Loading Plugins"); (Global.PluginManager = new PluginManager()).Initialize(); Global.logger.Info("Loading KB Layouts"); Global.kbLayout = new KeyboardLayoutManager(); Global.kbLayout.LoadBrandDefault(); Global.logger.Info("Loading Input Hooking"); Global.InputEvents = new InputEvents(); Global.Configuration.PropertyChanged += SetupVolumeAsBrightness; SetupVolumeAsBrightness(Global.Configuration, new PropertyChangedEventArgs(nameof(Global.Configuration.UseVolumeAsBrightness))); Utils.DesktopUtils.StartSessionWatch(); Global.key_recorder = new KeyRecorder(Global.InputEvents); Global.logger.Info("Loading RazerSdkManager"); if (RzHelper.IsSdkVersionSupported(RzHelper.GetSdkVersion())) { try { Global.razerSdkManager = new RzSdkManager() { KeyboardEnabled = true, MouseEnabled = true, MousepadEnabled = true, AppListEnabled = true, }; Global.logger.Info("RazerSdkManager loaded successfully!"); } catch (Exception exc) { Global.logger.Fatal("RazerSdkManager failed to load!"); Global.logger.Fatal(exc.ToString()); } } else { Global.logger.Warn("Currently installed razer sdk version \"{0}\" is not supported by the RazerSdkManager!", RzHelper.GetSdkVersion()); } Global.logger.Info("Loading Applications"); (Global.LightingStateManager = new LightingStateManager()).Initialize(); if (Global.Configuration.GetPointerUpdates) { Global.logger.Info("Fetching latest pointers"); Task.Run(() => Utils.PointerUpdateUtils.FetchDevPointers("master")); } Global.logger.Info("Loading Device Manager"); Global.dev_manager.RegisterVariables(); Global.dev_manager.Initialize(); /*Global.logger.LogLine("Starting GameEventHandler", Logging_Level.Info); * Global.geh = new GameEventHandler(); * if (!Global.geh.Init()) * { * Global.logger.LogLine("GameEventHander could not initialize", Logging_Level.Error); * return; * }*/ Global.logger.Info("Starting GameStateListener"); try { Global.net_listener = new NetworkListener(9088); Global.net_listener.NewGameState += new NewGameStateHandler(Global.LightingStateManager.GameStateUpdate); Global.net_listener.WrapperConnectionClosed += new WrapperConnectionClosedHandler(Global.LightingStateManager.ResetGameState); } catch (Exception exc) { Global.logger.Error("GameStateListener Exception, " + exc); System.Windows.MessageBox.Show("GameStateListener Exception.\r\n" + exc); Environment.Exit(0); } if (!Global.net_listener.Start()) { Global.logger.Error("GameStateListener could not start"); System.Windows.MessageBox.Show("GameStateListener could not start. Try running this program as Administrator.\r\nExiting."); Environment.Exit(0); } Global.logger.Info("Listening for game integration calls..."); Global.logger.Info("Loading ResourceDictionaries..."); this.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("Themes/MetroDark/MetroDark.MSControls.Core.Implicit.xaml", UriKind.Relative) }); this.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("Themes/MetroDark/MetroDark.MSControls.Toolkit.Implicit.xaml", UriKind.Relative) }); Global.logger.Info("Loaded ResourceDictionaries"); Global.logger.Info("Loading ConfigUI..."); MainWindow = new ConfigUI(); ((ConfigUI)MainWindow).Display(); //Debug Windows on Startup if (Global.Configuration.BitmapWindowOnStartUp) { Window_BitmapView.Open(); } if (Global.Configuration.HttpWindowOnStartUp) { Window_GSIHttpDebug.Open(); } } else { try { NamedPipeClientStream client = new NamedPipeClientStream(".", "aurora\\interface", PipeDirection.Out); client.Connect(30); if (!client.IsConnected) { throw new Exception(); } byte[] command = System.Text.Encoding.ASCII.GetBytes("restore"); client.Write(command, 0, command.Length); client.Close(); } catch { //Global.logger.LogLine("Aurora is already running.", Logging_Level.Error); System.Windows.MessageBox.Show("Aurora is already running.\r\nExiting.", "Aurora - Error"); } } }
private void Page_Load(object sender, System.EventArgs e) { settings = Salaries.Configuration.ModuleConfig.GetSettings(); if (!IsPostBack) { //se obtine tipul de autentificare la aplicatie string authentication = Salaries.Configuration.CryptographyClass.getSettingsWithoutDecode("authentication"); //virtual path string path = Page.Request.FilePath; char separator = '/'; string [] pathArr = path.Split(separator); int nr = pathArr.Length; //autentificare de tip windows if (authentication == "1") { //user-ul loginat user = new WindowsPrincipal(WindowsIdentity.GetCurrent()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], user)) { ErrHandler.MyErrHandler.WriteError("SearchAngajatiList_Recrutori.aspx - autentificare windows fara drepturi - " + user.Identity.Name); Server.Transfer("../Unauthorized.aspx"); } } //autentificare cu user si parola else { try { string nume = Session["Nume"].ToString(); string parola = Session["Parola"].ToString(); int angajatorId = int.Parse(Session["AngajatorId"].ToString()); //user-ul loginat nu are dreptul sa acceseze aceasta pagina este redirectat catre o pagina care sa il instiinteze de acest lucru if (!Salaries.Business.Authentication.HasUserRightsOnPage(pathArr[nr - 1], nume, parola, angajatorId)) { ErrHandler.MyErrHandler.WriteError("SearchAngajatiList_Recrutori.aspx - autentificare user parola fara drepturi - " + nume + ", " + angajatorId); Server.Transfer("../Unauthorized.aspx"); } } catch (Exception exc) { Response.Redirect("../index.aspx"); } } string searchTipCautare = Session["txtTipCautareHidden"].ToString(); string searchNume = Session["txtNumeSearch"].ToString(); string searchPrenume = Session["txtPrenumeSearch"].ToString(); int searchNationalitate = Convert.ToInt32(Session["lstNationalitateSearch"]); int searchTaraOrigine = Convert.ToInt32(Session["lstTaraOrigineSearch"]); //tara de origine int searchStareCivila = Convert.ToInt32(Session["lstStareCivilaSearch"]); int searchCopii = Convert.ToInt32(Session["lstCopiiSearch"]); //copii string searchSex = Session["lstSexSearch"].ToString(); int searchTitulatura = Convert.ToInt32(Session["lstTitulaturaSearch"]); int searchStudii = Convert.ToInt32(Session["lstStudiiSearch"]); string searchMarca = Session["txtMarcaSearch"].ToString(); int searchDepartament = Convert.ToInt32(Session["lstDepartamentSearch"]); int searchFunctie = Convert.ToInt32(Session["lstFunctieSearch"]); //functie int searchModIncadrare = Convert.ToInt32(Session["lstModIncadrareSearch"]); int searchIndemnizatieConducere = Convert.ToInt32(Session["lstIndemnizatieConducereSearch"]); //indemnizatie conducere //categorie angajat : scutit impozit/categorii int searchScutitImpozit = Convert.ToInt32(Session["lstScutitImpozitSearch"]); //scutit impozit | int searchCategorii = Convert.ToInt32(Session["lstCategorieAngajatSearch"]); //categorii | //deducere+copii int searchDeducere = Convert.ToInt32(Session["lstDeducereSearch"]); //deducere | int searchDeducereCopii = Convert.ToInt32(Session["lstDeducereCopiiSearch"]); // copii | //conturi bancare: are conturi/banca int searchContBancarExistenta = Convert.ToInt32(Session["lstContBancarExistentaSearch"]); //are conturi | int searchBanca = Convert.ToInt32(Session["lstBancaSearch"]); //banca | //Data angajarii: tip data angajare/data fixa - data/luna - luna+an/interval - dataSt+dataEnd/blank - nimic/ int searchTipDataAngajare = Convert.ToInt32(Session["lstTipDataAngajareSearch"]); DateTime searchDataFixa = DateTime.MinValue; DateTime searchIntervalDataStart = DateTime.MinValue; DateTime searchIntervalDataEnd = DateTime.MinValue; int searchAnData = -1; int searchLunaData = -1; switch (searchTipDataAngajare) { case 0: try { searchDataFixa = Utilities.ConvertText2DateTime(Session["txtDataAngajatiSearch"].ToString()); Session.Remove("txtDataAngajatiSearch"); } catch {} break; case 1: try { searchAnData = Convert.ToInt32(Session["lstAnAngajatiSearch"]); searchLunaData = Convert.ToInt32(Session["lstLunaAngajatiSearch"]); Session.Remove("lstAnAngajatiSearch"); Session.Remove("lstLunaAngajatiSearch"); } catch {} break; case 2: try { searchIntervalDataStart = Utilities.ConvertText2DateTime(Session["txtDataStartAngajatiSearch"].ToString()); searchIntervalDataEnd = Utilities.ConvertText2DateTime(Session["txtDataEndAngajatiSearch"].ToString()); Session.Remove("txtDataStartAngajatiSearch"); Session.Remove("txtDataEndAngajatiSearch"); } catch {} break; case -1: break; } int searchPerioadaDeterminata = Convert.ToInt32(Session["lstPerioadaDeterminataSearch"]); //Contract pe perioada determinata //stergerea variabilelor de sesiune stergeVariabile(); //comanda de cautare SqlConnection m_con = new SqlConnection(settings.ConnectionString); SqlCommand searchCommand = new SqlCommand("tmp_CautareAngajat", m_con); searchCommand.CommandType = CommandType.StoredProcedure; searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_TipCautare", SqlDbType.NVarChar, 50, searchTipCautare)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_Nume", SqlDbType.NVarChar, 50, searchNume)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_Prenume", SqlDbType.NVarChar, 50, searchPrenume)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_Nationalitate", SqlDbType.Int, 4, searchNationalitate)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_TaraOrigineID", SqlDbType.Int, 4, searchTaraOrigine)); //tara de origine searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_StareCivila", SqlDbType.Int, 4, searchStareCivila)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_Copii", SqlDbType.Int, 4, searchCopii)); //copii searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_Sex", SqlDbType.Char, searchSex.Length, searchSex)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_TitluID", SqlDbType.Int, 4, searchTitulatura)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_StudiuID", SqlDbType.Int, 4, searchStudii)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_Marca", SqlDbType.NVarChar, 8, searchMarca)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_DepartamentID", SqlDbType.Int, 5, searchDepartament)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_FunctieID", SqlDbType.Int, 4, searchFunctie)); //functie searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_ModIncadrare", SqlDbType.Int, 4, searchModIncadrare)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_IndemnizatieConducere", SqlDbType.Int, 4, searchIndemnizatieConducere)); //indemnizatie de conducere //categorie angajat searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_ScutitImpozit", SqlDbType.Int, 4, searchScutitImpozit)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_CategorieID", SqlDbType.Int, 4, searchCategorii)); //deducere searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_Deducere", SqlDbType.Int, 4, searchDeducere)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_DeducereCopii", SqlDbType.Int, 4, searchDeducereCopii)); //conturi bancare searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_ContBancarExistenta", SqlDbType.Int, 4, searchContBancarExistenta)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_BancaID", SqlDbType.Int, 4, searchBanca)); //data angajarii searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_TipDataAngajare", SqlDbType.Int, 4, searchTipDataAngajare)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_DataFixa", SqlDbType.DateTime, 8, searchDataFixa)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_LunaData", SqlDbType.Int, 4, searchLunaData)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_AnData", SqlDbType.Int, 4, searchAnData)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_IntervalDataStart", SqlDbType.DateTime, 8, searchIntervalDataStart)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_IntervalDataEnd", SqlDbType.DateTime, 8, searchIntervalDataEnd)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_DataMinValue", SqlDbType.DateTime, 8, DateTime.MinValue)); searchCommand.Parameters.Add(UtilitiesDb.AddInputParameter("@in_PerioadaDeterminata", SqlDbType.Int, 4, searchPerioadaDeterminata)); //Contract pe perioada determinata SqlDataAdapter dAdapt = new SqlDataAdapter(searchCommand); DataSet ds = new DataSet(); dAdapt.Fill(ds); Session["SortBy"] = ""; Index = 1; Session["DataSource_searchList"] = ds; listDataGrid.DataSource = ds; listDataGrid.DataBind(); } }
static bool ihInteg() { 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)); }
private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { try { //se obtine tipul de autentificare la aplicatie string authentication = Salaries.Configuration.CryptographyClass.getSettingsWithoutDecode("authentication"); //autentificare de tip windows if (authentication == "1") { //este preluat user-ul loginat user = new WindowsPrincipal(WindowsIdentity.GetCurrent()); //se verifica daca user-ul face parte din grupul Managers if (Salaries.Business.Authentication.IsUserInManagersGroup(user)) { lblErr.Text = ""; //numele user-ului string userName = user.Identity.Name; //numele departamentului din care face parte user-ul string numeDepartament = ""; //numele user-ului va fi de forma: numeUser_numeDepartament //este definit separatorul char separator = '_'; string [] arrUserName = userName.Split(separator); if (arrUserName.Length > 1) { //este obtinut numele departamentului din care face parte user-ul numeDepartament = arrUserName[1].ToString(); Parameters.NumeDepartament = numeDepartament; } else { //daca user-ul nu face parte din nici un departement, se afiseaza mesaj de eroare lblErr.Text = "Ne pare rau, dar nu faceti parte din nici un departament!"; } } else { ErrHandler.MyErrHandler.WriteError("Managers.aspx - autentificare windows fara drepturi - " + user.Identity.Name); Server.Transfer("../Unauthorized.aspx"); } } //autentificare cu user si parola else { try { string nume = Session["Nume"].ToString(); string parola = Session["Parola"].ToString(); int angajatorId = int.Parse(Session["AngajatorId"].ToString()); //se verifica daca utilizatorul face parte din grupul Managers if (Salaries.Business.Authentication.IsUserInManagersGroup(nume, parola, angajatorId)) { lblErr.Text = ""; //numele user-ului string userName = nume; //numele departamentului din care face parte user-ul string numeDepartament = ""; //numele user-ului va fi de forma: numeUser_numeDepartament //este definit separatorul char separator = '_'; string [] arrUserName = userName.Split(separator); if (arrUserName.Length > 1) { //este obtinut numele departamentului din care face parte user-ul numeDepartament = arrUserName[1].ToString(); Parameters.NumeDepartament = numeDepartament; } else { //daca user-ul nu face parte din nici un departement, se afiseaza mesaj de eroare lblErr.Text = "Ne pare rau, dar nu faceti parte din nici un departament!"; } } else { ErrHandler.MyErrHandler.WriteError("SearchAngajati.aspx - autentificare user parola fara drepturi - " + nume + ", " + angajatorId); Server.Transfer("../Unauthorized.aspx"); } } catch (Exception exc) { Response.Redirect("../index.aspx"); } } } catch (Exception ex) { lblErr.Text = ex.Message; } } string myCmd = Request.QueryString["cmd"]; // comanda // setez atributele tabelului principal mainTable.Attributes.Add("width", "100%"); mainTable.Attributes.Add("height", "100%"); mainTable.Attributes.Add("border", "0"); mainTable.Attributes.Add("cellpadding", "0"); mainTable.Attributes.Add("cellspacing", "0"); TableRow myRow; TableRow mySecondRow; TableCell myCell; // al doilea tabel.. care va contine 1 linie - control centru Table secondTable = new Table(); secondTable.Attributes.Add("width", "100%"); secondTable.Attributes.Add("height", "100%"); secondTable.Attributes.Add("border", "0"); secondTable.Attributes.Add("cellpadding", "0"); secondTable.Attributes.Add("cellspacing", "0"); // se adauga partea stanga - optiuni la salarii myRow = new TableRow(); myCell = new TableCell(); myCell = new TableCell(); myCell.Width = new Unit(200, UnitType.Pixel); ManagersOptions myManagersOptions = (ManagersOptions)LoadControl("ManagersOptions.ascx"); myCell.Attributes.Add("valign", "top"); myCell.Attributes.Add("height", "100%"); myCell.Controls.Add(myManagersOptions); myRow.Cells.Add(myCell); // se adauga prima linie din tabel.. ce contine controlul mySecondRow = new TableRow(); myCell = new TableCell(); myCell.Attributes.Add("valign", "top"); myCell.Attributes.Add("height", "100%"); myCell.Attributes.Add("align", "center"); if (myCmd == null) { myCmd = "contract_munca"; } switch (myCmd) { case "contract_munca": ManagersOptions_ContrMunca myContrMunca = (ManagersOptions_ContrMunca)LoadControl("ManagersOptions_ContrMunca.ascx"); myCell.Controls.Add(myContrMunca); break; case "check_up": ManagersOptions_Checkup myCheckup = (ManagersOptions_Checkup)LoadControl("ManagersOptions_Checkup.ascx"); myCell.Controls.Add(myCheckup); break; case "data_majorare": ManagersOptions_DataMajorare myDataMajorare = (ManagersOptions_DataMajorare)LoadControl("ManagersOptions_DataMajorare.ascx"); myCell.Controls.Add(myDataMajorare); break; case "evolutie_salariu": ManagersOptions_EvolutieSal myEvSal = (ManagersOptions_EvolutieSal)LoadControl("ManagersOptions_EvolutieSal.ascx"); myCell.Controls.Add(myEvSal); break; case "salarii_angajati": ManagersOptions_EvSalAngDept myEvSalDept = (ManagersOptions_EvSalAngDept)LoadControl("ManagersOptions_EvSalAngDept.ascx"); myCell.Controls.Add(myEvSalDept); break; case "exit": Response.Write("<script>window.close();</script>"); break; } mySecondRow.Cells.Add(myCell); secondTable.Rows.Add(mySecondRow); // se adauga al doilea tabel la primul myCell = new TableCell(); myCell.Controls.Add(secondTable); myCell.Attributes.Add("height", "100%"); myCell.Attributes.Add("width", "100%"); myRow.Cells.Add(myCell); mainTable.Rows.Add(myRow); }