public double[] SolveLinearSystem_Parallel_LU(double[] RightHandSide) { StopWatch_Solver_LU_Total = new StopWatchTimer(); StopWatch_Solver_LU_Decomposition = new StopWatchTimer(); StopWatch_Solver_LU_ForwardElimination = new StopWatchTimer(); StopWatch_Solver_LU_BackSubstitution = new StopWatchTimer(); StopWatch_Solver_LU_CalculateDeterminant = new StopWatchTimer(); StopWatch_Solver_LU_Total.StartTimer(); // PLU decomposition StopWatch_Solver_LU_Decomposition.StartTimer(); this.LUDecomposition_Parallel(); StopWatch_Solver_LU_Decomposition.StopTimer(); // Forward elimination StopWatch_Solver_LU_ForwardElimination.StartTimer(); this.ForwardElimination(RightHandSide); StopWatch_Solver_LU_ForwardElimination.StopTimer(); //Backward elimination StopWatch_Solver_LU_BackSubstitution.StartTimer(); this.BackSubstitution(); StopWatch_Solver_LU_BackSubstitution.StopTimer(); // Determinant StopWatch_Solver_LU_CalculateDeterminant.StartTimer(); this.CalculateDeterminant(); StopWatch_Solver_LU_CalculateDeterminant.StopTimer(); StopWatch_Solver_LU_Total.StopTimer(); return(rightHandSide); }
public async Task Invoke(HttpContext context) { string fileExtension = RouteFileExtension(context); if (!_processStaticFiles && !String.IsNullOrEmpty(fileExtension) && _staticFileExtensions.Contains($"{fileExtension};")) { await _next(context); return; } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { string route = RouteLowered(context); if (route.EndsWith("/robots.txt")) { context.Response.StatusCode = 200; context.Response.Body.Write(_spiderData, 0, _spiderData.Length); } else { if (_userSessionManagerLoaded) { if (context.Items.ContainsKey("UserSession")) { try { UserSession userSession = (UserSession)context.Items["UserSession"]; foreach (DeniedRoute deniedRoute in _deniedSpiderRoutes) { if (userSession.IsBot && deniedRoute.Route.StartsWith(route) && ( deniedRoute.UserAgent == "*" || #if NETCORE2_0 userSession.UserAgent.Contains(deniedRoute.UserAgent, StringComparison.CurrentCultureIgnoreCase) #else userSession.UserAgent.ToLower().Contains(deniedRoute.UserAgent.ToLower()) #endif )) { context.Response.StatusCode = 403; return; } } } catch (Exception err) { Initialisation.GetLogger.AddToLog(LogLevel.SpiderRouteError, err, MethodBase.GetCurrentMethod().Name); } } } } } await _next(context); }
public CallResult GetTestStringFromDatabase() //Backend, but... :) { StopWatchTimer timer = new StopWatchTimer(); timer.Start("Test database"); ///Create test values in database timer.StartNewLap("Save to database"); ///This is backend //TODO: move this to backend? TestData testDataValue = TestData.New(); const string TextToTestDatabaseIoWith = "Hello from database!;)"; testDataValue.TestText = TextToTestDatabaseIoWith; testDataValue.Save(); timer.StartNewLap("Read data from database"); var entryRead = TestData.ReadFirst("ID = @ID", "@ID", testDataValue.ID); ///end of Backend code ??? timer.Stop(); var response = string.Format("</br>Text from database: \"{0}\", </br> timer log: </br> {1}", entryRead.TestText, timer.ToString().Replace("\n", "</br>")); testDataValue.Delete(); return(new CallResult(response)); }
private async Task LoginUsingCookieValue(UserSession userSession, HttpContext context, IAuthenticationService authenticationService) { using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_autoLoginCookieTimings)) { string cookieValue = CookieValue(context, _loginControllerSettings.RememberMeCookieName, _loginControllerSettings.EncryptionKey, String.Empty); if (Int64.TryParse(cookieValue, out long userId)) { UserLoginDetails loginDetails = new UserLoginDetails(userId, true); LoginResult loginResult = _loginProvider.Login(String.Empty, String.Empty, GetIpAddress(context), 1, ref loginDetails); if (loginResult == LoginResult.Remembered) { userSession.Login(userId, loginDetails.Username, loginDetails.Email); await authenticationService.SignInAsync(context, _loginControllerSettings.AuthenticationScheme, new ClaimsPrincipal(_claimsProvider.GetUserClaims(loginDetails.UserId)), _claimsProvider.GetAuthenticationProperties()); } else { CookieDelete(context, _loginControllerSettings.RememberMeCookieName); } } else { CookieDelete(context, _loginControllerSettings.RememberMeCookieName); } } }
/// <summary> /// Developed by: Mehrdad Negahban /// Date: 12/25/2012 /// /// Purpose: Root class for static sparse N-D solvers (KU=F) /// Comments: /// /// Date modified: /// Modified by: /// Comments: /// </summary> public override void SolveFEMSystem() { //Set up the load vector and stiffness matrix int NDF = Unknowns_NDoF; //Get the size of the unknowns temperature (one per node) Vector F = new Vector(NDF); //Make global load vector MatrixSparseLinkedList K = new MatrixSparseLinkedList(NDF); // Make global stiffness matrix Timer_Assemble = new StopWatchTimer(); Timer_Assemble.StartTimer(); //Assemble F and K int NE = Elements.Length; //Get the number of elements for (int i = 0; i < NE; i++) { Elements[i].CalculateAndAssemble_FeAndKe(ref F, ref K); } //Adjust for boundary conditions int NBE = BoundaryElements.Length; for (int i = 0; i < NBE; i++) { BoundaryElements[i].AdjustFAndK(ref F, ref K); } Timer_Assemble.StopTimer(); Timer_Solve = new StopWatchTimer(); Timer_Solve.StartTimer(); //Solve system U = K.SolveLinearSystem(F); Timer_Solve.StopTimer(); }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { string route = RouteLowered(context); if (route.StartsWith("/sitemap")) { Dictionary <string, string> sitemaps = GetSitemaps(context); if (sitemaps.ContainsKey(route)) { await context.Response.WriteAsync(sitemaps[route]); context.Response.StatusCode = 200; return; } } } await _next(context); }
public async Task Invoke(HttpContext context) { bool passRequestOn = true; try { if (_disabled) { return; } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { string route = RouteLowered(context); string userIpAddress = GetIpAddress(context); bool isLocalAddress = _localIpAddresses.Contains(userIpAddress); #if !DEBUG // always allow local connections if (isLocalAddress) { return; } #endif foreach (KeyValuePair <string, List <string> > restrictedRoute in _restrictedRoutes) { if (route.StartsWith(restrictedRoute.Key)) { foreach (string restrictedIp in restrictedRoute.Value) { if ((isLocalAddress && restrictedIp == LocalHost) || (String.IsNullOrEmpty(restrictedIp))) { return; } if (userIpAddress.StartsWith(restrictedIp)) { return; } } // if we get here, we are in a restricted route and ip does not match, so fail with forbidden passRequestOn = false; context.Response.StatusCode = 403; Initialisation.GetLogger.AddToLog(LogLevel.IpRestricted, String.Format(RouteForbidden, userIpAddress, route)); } } } } finally { if (passRequestOn) { await _next(context); } } }
internal StopWatchManager( string stopWatchSetName, string saveDirectoryPath, int startingYLocation, Form form, Label primaryDisplay, bool includeMicroseconds, bool databaseCommitOption, EventHandler startStopClickEvents, EventHandler resetClickEvents) { this.stopWatchSetName = stopWatchSetName; this.databaseCommitOption = databaseCommitOption; this.saveDirectoryPath = saveDirectoryPath; stopWatch = new StopWatchTimer( saveDirectoryPath + "\\" + stopWatchSetName + ".dat", includeMicroseconds); locationY = startingYLocation; mainForm = form; lblPrimaryDisplay = primaryDisplay; tbSaveLocation = saveDirectoryPath + "\\" + StopWatchSetName + "_QuickNotes.dat"; LoadFormInfo(startStopClickEvents, resetClickEvents); StopWatch.DisplayUpdateTimer.Tick += new EventHandler(TimerTickIncrease); UpdateCurrentTimeLabel(); }
/// <summary> /// Method called during middleware processing of requests /// </summary> /// <param name="context">HttpContext for the request.</param> /// <param name="authenticationService"></param> /// <returns>Task</returns> /// <exception cref="ArgumentNullException">Raised if context is null</exception> public async Task Invoke(HttpContext context, IAuthenticationService authenticationService) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (authenticationService == null) { throw new ArgumentNullException(nameof(authenticationService)); } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_loginTimings)) { UserSession userSession = GetUserSession(context); if (userSession != null && context.Request.Headers.ContainsKey(SharedPluginFeatures.Constants.HeaderAuthorizationName)) { if (!await LoginUsingBasicAuth(userSession, context, authenticationService)) { return; } } else if (userSession != null && String.IsNullOrEmpty(userSession.UserName) && CookieExists(context, _loginControllerSettings.RememberMeCookieName)) { await LoginUsingCookieValue(userSession, context, authenticationService); } } await _next(context); }
//Stop Button: all digits fall back to zero when pressed private void btnStop_Click(object sender, EventArgs e) { StopWatchTimer.Stop(); seconds = minutes = hours = 0; lblHours.Text = appendZero(hours); lblMinutes.Text = appendZero(minutes); lblSeconds.Text = appendZero(seconds); }
private async Task <bool> LoginUsingBasicAuth(UserSession userSession, HttpContext context, IAuthenticationService authenticationService) { using (StopWatchTimer stopWatchTimer = StopWatchTimer.Initialise(_autoLoginBasicAuthLogin)) { string authData = context.Request.Headers[SharedPluginFeatures.Constants.HeaderAuthorizationName]; if (!authData.StartsWith("Basic ", StringComparison.InvariantCultureIgnoreCase)) { context.Response.StatusCode = 400; return(false); } try { authData = System.Text.Encoding.GetEncoding("ISO-8859-1").GetString(Convert.FromBase64String(authData.Substring(6))); } catch (FormatException) { context.Response.StatusCode = 400; return(false); } string[] authParts = authData.Split(':', StringSplitOptions.RemoveEmptyEntries); if (authParts.Length != 2) { context.Response.StatusCode = 400; return(false); } UserLoginDetails loginDetails = new UserLoginDetails(); LoginResult loginResult = _loginProvider.Login(authParts[0], authParts[1], GetIpAddress(context), 1, ref loginDetails); if (loginResult == LoginResult.Success) { userSession.Login(loginDetails.UserId, loginDetails.Username, loginDetails.Email); await authenticationService.SignInAsync(context, _loginControllerSettings.AuthenticationScheme, new ClaimsPrincipal(_claimsProvider.GetUserClaims(loginDetails.UserId)), _claimsProvider.GetAuthenticationProperties()); return(true); } else { context.Response.StatusCode = 401; return(false); } } }
public async Task Invoke(HttpContext context) { using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { if (context.Items.TryGetValue(Constants.UserCulture, out object sessionCulture)) { SetUserCulture((string)sessionCulture); } } await _next(context); }
public async Task Invoke(HttpContext context) { try { await _next(context); if (!context.Response.HasStarted) { switch (context.Response.StatusCode) { case 403: ITempDataDictionary tempData = GetTempData(context); tempData["ReturnUrl"] = context.Request.Path; context.Response.Redirect(_loginPage, false); break; case 404: using (StopWatchTimer notFoundTimer = StopWatchTimer.Initialise(_timingsMissingPages)) { context.Response.Redirect(GetMissingPage(context), false); break; } case 406: context.Response.Redirect("/Error/NotAcceptable"); break; case 420: case 429: context.Response.Redirect("/Error/Highvolume", false); break; } } } catch (Exception exception) { using (StopWatchTimer stopWatch = StopWatchTimer.Initialise(_timingsExceptions)) { if (ProcessException(context, exception)) { string s = exception.Message; context.Response.Redirect("/Error/", false); } else { // this is only invoked if the error manager is the problem throw; } } } }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } string fileExtension = RouteFileExtension(context); if (!String.IsNullOrEmpty(fileExtension) && _staticFileExtensions.Contains($"{fileExtension};")) { await _next(context); return; } string route = RouteLowered(context); using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { bool validateFormInput = false; foreach (ManagedRoute restrictedRoute in _managedRoutes) { if (restrictedRoute.ValidateFormFields && restrictedRoute.Route.StartsWith(route)) { validateFormInput = true; break; } } ValidateRequestResult validateResult = _validateConnections.ValidateRequest(context.Request, validateFormInput, out int _); if (!validateResult.HasFlag(ValidateRequestResult.IpWhiteListed)) { if (validateResult.HasFlag(ValidateRequestResult.IpBlackListed)) { context.Response.StatusCode = _badEggSettings.BannedResponseCode; return; } else if (validateResult.HasFlag(ValidateRequestResult.TooManyRequests)) { _notificationService.RaiseEvent(nameof(ValidateRequestResult.TooManyRequests), GetIpAddress(context)); context.Response.StatusCode = _badEggSettings.TooManyRequestResponseCode; return; } } } await _next(context); }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } try { if (_disabled) { return; } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { string routeLowered = RouteLowered(context); using (TimedLock lck = TimedLock.Lock(_lockObject)) { if (_ignoredRoutes.Contains(routeLowered)) { return; } } if (!context.Response.Headers.ContainsKey("Cache-Control")) { foreach (KeyValuePair <string, CacheControlRoute> keyValuePair in _routePaths) { if (routeLowered.StartsWith(keyValuePair.Key)) { context.Response.Headers.Add("Cache-Control", $"max-age={keyValuePair.Value.CacheValue}"); return; } } } using (TimedLock lck = TimedLock.Lock(_lockObject)) { _ignoredRoutes.Add(routeLowered); } } } finally { await _next(context); } }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { UserSession userSession = GetUserSession(context); if (userSession != null) { if (userSession.UserBasketId != 0 && !CookieExists(context, Constants.ShoppingCart)) { CookieAdd(context, Constants.ShoppingCart, Encrypt(userSession.UserBasketId.ToString(), _shoppingCartService.GetEncryptionKey()), 180); } if (userSession.UserBasketId == 0 && CookieExists(context, Constants.ShoppingCart)) { try { string basketCookie = Decrypt(CookieValue(context, Constants.ShoppingCart, String.Empty), _shoppingCartService.GetEncryptionKey()); if (Int64.TryParse(basketCookie, out long result)) { userSession.UserBasketId = result; } else { userSession.UserBasketId = 0; } } catch (FormatException) { // problem decrypting the cookie so delete it CookieDelete(context, Constants.ShoppingCart); } } context.Items[Constants.BasketSummary] = GetBasketSummary(userSession.UserBasketId); context.Items[Constants.DefaultTaxRate] = _cartSettings.DefaultTaxRate; } } await _next(context); }
internal StopWatchManager( string stopWatchSetName, string saveDirectoryPath, Label displayLabel, bool includeMicroseconds) { this.stopWatchSetName = stopWatchSetName; stopWatch = new StopWatchTimer( saveDirectoryPath + "\\" + StopWatchSetName + ".dat", includeMicroseconds); lblCurrentTime = displayLabel; StopWatch.DisplayUpdateTimer.Tick += new EventHandler(TimerTickIncreaseNoMainDisplay); }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { if (context.Items.TryGetValue(Constants.UserCulture, out object sessionCulture)) { SetUserCulture((string)sessionCulture); } } await _next(context); }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { string fileExtension = RouteFileExtension(context); if (!String.IsNullOrEmpty(fileExtension) && StaticFileExtensions.Contains($"{fileExtension};")) { await _next(context); return; } string route = RouteLowered(context); if (route.Length > 1 && route[route.Length - 1] == Constants.ForwardSlashChar) { route = route.Substring(0, route.Length - 1); } string cacheName = $"Seo Cache {route}"; CacheItem cacheItem = _memoryCache.GetCache().Get(cacheName); if (cacheItem == null) { _seoProvider.GetSeoDataForRoute(route, out string title, out string description, out string author, out List <string> tags); cacheItem = new CacheItem(cacheName, new SeoCacheItem(title, description, author, tags)); _memoryCache.GetCache().Add(cacheName, cacheItem); } SeoCacheItem seoCache = (SeoCacheItem)cacheItem.Value; context.Items[SeoMetaAuthor] = seoCache.Author; context.Items[SeoTitle] = seoCache.Title; context.Items[SeoMetaDescription] = seoCache.Description; context.Items[SeoMetaKeywords] = seoCache.Keywords; } await _next(context); }
public LocalizedString this[string name] { get { using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { try { StringBuilder resourceName = new StringBuilder(name.Length); // strip out any non alpha numeric characters foreach (char c in name) { if (c >= 65 && c <= 90) { resourceName.Append(c); } else if (c >= 61 && c <= 122) { resourceName.Append(c); } else if (c >= 48 && c <= 57) { resourceName.Append(c); } } string locString = _resourceManager.GetString(resourceName.ToString(), Thread.CurrentThread.CurrentUICulture); if (String.IsNullOrEmpty(locString)) { return(new LocalizedString(name, name)); } return(new LocalizedString(name, locString)); } catch (Exception error) { PluginInitialisation.GetLogger.AddToLog(LogLevel.Error, nameof(StringLocalizer), error, name); return(new LocalizedString(name, name)); } } } }
public async Task Invoke(HttpContext context) { using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_loginTimings)) { UserSession userSession = GetUserSession(context); if (userSession != null && String.IsNullOrEmpty(userSession.UserName) && CookieExists(context, _loginControllerSettings.RememberMeCookieName)) { using (StopWatchTimer stopwatchAutoLogin = StopWatchTimer.Initialise(_autoLoginTimings)) { string cookieValue = CookieValue(context, _loginControllerSettings.RememberMeCookieName, _loginControllerSettings.EncryptionKey, String.Empty); if (Int64.TryParse(cookieValue, out long userId)) { UserLoginDetails loginDetails = new UserLoginDetails(userId, true); LoginResult loginResult = _loginProvider.Login(String.Empty, String.Empty, base.GetIpAddress(context), 1, ref loginDetails); if (loginResult == LoginResult.Remembered) { userSession.Login(userId, loginDetails.Username, loginDetails.Email); await _authenticationService.SignInAsync(context, _loginControllerSettings.AuthenticationScheme, new ClaimsPrincipal(_claimsProvider.GetUserClaims(loginDetails.UserId)), _claimsProvider.GetAuthenticationProperties()); } else { CookieDelete(context, _loginControllerSettings.RememberMeCookieName); } } else { CookieDelete(context, _loginControllerSettings.RememberMeCookieName); } } } } await _next(context); }
public double[] SolveLinearSystemForwardEliminationAndBackSubstitution(double[] RightHandSide) { WriteToDisplay.WriteInfo("\n Solving linear system using link-list storage method and PLU decomposition\n\n"); WriteToDisplay.WriteInfo(" Number of equations = " + n.ToString() + "\n"); StopWatchTimer Totaltime = new StopWatchTimer(); Totaltime.StartTimer(); StopWatchTimer timer = new StopWatchTimer(); //rightHandSide = RightHandSide; //ScaleAllRowsAndRightHandSideAndRemoveZeros(); //this.RemoveAllZeros(); // PLU decomposition timer.StartTimer(); //this.LUDecomposition(); timer.StopTimer(); WriteToDisplay.WriteInfo(" PLU decomposition time = " + timer.TimeElapsedInSeconds().ToString() + "\n"); // Forward elimination timer.StartTimer(); this.ForwardElimination(RightHandSide); timer.StopTimer(); WriteToDisplay.WriteInfo(" Forward elimination time = " + timer.TimeElapsedInSeconds().ToString() + "\n"); //Backward elimination timer.StartTimer(); this.BackSubstitution(); timer.StopTimer(); WriteToDisplay.WriteInfo(" Backward elimination time = " + timer.TimeElapsedInSeconds().ToString() + "\n"); // Determinant timer.StartTimer(); this.CalculateDeterminant(); timer.StopTimer(); WriteToDisplay.WriteInfo(" Determinant time = " + timer.TimeElapsedInSeconds().ToString() + "\n"); Totaltime.StopTimer(); WriteToDisplay.WriteInfo("\n Total time to solve = " + Totaltime.TimeElapsedInSeconds().ToString() + "\n\n"); return(rightHandSide); }
protected async Task Processing() { StopWatchTimer.Start(); TimeSpan?next = null; TimeSpan now; do { await BenchmarkingTarget(); Iterations++; now = StopWatchTimer.Elapsed; next = now > next ? now + PerfCollector.TryRead(): next ?? (now + PerfCollector.TryRead()); } while (now < TimeSpan); StopWatchTimer.Stop(); ElapsedMilliseconds = StopWatchTimer.ElapsedMilliseconds; StopWatchTimer = null; }
public override void SolveFEMSystem_Parallel() { //Set up the load vector and stiffness matrix int NDF = Unknowns_NDoF; //Get the size of the unknowns temperature (one per node) Vector F = new Vector(NDF); //Make global load vector MatrixSparseLinkedList K = new MatrixSparseLinkedList(NDF); // Make global stiffness matrix //Assemble F and K int NE = Elements.Length; //Get the number of elements ParallelOptions op = new ParallelOptions(); op.MaxDegreeOfParallelism = Environment.ProcessorCount; Timer_Assemble = new StopWatchTimer(); Timer_Assemble.StartTimer(); Parallel.For(0, NE, op, i => { Vector Fe = Elements[i].Calculate_Fe(); Matrix_Jagged Ke = Elements[i].Calculate_Ke(); lock (K_Lock) { Elements[i].Assemble(ref K, Ke); } lock (F_Lock) { Elements[i].Assemble(ref F, Fe); } }); //Adjust for boundary conditions int NBE = BoundaryElements.Length; for (int i = 0; i < NBE; i++) { BoundaryElements[i].AdjustFAndK(ref F, ref K); } Timer_Assemble.StopTimer(); Timer_Solve = new StopWatchTimer(); Timer_Solve.StartTimer(); //Solve system U = new Vector(); U.Values = K.SolveLinearSystem_Parallel(F.Values); Timer_Solve.StopTimer(); }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (_settings.Enabled) { string route = RouteLowered(context); if (route.StartsWith("/smoketest/")) { using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { if (route.Equals("/smoketest/siteid/")) { byte[] siteId = Encoding.UTF8.GetBytes( Encrypt(String.Join(';', _settings.SiteId), _settings.EncryptionKey)); await context.Response.Body.WriteAsync(siteId, 0, siteId.Length); } else if (route.Equals("/smoketest/start/")) { ISmokeTestProvider smokeTestProvider = context.RequestServices .GetService(typeof(ISmokeTestProvider)) as ISmokeTestProvider; if (smokeTestProvider != null) { NVPCodec codec = smokeTestProvider.SmokeTestStart(); if (codec != null) { byte[] testNVPData = Encoding.UTF8.GetBytes( Encrypt(codec.Encode(), _settings.EncryptionKey)); await context.Response.Body.WriteAsync(testNVPData, 0, testNVPData.Length); } } } else if (route.Equals("/smoketest/count/")) { byte[] siteId = Encoding.UTF8.GetBytes( Encrypt(SmokeTests.Count.ToString(), _settings.EncryptionKey)); await context.Response.Body.WriteAsync(siteId, 0, siteId.Length); } else if (route.StartsWith("/smoketest/test")) { string testNumber = route.Substring(16); List <WebSmokeTestItem> testItems = SmokeTests; if (Int32.TryParse(testNumber, out int number) && number >= 0 && number < testItems.Count) { context.Response.ContentType = "application/json"; byte[] testData = Encoding.UTF8.GetBytes( Encrypt(JsonConvert.SerializeObject(testItems[number]), _settings.EncryptionKey)); await context.Response.Body.WriteAsync(testData, 0, testData.Length); } else { context.Response.StatusCode = 400; } } else if (route.Equals("/smoketest/end/")) { ISmokeTestProvider smokeTestProvider = context.RequestServices .GetService(typeof(ISmokeTestProvider)) as ISmokeTestProvider; if (smokeTestProvider != null) { smokeTestProvider.SmokeTestEnd(); } } else { context.Response.StatusCode = 404; } return; } } } await _next(context); }
//Pause Button private void button1_Click(object sender, EventArgs e) { StopWatchTimer.Stop(); }
public async Task Invoke(HttpContext context) { string fileExtension = RouteFileExtension(context); if (!_processStaticFiles && !String.IsNullOrEmpty(fileExtension) && _staticFileExtensions.Contains($"{fileExtension};")) { await _next(context); return; } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { string route = RouteLowered(context); if (route.EndsWith("/robots.txt")) { context.Response.StatusCode = 200; // prepend sitemaps if there are any object notificationResult = new object(); if (_notificationService.RaiseEvent(Constants.NotificationSitemapNames, context, null, ref notificationResult)) { string[] sitemaps = ((System.Collections.IEnumerable)notificationResult) .Cast <object>() .Select(x => x.ToString()) .ToArray(); if (sitemaps != null) { StringBuilder stringBuilder = new StringBuilder(); string url = GetHost(context); for (int i = 0; i < sitemaps.Length; i++) { stringBuilder.Append($"Sitemap: {url}{sitemaps[i].Substring(1)}\r\n\r\n"); } await context.Response.WriteAsync(stringBuilder.ToString()); } } context.Response.Body.Write(_spiderData, 0, _spiderData.Length); } else { if (_userSessionManagerLoaded) { if (context.Items.ContainsKey(Constants.UserSession)) { try { UserSession userSession = (UserSession)context.Items[Constants.UserSession]; foreach (DeniedRoute deniedRoute in _deniedSpiderRoutes) { if (userSession.IsBot && deniedRoute.Route.StartsWith(route) && ( deniedRoute.UserAgent == "*" || #if NET_CORE userSession.UserAgent.Contains(deniedRoute.UserAgent, StringComparison.CurrentCultureIgnoreCase) #else userSession.UserAgent.ToLower().Contains(deniedRoute.UserAgent.ToLower()) #endif )) { context.Response.StatusCode = 403; return; } } } catch (Exception err) { _logger.AddToLog(LogLevel.Error, nameof(SpiderMiddleware), err, MethodBase.GetCurrentMethod().Name); } } } } } await _next(context); }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } string fileExtension = RouteFileExtension(context); if (!String.IsNullOrEmpty(fileExtension) && _staticFileExtensions.Contains($"{fileExtension};")) { await _next(context); return; } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { string route = RouteLowered(context); if (route.Length > 1 && route[route.Length - 1] == Constants.ForwardSlashChar) { route = route.Substring(0, route.Length - 1); } try { bool found = false; if (_breadcrumbRoutes.ContainsKey(route)) { context.Items.Add(Constants.Breadcrumbs, GetBreadCrumbs(route, _breadcrumbRoutes[route].Breadcrumbs, String.Empty)); found = true; } else { foreach (KeyValuePair <string, BreadcrumbRoute> kvp in _breadcrumbRoutes) { if (route.StartsWith(kvp.Value.PartialRoute) && kvp.Value.HasParameters) { context.Items.Add(Constants.Breadcrumbs, GetBreadCrumbs(route, kvp.Value.Breadcrumbs, Route(context).Substring(kvp.Value.PartialRoute.Length - 1))); found = true; break; } } } if (!found) { BreadcrumbItem homeBreadCrumb; if (_stringLocalizer != null) { homeBreadCrumb = new BreadcrumbItem(_stringLocalizer[_homeBreadCrumb.Name], _homeBreadCrumb.Route, _homeBreadCrumb.HasParameters); } else { homeBreadCrumb = _homeBreadCrumb; } context.Items.Add(Constants.Breadcrumbs, new List <BreadcrumbItem>() { homeBreadCrumb }); } } catch (Exception err) { _logger.AddToLog(LogLevel.Error, nameof(BreadcrumbMiddleware), err, MethodBase.GetCurrentMethod().Name); } } await _next(context); }
public async Task Invoke(HttpContext context) { string fileExtension = base.RouteFileExtension(context); // if it's a static file, don't add user session data to the context if (!String.IsNullOrEmpty(fileExtension) && _staticFileExtension.Contains($"{fileExtension};")) { await _next(context); return; } using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings)) { string cookieSessionID; CookieOptions options = new CookieOptions() { HttpOnly = false }; if (context.Request.Cookies.ContainsKey(_cookieName)) { cookieSessionID = Shared.Utilities.Decrypt(context.Request.Cookies[_cookieName], _cookieEncryptionKey); context.Response.Cookies.Append(_cookieName, Shared.Utilities.Encrypt(cookieSessionID, _cookieEncryptionKey), options); } else { cookieSessionID = GetNextID(); context.Response.Cookies.Append(_cookieName, Shared.Utilities.Encrypt(cookieSessionID, _cookieEncryptionKey), options); } CacheItem currentSession = UserSessionManager.UserSessions.Get(cookieSessionID); UserSession userSession; if (currentSession != null) { userSession = (UserSession)currentSession.Value; } else { userSession = GetUserSession(context, cookieSessionID); GetSessionCulture(context, userSession); } string referrer = context.Request.Headers[Constants.PageReferer]; userSession.PageView(GetAbsoluteUri(context).ToString(), referrer ?? String.Empty, false); context.Items.Add(Constants.UserSession, userSession); context.Items.Add(Constants.UserCulture, userSession.Culture); string route = RouteLowered(context); bool loggedIn = !String.IsNullOrEmpty(userSession.UserName); // is the route a loggedin/loggedout route RouteData partialMatch = null; foreach (RouteData routeData in _routeData) { if (routeData.Matches(route)) { if (routeData.Ignore) { partialMatch = null; } else { partialMatch = routeData; } break; } if (partialMatch == null && route.StartsWith(routeData.Route)) { partialMatch = routeData; } } // if we have a match check if we need to redirect if (partialMatch != null) { if (!partialMatch.LoggedIn && loggedIn) { context.Response.Redirect(partialMatch.RedirectPath, false); return; } else if (partialMatch.LoggedIn && !loggedIn) { context.Response.Redirect($"{partialMatch.RedirectPath}?returnUrl={context.Request.Path.ToString()}", false); return; } } } await _next(context); }
public void TestStopWatch() { Console.WriteLine(StopWatchTimer.Start()); Thread.Sleep(7000); Console.WriteLine(StopWatchTimer.Stop()); }