public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { ISessionFeature session = null; try { //Any application messages, clear them out session = context.HttpContext.Features.Get <ISessionFeature>(); if (session != null && session.Session.IsAvailable) { session.Session.Remove("application-message"); } } catch (Exception e) { await raven.CaptureNetCoreEventAsync(e); } //Execute the action method await next(); try { //Any application messages, add to session so they can be retrieved after any redirects var messages = context.HttpContext.Features.Get <ApplicationMessageFeature>(); if (messages != null && session != null && session.Session.IsAvailable) { session.Session.Set("application-message", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messages))); } } catch (Exception e) { await raven.CaptureNetCoreEventAsync(e); } }
public async Task TransactionAsync(Action <NpgsqlTransaction> func) { try { using (var connection = this.Connect()) { await connection.OpenAsync(); var transaction = connection.BeginTransaction(); func(transaction); try { await transaction.CommitAsync(); } catch (Exception e) { await transaction.RollbackAsync(); throw e; } } } catch (Exception e) { var sentry = new SentryEvent(e); await raven.CaptureNetCoreEventAsync(sentry); } }
public override async Task <ItemDetail> SearchItem(SingleItemRequest item) { if (item.ID.EmptyOrNull() && item.Title.EmptyOrNull()) { if (item.Link.EmptyOrNull()) { throw new AllowedException("ID, Title and Link cannot be empty"); } item = new AliexpressQueryString().DecodeItemLink(item.Link); //Means there was a translation error in the URI format if (item.ID.EmptyOrNull() & item.Title.EmptyOrNull()) { return(null); } } string endpoint = SearchEndpoints.AliexpressItemUrl(item.Title, item.ID); var response = ""; ItemDetail detail = null; try { var responseMessage = await http.Get(endpoint); response = await responseMessage.Content.ReadAsStringAsync(); } catch (Exception e) { } try { detail = new AliexpressPageDecoder().ScrapeSingleItem(response); var freights = await CalculateFreight(new FreightAjaxRequest() { ProductID = item.ID, Country = item.ShipCountry, CurrencyCode = "USD" }); if (freights.Length > 0) { var def = freights.FirstOrDefault(x => x.IsDefault == true); detail.ShippingPrice = def.LocalPrice; detail.ShippingType = def.CompanyDisplayName; } } catch (Exception e) { await raven.CaptureNetCoreEventAsync(e); } return(detail); }
public async Task Invoke(HttpContext context) { try { logger.LogInformation($"{context.Request.Path}\tRECEIVED"); var sw = new Stopwatch(); sw.Start(); //Log activty through Sentry Breadcrumb var crumb = new Breadcrumb("LoggerMiddleware"); crumb.Message = $"{context.Request.Method} {context.Request.Path}{context.Request.QueryString.ToUriComponent()}"; crumb.Data = new Dictionary <string, string>() { { "IsAuthenticated", context.User.Identity.IsAuthenticated.ToString() }, { "Authentication", context.User.Identity.IsAuthenticated ? context.User.Identity.Name : "Unknown" } }; raven.AddTrail(crumb); //Log activty through API var activity = new LoggingActivityModel() { IP = context.Connection.RemoteIpAddress == null ? "N/A" : context.Connection.RemoteIpAddress.ToString(), User = (context.User.Identity.IsAuthenticated == false) ? "Guest" : context.User.FindFirst(ClaimTypes.Name).Value, Request = context.Request.Path }; AppTask.Forget(() => appLogging.LogActivity(activity)); //Start processing the request try { await _next.Invoke(context); } catch (Exception e) { //Allow Postgres to receive querystring var feature = new LoggerFeature() { Path = context.Request.Path + context.Request.QueryString.ToString() }; context.Features.Set <LoggerFeature>(feature); //Try to send the request to Sentry await raven.CaptureNetCoreEventAsync(e); //rethrow so we can redirect to Error page throw e; } //Stop request timing and output time sw.Stop(); logger.LogInformation($"{context.Request.Path}\t{sw.Elapsed.TotalMilliseconds}(ms)"); } catch (Exception e) { //Try to send the request to Sentry await raven.CaptureNetCoreEventAsync(e); } }
public async Task <IActionResult> Error([FromServices] ILoggingService logging) { try { var error = HttpContext.Features.Get <IExceptionHandlerFeature>().Error; var path = HttpContext.Features.Get <AliseeksFE.Middleware.LoggerFeature>().Path; var model = new LoggingExceptionModel() { Criticality = 5, Message = $"Query: {path}\n{error.Message}", StackTrace = error.StackTrace }; await logging.LogException(model); await raven.CaptureNetCoreEventAsync(error); } catch (Exception e) { logger.LogError(new EventId(501), e, "ERROR IN ERROR LOGGER"); } return(View()); }
public string GenerateToken(Claim[] claims) { var securityKey = System.Text.Encoding.ASCII.GetBytes(jwtOptions.SecretKey); var handler = new JwtSecurityTokenHandler(); var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(claims), Issuer = "AliseeksIssuer", Audience = "AliseeksUser", Expires = DateTime.Now.AddDays(14), NotBefore = now, IssuedAt = now, SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(securityKey), SecurityAlgorithms.HmacSha256) }; try { var token = handler.CreateToken(tokenDescriptor); var tokenString = handler.WriteToken(token); return(tokenString); } catch (Exception e) { var sentry = new SentryEvent(e); raven.CaptureNetCoreEventAsync(sentry).Wait(); //blocking i/o throw e; } }
public async Task Invoke(HttpContext context) { logger.LogInformation($"{context.Request.Path}\tRECEIVED"); var sw = new Stopwatch(); sw.Start(); var crumb = new Breadcrumb("LoggerMiddleware"); crumb.Message = $"{context.Request.Method} {context.Request.Path}{context.Request.QueryString.ToUriComponent()}"; crumb.Data = new Dictionary <string, string>() { { "IsAuthenticated", context.User.Identity.IsAuthenticated.ToString() }, { "Authentication", context.User.Identity.IsAuthenticated ? context.User.Identity.Name : "Unknown" } }; raven.AddTrail(crumb); try { await _next.Invoke(context); } catch (Exception e) { //Log exception with RavenClient await raven.CaptureNetCoreEventAsync(e); } sw.Stop(); logger.LogInformation($"{context.Request.Path}\t{sw.Elapsed.TotalMilliseconds}(ms)"); }
public async Task SendPasswordResetTo(PasswordResetModel model) { try { using (var stream = new StreamReader(File.OpenRead(Directory.GetCurrentDirectory() + templatePasswordReset))) { var template = stream.ReadToEnd(); template = template.Replace("{{product_name}}", "Aliseeks"); template = template.Replace("{{name}}", model.Name); template = template.Replace("{{action_url}}", model.ActionUrl); template = template.Replace("{{sender_name}}", "Alex"); await sendMail(template, model.Subject, model.ToAddress); } } catch (Exception e) { var sentry = new SentryEvent(e); await raven.CaptureNetCoreEventAsync(sentry); } }
public async Task Invoke(HttpContext context) { try { await _next.Invoke(context); } catch (Exception ex) { logger.LogError(0, ex, "An unhandled exception has occured: " + ex.Message); //If response has not been started, send back a 500 if (!context.Response.HasStarted) { context.Response.StatusCode = 500; await context.Response.WriteAsync("An unhandled exception in the API has occured."); } //Log the error into our DB ExceptionLogModel model = new ExceptionLogModel() { Criticality = 10, Message = ex.Message, StackTrace = ex.StackTrace }; var sentry = new SentryEvent(ex) { Extra = new { Request = context.Request.Path.ToString(), QueryString = context.Request.QueryString.ToUriComponent() } }; try { await raven.CaptureNetCoreEventAsync(sentry); } catch (Exception e) { logger.LogError(0, e, "Error sending RavenClient error"); } try { await dbLog.LogException(model); } catch (Exception e) { logger.LogError(0, e, "Error logging exception: " + e.Message); } } }
public async Task InsertFeedback(FeedbackModel model) { try { var command = new NpgsqlCommand(); var commandParameters = "@message, @email"; command.CommandText = $"INSERT INTO {feedbackTable} ({feedbackColumns}) VALUES ({commandParameters});"; command.Parameters.AddWithValue("@message", model.Message); command.Parameters.AddWithValue("@email", model.Email); await db.CommandNonqueryAsync(command); } catch (Exception e) { await raven.CaptureNetCoreEventAsync(e); } }
public async Task CacheSearch(SearchCriteria criteria, WebSearchService[] services, SearchResultOverview result) { var key = RedisKeyConvert.Serialize(criteria); //Cache the search & service models try { await cacheItemSearch(criteria, result); await cacheServices(services); } catch (Exception e) { var sentry = new SentryEvent(e); sentry.Message = $"Error when saving to cache: {e.Message}"; await raven.CaptureNetCoreEventAsync(sentry); } }
public async Task <SearchResultOverview> SearchItems(SearchCriteria search) { //Check for cached item list string key = RedisKeyConvert.Serialize(search); SearchResultOverview result = null; try { storeSearchHistory(search); if (await cache.Exists(key)) { var cachedResult = JsonConvert.DeserializeObject <SearchResultOverview>(await cache.GetString(key)); result = cachedResult; } else { await SearchServiceProvider.RetrieveSearchServices(services, cache, search, allNew : true); var results = await SearchDispatcher.Search(services, new int[] { search.Page }); var formattedResults = SearchFormatter.FormatResults(0, results); await searchCache.CacheSearch(search, services, formattedResults.Results); result = formattedResults.Results; } searchCache.StartCacheJob(search, null); } catch (Exception e) { await raven.CaptureNetCoreEventAsync(e); } return(result); }
async Task <HttpResponseMessage> sendRequest(HttpRequestMessage request, Action <HttpClient> clientConfig = null) { var response = new HttpResponseMessage(System.Net.HttpStatusCode.ServiceUnavailable); using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(apiAddress); try { await preRequest(request); if (clientConfig != null) { clientConfig(client); } response = await client.SendAsync(request); await postRequest(response); } catch (HttpRequestException e) { await raven.CaptureNetCoreEventAsync(e); logger.LogCritical(new EventId(502), e, $"Aliseeks API Service is unavailable at {request.RequestUri.ToString()}"); } catch (Exception e) { await raven.CaptureNetCoreEventAsync(e); logger.LogError(new EventId(503), e, $"Unknown Aliseeks API Service error when requesting {request.RequestUri.ToString()}"); } } //Show message to user when API issues are occuring switch (response.StatusCode) { case System.Net.HttpStatusCode.BadGateway: if (context != null) { context.Features.Set <ApplicationMessageFeature>(new ApplicationMessageFeature() { Message = ApiUnavailableMessage, Level = Category.Danger }); } break; case System.Net.HttpStatusCode.BadRequest: if (context != null) { context.Features.Set <ApplicationMessageFeature>(new ApplicationMessageFeature() { Message = ApiUnavailableMessage, Level = Category.Danger }); } break; case System.Net.HttpStatusCode.ServiceUnavailable: if (context != null) { context.Features.Set <ApplicationMessageFeature>(new ApplicationMessageFeature() { Message = ApiUnavailableMessage, Level = Category.Danger }); } break; } return(response); }
public override async Task <SearchResultOverview> SearchItems() { var search = this.ServiceModel; string endpoint = String.Empty; string pagingKey = search.PageKey; var resultTasks = new List <Task <string> >(); SearchResultOverview overallResult = null; //Get the first page if we have no pagekey if (this.ServiceModel.PageKey == null || this.ServiceModel.PageKey == String.Empty) { endpoint = new DHGateQueryString().Convert(search.Criteria); try { var response = await(await http.Get(endpoint)).Content.ReadAsStringAsync(); overallResult = new DHGatePageDecoder().DecodePage(response); this.ServiceModel.PopulateState(overallResult); } catch (Exception e) { await raven.CaptureNetCoreEventAsync(e); return(new SearchResultOverview()); } } foreach (int page in search.Pages) { if (page < search.Page) { continue; } if (page == 0) { continue; } search.Page = page; endpoint = new DHGateQueryString().ConvertWithPage(search, this.ServiceModel.PageKey); try { resultTasks.Add((await http.Get(endpoint)).Content.ReadAsStringAsync()); } catch (Exception e) { await raven.CaptureNetCoreEventAsync(e); } } var responses = await Task.WhenAll(resultTasks); foreach (var response in responses) { var oneResult = new DHGatePageDecoder().DecodePage(response); if (overallResult == null) { overallResult = oneResult; this.ServiceModel.PopulateState(oneResult); } else { overallResult.Items.AddRange(oneResult.Items); } } return((overallResult != null) ? overallResult : new SearchResultOverview()); }
public async Task <BaseServiceResponse> Register(UserNewModel model) { var response = new BaseServiceResponse(); if (model.Username == null || model.Password == null || model.Email == null) { return(response); } model.Username = model.Username.ToLower(); model.Email = model.Email.ToLower(); //Convert to new User Model var userModel = new UserModel() { Username = model.Username.ToLower(), Password = model.Password, Email = model.Email.ToLower(), Meta = new UserMetaModel() { PrimaryUse = model.PrimaryUse, Referral = model.Referral } }; var hash = hasher.Hash(userModel.Password); userModel.Password = hash.Hash; userModel.Salt = hash.Salt; var exists = await db.Exists(userModel); if (exists.Email == model.Email) { return new BaseServiceResponse() { Code = 409, Message = "Email already in use" } } ; else if (exists.Username == model.Username) { return new BaseServiceResponse() { Code = 409, Message = "Username already in use" } } ; try { await db.InsertAsync(userModel); } catch (PostgresDuplicateValueException e) { var sentry = new SentryEvent(e); await raven.CaptureNetCoreEventAsync(sentry); //Should not get this exception throw e; } catch (Exception e) { var sentry = new SentryEvent(e); await raven.CaptureNetCoreEventAsync(sentry); } AppTask.Forget(() => email.SendWelcomeTo(new WelcomeModel() { Address = userModel.Email, Subject = "Welcome to Aliseeks", User = userModel.Username })); return(response); }