ApplicationSessions getApplicationSessions(DataSet dataSet) { ApplicationSessions result = new ApplicationSessions(); foreach (DataRow row in dataSet.Tables[0].Rows) { string sessionId = (string)row["ASP.NET_SessionId"]; if (result.Sessions.ContainsKey(sessionId)) { addApplicationRequest(row, result.Sessions[sessionId]); } else { string requestingIp = (string)row["IP"]; DateTime start = (DateTime)row["Start"]; DateTime end = (DateTime)row["End"]; string localhostName = (string)row["LocalhostName"]; ApplicationSession session = new ApplicationSession(sessionId, requestingIp, start, localhostName); session.End = end; result.Sessions.Add(sessionId, session); addApplicationRequest(row, session); } } return(result); }
/// <summary> /// Loads a file into the GUI. /// </summary> private void OpenTestFile() { LoadFileTestReset(); // Working in the master form ApplicationSession.FindElementByName("OpenFileButton").Click(); // Save current working file if one is opened try { Thread.Sleep(TimeSpan.FromSeconds(2)); // Wait for 1 second in case save as dialog appears ApplicationSession.FindElementByName("No").Click(); } catch { } Thread.Sleep(TimeSpan.FromSeconds(5)); // Working in the load dialog ApplicationSession.FindElementByClassName("Edit").SendKeys(TargetFileLocation + TestFileGZ); ApplicationSession.FindElementByClassName("Button").FindElementByName("Open").Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); // Working in enter password for file form ApplicationSession.FindElementByName("PasswordEntry").SendKeys("password"); ApplicationSession.FindElementByName("Ok").Click(); Thread.Sleep(TimeSpan.FromSeconds(4)); }
public async Task<IHttpActionResult> Logout() { if (string.IsNullOrWhiteSpace(IdUsuario)) { AuthenticationManager.SignOut(); return ApiOk(); } ApplicationUser usuarioAplicacao = UserManager.FindById(IdUsuario); if (usuarioAplicacao != null) { if (usuarioAplicacao.IdApplicationSession.HasValue) { ApplicationSession usuarioSessao = _unitOfWork.ApplicationSessionRepository.GetById(usuarioAplicacao.IdApplicationSession.Value); usuarioSessao.DataLogout = DateTime.Now; usuarioSessao.DataUltimaAcao = DateTime.Now; _unitOfWork.ApplicationSessionRepository.Update(usuarioSessao); await _unitOfWork.SaveChangesAsync(); usuarioAplicacao.IdApplicationSession = null; UserManager.Update(usuarioAplicacao); } } AuthenticationManager.SignOut(); return ApiOk(); }
private Application(Process process) { this.process = process; applicationSession = new ApplicationSession(); applicationSession.Register(this); windowFactory = WindowFactory.Desktop; }
public ActionResult LogOff() { ApplicationUser applicationUser = UserManager.FindByName(User.Identity.Name); if (applicationUser != null) { if (applicationUser.IdApplicationSession.HasValue) { ApplicationSession applicationSession = _unitOfWork.ApplicationSessionRepository.GetById(applicationUser.IdApplicationSession.Value); applicationSession.DataUltimaAcao = DateTime.Now; applicationSession.DataLogout = DateTime.Now; _unitOfWork.ApplicationSessionRepository.Update(applicationSession); _unitOfWork.SaveChanges(); applicationUser.IdApplicationSession = null; UserManager.Update(applicationUser); } } CookieLogoff(); AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return(RedirectToAction("LogOn", "BOAccountBase")); }
public virtual List <Window> DesktopWindows(Process process, ApplicationSession applicationSession) { return((from automationElement in FindAllWindowElements(process) let initializeOption = InitializeOption.NoCache select Create(automationElement, initializeOption, applicationSession.WindowSession(initializeOption))) .ToList()); }
public MainWindow() { InitializeComponent(); applicationSession = ApplicationSession.Start(new DispatcherInvoker(Dispatcher)); messageManager = applicationSession.MessageManager; activeThoughtsPresenter = new CollectionsPresenter <SubjectSession, ObservableCollection <Message>, Message>( messageManager, manager => manager.ActiveThoughts, manager => manager.FocusedActiveThought); staleThoughtsPresenter = new CollectionsPresenter <SubjectSession, ObservableCollection <Message>, Message>( messageManager, manager => manager.StaleThoughts, manager => manager.FocusedStaleThought); mainWindowPresenter = new MainPresenter() { Entry = new ThoughtEntryPresenter(messageManager), }; mainWindowPresenter.SetActiveDisplay(activeThoughtsPresenter); messageManager.PropertyChanged += messageManager_PropertyChanged; DataContext = mainWindowPresenter; }
/// <summary> /// Called by the MVC framework before the action method executes. /// </summary> /// <param name="filterContext">The filter context.</param> public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } var principal = PrivilegePrincipalPermission.Current; if (principal == null) { return; } var identity = principal.Identity as WebUserIdentity; if (identity == null) { return; } var session = new ApplicationSession(); session.Create(filterContext.HttpContext, principal, identity); }
public JsonResult MudarEmpresa(int id) { try { ApplicationUser applicationUser = UserManager.FindById(User.Identity.GetUserId()); ApplicationSession applicationSession = _unitOfWork.ApplicationSessionRepository.GetById(applicationUser.IdApplicationSession.Value); applicationSession.IdEmpresa = id; _unitOfWork.ApplicationSessionRepository.Update(applicationSession); _unitOfWork.SaveChanges(); } catch (Exception e) { _log.Error(e.Message, e); return(Json(new AjaxGenericResultModel { Success = false, Message = "Ocorreu um erro ao trocar a empresa.", Data = Url.Action("Index", "BOHome") }, JsonRequestBehavior.DenyGet)); } return(Json(new AjaxGenericResultModel { Success = true, Message = Resources.CommonStrings.ChangeCompanySuccess, Data = Url.Action("Index", "BOHome") }, JsonRequestBehavior.DenyGet)); }
public frmSetupApp() { AppSetting = ThisApp.AppSetting; Session = ThisApp.currentSession; InitializeComponent(); lblNotify.Text = ""; }
private void btnSave_Click(object sender, EventArgs e) { AppSetting = new ApplicationSetting(); this.ToEntity(AppSetting); AppSetting.ProjectName = ThisApp.Project.Name; Utility.WriteAppSetting(AppSetting); Session = new ApplicationSession(); if (rdSql.Checked) { Session.DbType = DatabaseType.SQL; } if (rdMongo.Checked) { Session.DbType = DatabaseType.Mongo; } if (rdNeo.Checked) { Session.DbType = DatabaseType.Neo; } groupBox2.ToEntity(Session); Session.ProjectName = ThisApp.Project.Name; Utility.WriteSession(Session); ThisApp.currentSession = Session; ThisApp.AppSetting = AppSetting; lblNotify.SetText("Thà nh công", AutoControl.LabelNotify.EnumStatus.Success); updateSession?.Invoke(); }
private async Task CreateApplicationSession(string userName) { ApplicationUser applicationUser = await UserManager.FindByNameAsync(userName); if (applicationUser == null) { return; } long idEmpresa = _uow.EmpresaRepository.RetornarEmpresaPrincipal(applicationUser.Id); var applicationSession = new ApplicationSession { IdAspNetUsers = applicationUser.Id, IdApplication = applicationUser.ApplicationId, DataLogin = DateTime.Now, DataUltimaAcao = DateTime.Now, IdEmpresa = idEmpresa }; _uow.ApplicationSessionRepository.Add(applicationSession); _uow.SaveChanges(); applicationUser.IdApplicationSession = applicationSession.IdApplicationSession; UserManager.Update(applicationUser); }
void Application_Start(object sender, EventArgs e) { ServiceInterfaceManager.LogInformation("CRSe_WEB Started", String.Format("{0}.{1}", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodBase.GetCurrentMethod().Name), string.Empty, 0); if (Application["ApplicationSession"] == null) { Application["ApplicationSession"] = new ApplicationSession(); } }
void cb_CheckedChanged(object sender, EventArgs e) { ApplicationSession session = new ApplicationSession(); session.DbType = m_dbType; groupBox2.ToEntity(session); Utility.WriteSession(session); ThisApp.currentSession = session; }
private async Task PostAuthenticateRequestEvent(object sender, EventArgs e) { if (User == null || User.Identity == null || !User.Identity.IsAuthenticated || !(User is ClaimsPrincipal)) { return; } var userManager = HttpContext.Current.GetOwinContext().GetUserManager <BackofficeUserManager>(); var user = (ClaimsPrincipal)User; var applicationUser = userManager.FindById(User.Identity.GetUserId()); long idEmpresa = 0; if (applicationUser != null) { var uow = (UnitOfWork)DependencyResolver.Current.GetService(typeof(UnitOfWork)); ApplicationSession applicationSession; if (!applicationUser.IdApplicationSession.HasValue) { PerfilUsuario perfilUsuario = uow.PerfilUsuarioRepository.GetByUserId(applicationUser.Id); long idEmpresaPrincipal = perfilUsuario.EmpresaPrincipal.IdEmpresa; applicationSession = new ApplicationSession { IdAspNetUsers = applicationUser.Id, IdApplication = applicationUser.ApplicationId, DataLogin = DateTime.Now, DataUltimaAcao = DateTime.Now, IdEmpresa = idEmpresaPrincipal }; uow.ApplicationSessionRepository.Add(applicationSession); uow.SaveChanges(); applicationUser.IdApplicationSession = applicationSession.IdApplicationSession; userManager.Update(applicationUser); } else { applicationSession = uow.ApplicationSessionRepository.GetById(applicationUser.IdApplicationSession.Value); } if (applicationSession != null && applicationSession.IdEmpresa.HasValue) { idEmpresa = applicationSession.IdEmpresa.Value; } } string userId = user.Identity.GetUserId(); IList <string> permissions = await userManager.GetPermissionsByIdEmpresaAsync(userId, idEmpresa).ConfigureAwait(false); HttpContext.Current.User = new ApplicationClaimsPrincipal(user, permissions); }
void addApplicationRequest(DataRow row, ApplicationSession parentSession) { string url = (string)row["URI"]; DateTime requestTimestamp = (DateTime)row["RequestTimestamp"]; DateTime responseTimestamp = (DateTime)row["ResponseTimestamp"]; string requestBody = (row["RequestBody"] == DBNull.Value) ? "" : (string)row["RequestBody"]; string responseBody = (row["ResponseBody"] == DBNull.Value) ? "" : (string)row["ResponseBody"]; parentSession.Requests.Add(new ApplicationRequest (parentSession.AspNetSessionId, new Uri(url, UriKind.RelativeOrAbsolute), requestTimestamp, responseTimestamp, requestBody, responseBody)); }
protected override ApplicationSession CreateApplicationSession(string name) { bool isAdmin; ApplicationSession applicationSession = new ApplicationSession(true, name) { RoleIds = GetRolesIdByUserId(name, out isAdmin).ToArray(), IsAdmin = isAdmin }; return(applicationSession); }
public virtual List <Window> DesktopWindows(Process process, ApplicationSession applicationSession) { var collection = FindAllWindowElements(process); var list = new List <Window>(); foreach (AutomationElement automationElement in collection) { InitializeOption initializeOption = InitializeOption.NoCache; list.Add(Create(automationElement, initializeOption, applicationSession.WindowSession(initializeOption))); } return(list); }
public void LoadFileWithKeyTest() { // Arrange LoadFileWithKeyTestReset(); DirectoryInfo keyFileInfo = new DirectoryInfo(TestKeyFile); string keyFilePath = keyFileInfo.FullName; // Act // Working in the master form ApplicationSession.FindElementByName("OpenFileButton").Click(); // Save current working file if one is opened try { Thread.Sleep(TimeSpan.FromSeconds(2)); // Wait for 1 second in case save as dialog appears ApplicationSession.FindElementByName("No").Click(); } catch { } Thread.Sleep(TimeSpan.FromSeconds(5)); // Working in the load dialog ApplicationSession.FindElementByClassName("Edit").SendKeys(TargetFileLocation + TestFileGZ); ApplicationSession.FindElementByClassName("Button").FindElementByName("Open").Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); // Working in enter password for file form ApplicationSession.FindElementByName("PasswordEntry").SendKeys("password"); ApplicationSession.FindElementByName("FindKeyFile").Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); // Working in Windows' open file dialog ApplicationSession.FindElementByClassName("Edit").SendKeys(keyFilePath); ApplicationSession.FindElementByClassName("Button").FindElementByName("Open").Click(); Thread.Sleep(TimeSpan.FromSeconds(5)); // Working in enter password for file form ApplicationSession.FindElementByName("Ok").Click(); Thread.Sleep(TimeSpan.FromSeconds(5)); // Assert Assert.AreEqual(FileOP.GetFile(), TestFileCSV); ApplicationSession.FindElementByName("LockButton").Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); ApplicationSession.FindElementByName("Yes").Click(); Thread.Sleep(TimeSpan.FromSeconds(5)); }
/// <summary> /// Using the configured SQL connection string, opens a connection to the database and attempts /// to wrtie a record from the ApplicationSessions table /// </summary> /// <returns>BoolTO with true value if read was successful, FaultTO otherwise</returns> public BoolTO canWrite() { UsageDao dao = new UsageDao(_connectionString); string sessionId = gov.va.medora.utils.StringUtils.getNCharRandom(24); ApplicationSession session = new ApplicationSession(sessionId, System.Net.IPAddress.Loopback.ToString(), DateTime.Now); session.End = DateTime.Now; session.LocalhostName = System.Net.IPAddress.Loopback.ToString(); ApplicationRequest request = new ApplicationRequest(sessionId, new Uri("http://mdws.va.gov/getSomething"), DateTime.Now, DateTime.Now, "<Soap>...</Soap>", "<Soap>...</Soap>"); session.Requests.Add(request); dao.saveSession(session); return(dao.deleteSession(sessionId)); }
public void EditWithRandomPasswordTest() { // Arrange OpenTestFile(); // Act // Working in master form ApplicationSession.FindElementByName("AddNewEntry").Click(); ApplicationSession.FindElementByName("EntryVariablesExpirationTextBox").SendKeys("expdate1"); ApplicationSession.FindElementByName("EntryVariablesTitleTextBox").SendKeys("title1"); ApplicationSession.FindElementByName("EntryVariablesUsernameTextBox").SendKeys("user1"); ApplicationSession.FindElementByName("EntryVariablesUrlTextBox").SendKeys("url1"); ApplicationSession.FindElementByName("EntryVariablesPasswordTextBox").Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); // Working in entry password form ApplicationSession.FindElementByName("EntryPasswordRandomizeButton").Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); // Working in random password generator form ApplicationSession.FindElementByName("Special").Click(); ApplicationSession.FindElementByName("UpperCase").Click(); ApplicationSession.FindElementByName("Brackets").Click(); ApplicationSession.FindElementByName("Digits").Click(); ApplicationSession.FindElementByName("CloseButton").Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); // Working in entry password form ApplicationSession.FindElementByName("entryPasswordOkButton").Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); // Working in master form ApplicationSession.FindElementByName("EntryVariablesConfirmButton").Click(); ApplicationSession.FindElementByName("SaveFileButton").Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); // Assert Assert.IsTrue(File.Exists(TargetFileLocation + TestFileGZ)); ApplicationSession.FindElementByName("LockButton").Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); ApplicationSession.FindElementByName("Yes").Click(); Thread.Sleep(TimeSpan.FromSeconds(5)); }
SqlDataAdapter buildInsertSessionAdapter(ApplicationSession session, SqlConnection conn, SqlTransaction tx) { SqlDataAdapter adapter = new SqlDataAdapter(); adapter.InsertCommand = new SqlCommand(); adapter.InsertCommand.Connection = conn; adapter.InsertCommand.Transaction = tx; adapter.InsertCommand.CommandText = "INSERT INTO dbo.MdwsSessions " + "([ASP.NET_SessionId], IP, Start, [End], LocalhostName) VALUES ('" + session.AspNetSessionId + "', '" + session.RequestingIP + "', '" + session.Start.ToString() + "', '" + session.End.ToString() + "', '" + session.LocalhostName + "');"; return(adapter); }
public ActionResult Login(UserEntity u) { if (u.Email != null && u.Password != null) { var user = _userservice.GetUserByName(u.Email, u.Password); if (user != null) { FormsAuthentication.SetAuthCookie(u.Email, u.Rememberme); if (u.Rememberme) { cookie.Values.Add("Email", user.Email); cookie.Values.Add("Password", u.Password); cookie.Values.Add("Rememberme", (u.Rememberme).ToString()); cookie.Expires = DateTime.Now.AddDays(15); Response.Cookies.Add(cookie); //var createPersistentCookie = u.Rememberme; //int timeout = createPersistentCookie ? 525600 : 2; // Timeout in minutes,525600 = 365 days //var ticket = new FormsAuthenticationTicket(u.Email, createPersistentCookie, timeout); //string encrypted = FormsAuthentication.Encrypt(ticket); //var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); //cookie.Expires = System.DateTime.Now.AddMinutes(timeout);//My Line //HttpContext.Response.Cookies.Add(cookie); // FormsAuthentication.SetAuthCookie(u.Email, false); //var authTicket = new FormsAuthenticationTicket(1, u.Email, DateTime.Now, DateTime.Now.AddMinutes(20), false, "Testing"); //string encryptedTicket = FormsAuthentication.Encrypt(authTicket); //var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); //HttpContext.Response.Cookies.Add(authCookie); } else { Response.Cookies["Login"].Values["Rememberme"] = "false"; //cookie.Values.Remove(Convert.ToBoolean(Request.Cookies["Login"].Values["Rememberme"]).ToString()); } ApplicationSession.Login(user); Session["Id"] = user.Id; Session["username"] = user.FirstName + " " + user.LastName; Session["rememberme"] = u.Rememberme; // LoggedInCkeck.g_IsLoggedIn = Session["IsLoggedIn"] == null ? false : (bool)Session["IsLoggedIn"]; return(RedirectToAction("Index", "Dashboard")); } else { ModelState.AddModelError("", "Invalid User Name or Password "); } } return(View(u)); }
public void CreateFileTest() { // Arrange DirectoryInfo keyFileInfo = new DirectoryInfo(TestKeyFile); string keyFilePath = keyFileInfo.FullName; // Act // Working in the master form ApplicationSession.FindElementByName("CreateNewButton").Click(); ApplicationSession.FindElementByName("Yes").Click(); // Save current working file if one is opened try { Thread.Sleep(TimeSpan.FromSeconds(1)); // Wait for 1 second in case save as dialog appears ApplicationSession.FindElementByName("Yes").Click(); } catch { } Thread.Sleep(TimeSpan.FromSeconds(1)); // Working in the windows save dialog ApplicationSession.FindElementByAccessibilityId("FileNameControlHost").SendKeys(TargetFileLocation + TestFileCSV); ApplicationSession.FindElementByName("Save").Click(); // Check if the Save As dialog appears when there's a leftover test file from previous test run try { Thread.Sleep(TimeSpan.FromSeconds(1)); // Wait for 1 second in case save as dialog appears ApplicationSession.FindElementByName("Confirm Save As").FindElementByName("Yes").Click(); } catch { } Thread.Sleep(TimeSpan.FromSeconds(1)); // Working in master password gen form ApplicationSession.FindElementByName("PassEntry1").SendKeys("password"); ApplicationSession.FindElementByName("PassEntry2").SendKeys("password"); ApplicationSession.FindElementByName("Ok").Click(); Thread.Sleep(TimeSpan.FromSeconds(1)); // Working in master password print pop up form ApplicationSession.FindElementByName("No").Click(); Thread.Sleep(TimeSpan.FromSeconds(3)); // Assert Assert.IsTrue(File.Exists(TargetFileLocation + TestFileGZ)); }
public ApplicationSessionTO(ApplicationSession session) { this.sessionId = session.AspNetSessionId; this.requestingIp = session.RequestingIP; this.start = session.Start.ToString(); this.end = session.End.ToString(); if (session.Requests != null) { this.requests = new ApplicationRequestTO[session.Requests.Count]; for (int i = 0; i < session.Requests.Count; i++) { this.requests[i] = new ApplicationRequestTO(session.Requests[i]); } } this.localhostName = session.LocalhostName; }
public void Screen_caching_with_matches() { MockRepository mocks = new MockRepository(); Application mockApplication = mocks.CreateMock<Application>(); DummyWindow window = mocks.CreateMock<DummyWindow>(); SetupResult.For(window.Title).Return("whatever"); SetupResult.For(window.IsClosed).Return(false); Expect.Call(mockApplication.Find(delegate { return true; }, InitializeOption.NoCache)).Return(window).IgnoreArguments(); ApplicationSession applicationSession = mocks.CreateMock<ApplicationSession>(); SetupResult.For(applicationSession.Application).Return(mockApplication); mocks.ReplayAll(); ScreenRepository screenRepository = new ScreenRepository(applicationSession); Assert.AreSame(FindScreen(screenRepository), FindScreen(screenRepository)); mocks.VerifyAll(); }
public async Task <GerarTokenAcessoColetorResponse> GerarTokenAcessoColetor(string usuario, string senha, string idUsuario) { var applicationSession = new ApplicationSession { DataLogin = DateTime.Now, DataUltimaAcao = DateTime.Now, IdApplication = 2, IdAspNetUsers = idUsuario }; _uow.ApplicationSessionRepository.Add(applicationSession); _uow.SaveChanges(); return(new GerarTokenAcessoColetorResponse { Token = await Token(usuario, senha), ApplicationSession = applicationSession, EmpresasUsuario = _uow.UsuarioEmpresaRepository.RetornaAtivaPorUsuario(idUsuario) }); }
public ActionResult Logout() { //var rememberme = Request.Cookies["Login"].Values["Rememberme"]; //if(rememberme=="True") //{ // cookie.Values.Add("rememberme",(true).ToString()); //} //else //{ // cookie.Values.Add("rememberme", (false).ToString()); //} Session.Clear(); Session.Abandon(); ApplicationSession.Logout(); FormsAuthentication.SignOut(); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1)); Response.Cache.SetNoStore(); return(RedirectToAction("Login", "CommonView")); }
public void ScreenShouldRemovedFromCacheWhenClosed() { var mocks = new MockRepository(); var mockApplication = mocks.CreateMock<Application>(); DummyWindow window = mocks.CreateMock<DummyWindow>(); Expect.Call(window.Title).Return("dummy"); SetupResult.For(window.IsClosed).Return(false); window.Close(); Expect.Call(mockApplication.GetWindow("dummy", InitializeOption.NoCache)).Return(window).IgnoreArguments().Repeat.Twice(); ApplicationSession applicationSession = mocks.CreateMock<ApplicationSession>(); SetupResult.For(applicationSession.Application).Return(mockApplication); mocks.ReplayAll(); ScreenRepository screenRepository = new ScreenRepository(applicationSession); DummyScreen screen = GetScreen(screenRepository); Assert.AreSame(screen, GetScreen(screenRepository)); screen.Close(); GetScreen(screenRepository); mocks.VerifyAll(); }
/// <summary> /// Save a ApplicationSession object and it's requests /// </summary> /// <param name="session">The session object to save</param> /// <returns> /// BoolTO.trueOrFalse = true on success /// BoolTO.fault will be != null on error /// </returns> public BoolTO saveSession(ApplicationSession session) { BoolTO result = new BoolTO(); SqlConnection conn = new SqlConnection(); SqlTransaction tx = null; try { conn = getConnection(); tx = conn.BeginTransaction(); SqlDataAdapter adapter = buildInsertSessionAdapter(session, conn, tx); adapter.InsertCommand.ExecuteNonQuery(); foreach (ApplicationRequest request in session.Requests) { adapter = buildInsertRequestAdapter(request, conn, tx); adapter.InsertCommand.ExecuteNonQuery(); } tx.Commit(); result.trueOrFalse = true; return(result); } catch (Exception exc) { if (tx != null && tx.Connection != null) // transaction connection should be null if completed { tx.Rollback(); } result.fault = new FaultTO(exc); return(result); } finally { conn.Close(); if (tx != null) { tx.Dispose(); } } }
public void LoadFileTest() { // Arrange LoadFileTestReset(); // Act // Working in the master form ApplicationSession.FindElementByName("OpenFileButton").Click(); // Save current working file if one is opened try { Thread.Sleep(TimeSpan.FromSeconds(2)); // Wait for 1 second in case save as dialog appears ApplicationSession.FindElementByName("No").Click(); } catch { } Thread.Sleep(TimeSpan.FromSeconds(5)); // Working in the load dialog ApplicationSession.FindElementByClassName("Edit").SendKeys(TargetFileLocation + TestFileGZ); ApplicationSession.FindElementByClassName("Button").FindElementByName("Open").Click(); Thread.Sleep(TimeSpan.FromSeconds(5)); // Working in enter password for file form ApplicationSession.FindElementByName("PasswordEntry").SendKeys("password"); ApplicationSession.FindElementByName("Ok").Click(); Thread.Sleep(TimeSpan.FromSeconds(5)); // Assert Assert.AreEqual(TestFileCSV, FileOP.GetFile()); ApplicationSession.FindElementByName("LockButton").Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); ApplicationSession.FindElementByName("Yes").Click(); Thread.Sleep(TimeSpan.FromSeconds(5)); }
/// <summary> /// Save a ApplicationSession object and it's requests /// </summary> /// <param name="session">The session object to save</param> /// <returns> /// BoolTO.trueOrFalse = true on success /// BoolTO.fault will be != null on error /// </returns> public BoolTO saveSession(ApplicationSession session) { BoolTO result = new BoolTO(); SqlConnection conn = new SqlConnection(); SqlTransaction tx = null; try { conn = getConnection(); tx = conn.BeginTransaction(); SqlDataAdapter adapter = buildInsertSessionAdapter(session, conn, tx); adapter.InsertCommand.ExecuteNonQuery(); foreach (ApplicationRequest request in session.Requests) { adapter = buildInsertRequestAdapter(request, conn, tx); adapter.InsertCommand.ExecuteNonQuery(); } tx.Commit(); result.trueOrFalse = true; return result; } catch (Exception exc) { if (tx != null && tx.Connection != null) // transaction connection should be null if completed { tx.Rollback(); } result.fault = new FaultTO(exc); return result; } finally { conn.Close(); if (tx != null) { tx.Dispose(); } } }
SqlDataAdapter buildInsertSessionAdapter(ApplicationSession session, SqlConnection conn, SqlTransaction tx) { SqlDataAdapter adapter = new SqlDataAdapter(); adapter.InsertCommand = new SqlCommand(); adapter.InsertCommand.Connection = conn; adapter.InsertCommand.Transaction = tx; adapter.InsertCommand.CommandText = "INSERT INTO dbo.MdwsSessions " + "([ASP.NET_SessionId], IP, Start, [End], LocalhostName) VALUES ('" + session.AspNetSessionId + "', '" + session.RequestingIP + "', '" + session.Start.ToString() + "', '" + session.End.ToString() + "', '" + session.LocalhostName + "');"; return adapter; }
ApplicationSessions getApplicationSessions(DataSet dataSet) { ApplicationSessions result = new ApplicationSessions(); foreach (DataRow row in dataSet.Tables[0].Rows) { string sessionId = (string)row["ASP.NET_SessionId"]; if (result.Sessions.ContainsKey(sessionId)) { addApplicationRequest(row, result.Sessions[sessionId]); } else { string requestingIp = (string)row["IP"]; DateTime start = (DateTime)row["Start"]; DateTime end = (DateTime)row["End"]; string localhostName = (string)row["LocalhostName"]; ApplicationSession session = new ApplicationSession(sessionId, requestingIp, start, localhostName); session.End = end; result.Sessions.Add(sessionId, session); addApplicationRequest(row, session); } } return result; }
/// <summary> /// Using the configured SQL connection string, opens a connection to the database and attempts /// to wrtie a record from the ApplicationSessions table /// </summary> /// <returns>BoolTO with true value if read was successful, FaultTO otherwise</returns> public BoolTO canWrite() { UsageDao dao = new UsageDao(_connectionString); string sessionId = gov.va.medora.utils.StringUtils.getNCharRandom(24); ApplicationSession session = new ApplicationSession(sessionId, System.Net.IPAddress.Loopback.ToString(), DateTime.Now); session.End = DateTime.Now; session.LocalhostName = System.Net.IPAddress.Loopback.ToString(); ApplicationRequest request = new ApplicationRequest(sessionId, new Uri("http://mdws.va.gov/getSomething"), DateTime.Now, DateTime.Now, "<Soap>...</Soap>", "<Soap>...</Soap>"); session.Requests.Add(request); dao.saveSession(session); return dao.deleteSession(sessionId); }