/// <summary> /// Wraps the exception. /// </summary> /// <param name="func">The function.</param> /// <param name="logger">The logger.</param> /// <exception cref="HttpResponseException"> /// </exception> public static void WrapException(Action func, ILoggingService logger) { try { func(); } catch (ArgumentNullException ex) { logger?.Error(ex); throw new HttpResponseException(HttpStatusCode.ExpectationFailed); } catch (NotImplementedException ex) { logger?.Error(ex); throw new HttpResponseException(HttpStatusCode.NotImplemented); } catch (ArgumentOutOfRangeException ex) { logger?.Error(ex); throw new HttpResponseException(HttpStatusCode.ExpectationFailed); } catch (Exception ex) { logger?.Error(ex); throw new HttpResponseException(HttpStatusCode.InternalServerError); } }
/// <summary> /// Handles the Error event of the Application control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Application_Error(object sender, EventArgs e) { Exception exc = Server.GetLastError(); _logger?.Error(exc, "Application Error"); Server.ClearError(); }
public async Task <WrapResult <T> > TryWithErrorHandlingAsync <T>( Func <Task <T> > task, Func <Exception, Task <bool> > customErrorHandler = null) { var result = WrapResult <T> .Failed; bool keepTrying; whenStarting?.Invoke(); if (!connectivityService.IsThereInternet) { loggingService?.Warning("There's no Internet access"); return(result); } do { keepTrying = false; try { T actualResult = await task(); result = new WrapResult <T>(actualResult, true); } catch (HttpRequestException exception) { loggingService?.Warning($"{exception}"); if (customErrorHandler == null || !await customErrorHandler?.Invoke(exception)) { await Application.Current.MainPage.DisplayAlert( Resources.Alert_Title_UnexpectedError, Resources.Alert_Message_InternetError, Resources.Alert_OK_OKEllipsis); } } catch (TaskCanceledException exception) { loggingService?.Debug($"{exception}"); } catch (Exception exception) { loggingService?.Error(exception); if (customErrorHandler == null || !await customErrorHandler?.Invoke(exception)) { await Application.Current.MainPage.DisplayAlert( Resources.Alert_Title_UnexpectedError, Resources.Alert_Message_InternetError, Resources.Alert_OK_OKEllipsis); } } }while (keepTrying); whenFinished?.Invoke(); return(result); }
public async Task <Result <T> > TryWithErrorHandlingAsync <T>( Task <T> task, Func <Exception, Task <bool> > customErrorHandler = null) { whenStarting?.Invoke(); if (!connectivityService.IsThereInternet) { loggingService?.Warning("There's no Internet access"); return(Error()); } try { T actualResult = await task; return(Ok(actualResult)); } catch (HttpRequestException exception) { loggingService?.Warning($"{exception}"); if (customErrorHandler == null || !await customErrorHandler?.Invoke(exception)) { await Application.Current.MainPage.DisplayAlert( "Unexpected Error", //Resources.Alert_Title_UnexpectedError, "Internet Error", //Resources.Alert_Message_InternetError, "OK..."); //Resources.Alert_OK_OKEllipsis); } } catch (TaskCanceledException exception) { loggingService?.Debug($"{exception}"); } catch (Exception exception) { loggingService?.Error(exception); if (customErrorHandler == null || !await customErrorHandler?.Invoke(exception)) { await Application.Current.MainPage.DisplayAlert( "Unexpected Error", //Resources.Alert_Title_UnexpectedError, "Internet Error", //Resources.Alert_Message_InternetError, "OK..."); //Resources.Alert_OK_OKEllipsis); } } finally { whenFinished?.Invoke(); } return(Error()); }
public async Task <Result <T> > TryWithErrorHandlingAsync <T>( Task <T> task, Func <Exception, Task <bool> > customErrorHandler = null) { whenStarting?.Invoke(); if (!connectivityService.IsThereInternet) { loggingService?.Warning("There's no Internet access"); return(Error()); } try { T actualResult = await task; return(Ok(actualResult)); } catch (HttpRequestException exception) { loggingService?.Warning($"{exception}"); if (customErrorHandler == null || !await customErrorHandler?.Invoke(exception)) { await dialogService.ShowAlertAsync( Resources.AppResources.AlertTitleUnexpectedError, Resources.AppResources.AlertMessageInternetError, Resources.AppResources.AlertOKEllipsis); } } catch (TaskCanceledException exception) { loggingService?.Debug($"{exception}"); } catch (Exception exception) { loggingService?.Error(exception); if (customErrorHandler == null || !await customErrorHandler?.Invoke(exception)) { await dialogService.ShowAlertAsync( Resources.AppResources.AlertTitleUnexpectedError, Resources.AppResources.AlertMessageInternetError, Resources.AppResources.AlertOKEllipsis); } } finally { whenFinished?.Invoke(); } return(Error()); }
public async Task <Result <T> > TryExecuteAsync <T>(Func <Task <T> > task) { if (checkInternetAccess) { bool abort = await ExecuteInternetAccessLoopAsync(); if (abort) { return(Error()); } } whenStarting?.Invoke(); Result <T> result = Error(); try { var actualResult = await task(); result = Ok(actualResult); } catch (Exception exception) { logger?.Error(exception); var isAlreadyHandled = false; if (errorHandler != null) { isAlreadyHandled = await errorHandler.Invoke(exception); } if (!isAlreadyHandled) { isAlreadyHandled = await HandleCommonExceptionsAsync(exception); } if (!isAlreadyHandled) { throw; } } finally { whenFinished?.Invoke(); } return(result); }
public async Task Login(bool force = false) { _log.Debug($"DVBStreamer login"); if (String.IsNullOrEmpty(_url)) { _status = StatusEnum.EmptyCredentials; return; } try { var res = await SendRequest(new Dictionary <string, string> { { "action", "getServiceState" } }); var resJson = JObject.Parse(res); // get session key: if ( resJson.HasValue("serviceState") ) { _status = StatusEnum.Logged; } else { _status = StatusEnum.ConnectionNotAvailable; } } catch (Exception wex) { _log.Error(wex, "Login failed"); _status = StatusEnum.ConnectionNotAvailable; } }
/// <inheritdoc /> public async Task <IPipelineProcess <Post> > Process(IPipelineProcess <Post> input, IMvcForumContext context) { _roleService.RefreshContext(context); _localizationService.RefreshContext(context); try { // Get the Current user from ExtendedData var username = input.ExtendedData[Constants.ExtendedDataKeys.Username] as string; // IS this an existing topic var existingPost = await context.Post.Include(x => x.User) .FirstOrDefaultAsync(x => x.Id == input.EntityToProcess.Id); input.ExtendedData.Add(Constants.ExtendedDataKeys.IsEdit, existingPost != null); // See if we can get the username if (!string.IsNullOrWhiteSpace(username)) { // Get logged on user var loggedOnUser = await context.MembershipUser.FirstOrDefaultAsync(x => x.UserName == username); if (loggedOnUser != null) { // Users role var loggedOnUsersRole = GetGroupMembershipRole(input.EntityToProcess.Topic.Group.Id, loggedOnUser); // Get the permissions and add to extendeddata as we'll use it again var permissions = _roleService.GetPermissions(input.EntityToProcess.Topic.Group, loggedOnUsersRole); input.ExtendedData.Add(Constants.ExtendedDataKeys.PermissionSet, permissions); // Check this users role has permission to create a post if (permissions[ForumConfiguration.Instance.PermissionDenyAccess].IsTicked || permissions[ForumConfiguration.Instance.PermissionReadOnly].IsTicked) { input.AddError(_localizationService.GetResourceString("Errors.NoPermission")); return(input); } // Files? Check and then check permissions if (input.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.PostedFiles)) { if (permissions[ForumConfiguration.Instance.PermissionAttachFiles].IsTicked == false) { // Not allowed to upload files input.AddError(_localizationService.GetResourceString("Errors.NoPermission")); return(input); } } // What if this is an edit if (existingPost != null) { if (existingPost.User.Id != loggedOnUser.Id && !permissions[ForumConfiguration.Instance.PermissionEditPosts].IsTicked) { // Not allowed to edit this post input.AddError(_localizationService.GetResourceString("Errors.NoPermission")); return(input); } } } else { input.AddError("Unable to get user from username"); return(input); } } else { input.AddError("Unable to get username"); return(input); } } catch (System.Exception ex) { input.AddError(ex.Message); _loggingService.Error(ex); } return(input); }
/// <inheritdoc /> public async Task <IPipelineProcess <MembershipUser> > Process(IPipelineProcess <MembershipUser> input, IMvcForumContext context) { _localizationService.RefreshContext(context); _membershipService.RefreshContext(context); try { var username = input.ExtendedData[Constants.ExtendedDataKeys.Username] as string; var password = input.ExtendedData[Constants.ExtendedDataKeys.Password] as string; // Validate login if (_membershipService.ValidateUser(username, password, Membership.MaxInvalidPasswordAttempts)) { // Set last login date as users details are ok input.EntityToProcess = await context.MembershipUser.FirstOrDefaultAsync(x => x.UserName == username); if (input.EntityToProcess.IsApproved && !input.EntityToProcess.IsLockedOut && !input.EntityToProcess.IsBanned) { input.EntityToProcess.LastLoginDate = DateTime.Now; input.Successful = true; return(input); } input.Successful = false; input.ProcessLog.Clear(); if (input.EntityToProcess.IsLockedOut) { input.ProcessLog.Add(_localizationService.GetResourceString("Members.Errors.UserLockedOut")); } if (!input.EntityToProcess.IsApproved) { input.ProcessLog.Add(_localizationService.GetResourceString("Members.Errors.UserNotApproved")); } if (input.EntityToProcess.IsBanned) { input.ProcessLog.Add(_localizationService.GetResourceString("Members.NowBanned")); } } else { // get here Login failed, check the login status var loginStatus = _membershipService.LastLoginStatus; input.Successful = false; input.ProcessLog.Clear(); switch (loginStatus) { case LoginAttemptStatus.UserNotFound: case LoginAttemptStatus.PasswordIncorrect: input.ProcessLog.Add(_localizationService.GetResourceString("Members.Errors.PasswordIncorrect")); break; case LoginAttemptStatus.PasswordAttemptsExceeded: input.ProcessLog.Add(_localizationService.GetResourceString("Members.Errors.PasswordAttemptsExceeded")); break; case LoginAttemptStatus.UserLockedOut: input.ProcessLog.Add(_localizationService.GetResourceString("Members.Errors.UserLockedOut")); break; case LoginAttemptStatus.Banned: input.ProcessLog.Add(_localizationService.GetResourceString("Members.NowBanned")); break; case LoginAttemptStatus.UserNotApproved: input.ProcessLog.Add(_localizationService.GetResourceString("Members.Errors.UserNotApproved")); break; default: input.ProcessLog.Add(_localizationService.GetResourceString("Members.Errors.LogonGeneric")); break; } } } catch (Exception ex) { input.AddError(ex.Message); _loggingService.Error(ex); } return(input); }
/// <inheritdoc /> public async Task <IPipelineProcess <MembershipUser> > Process(IPipelineProcess <MembershipUser> input, IMvcForumContext context) { _voteService.RefreshContext(context); _notificationService.RefreshContext(context); _favouriteService.RefreshContext(context); _membershipUserPointsService.RefreshContext(context); _activityService.RefreshContext(context); _pollService.RefreshContext(context); _topicService.RefreshContext(context); _groupService.RefreshContext(context); _postService.RefreshContext(context); try { // Delete all topics var topics = input.EntityToProcess.Topics; if (topics != null && topics.Any()) { var topicList = new List <Topic>(); topicList.AddRange(topics); foreach (var topic in topicList) { var topicDeleteResult = await _topicService.Delete(topic); if (!topicDeleteResult.Successful) { input.AddError(topicDeleteResult.ProcessLog.FirstOrDefault()); return(input); } } input.EntityToProcess.Topics.Clear(); await context.SaveChangesAsync(); } // Now sorts Last Posts on topics and delete all the users posts var posts = input.EntityToProcess.Posts; if (posts != null && posts.Any()) { var postIds = posts.Select(x => x.Id).ToList(); // Get all Groups var allGroups = _groupService.GetAll(input.EntityToProcess.Id); // Need to see if any of these are last posts on Topics // If so, need to swap out last post var lastPostTopics = _topicService.GetTopicsByLastPost(postIds, allGroups.ToList()); foreach (var topic in lastPostTopics.Where(x => x.User.Id != input.EntityToProcess.Id)) { var lastPost = topic.Posts.Where(x => !postIds.Contains(x.Id)) .OrderByDescending(x => x.DateCreated) .FirstOrDefault(); topic.LastPost = lastPost; } await context.SaveChangesAsync(); // Delete all posts var postList = new List <Post>(); postList.AddRange(posts); foreach (var post in postList) { // Delete post via pipeline var postDeleteResult = await _postService.Delete(post, true); if (!postDeleteResult.Successful) { input.AddError(postDeleteResult.ProcessLog.FirstOrDefault()); return(input); } } input.EntityToProcess.UploadedFiles.Clear(); input.EntityToProcess.Posts.Clear(); await context.SaveChangesAsync(); } // User Votes if (input.EntityToProcess.Votes != null) { var votesToDelete = new List <Vote>(); votesToDelete.AddRange(input.EntityToProcess.Votes); votesToDelete.AddRange(input.EntityToProcess.VotesGiven); foreach (var d in votesToDelete) { _voteService.Delete(d); } input.EntityToProcess.Votes.Clear(); input.EntityToProcess.VotesGiven.Clear(); await context.SaveChangesAsync(); } // User Group notifications if (input.EntityToProcess.GroupNotifications != null) { var toDelete = new List <GroupNotification>(); toDelete.AddRange(input.EntityToProcess.GroupNotifications); foreach (var obj in toDelete) { _notificationService.Delete(obj); } input.EntityToProcess.GroupNotifications.Clear(); await context.SaveChangesAsync(); } // User Favourites if (input.EntityToProcess.Favourites != null) { var toDelete = new List <Favourite>(); toDelete.AddRange(input.EntityToProcess.Favourites); foreach (var obj in toDelete) { _favouriteService.Delete(obj); } input.EntityToProcess.Favourites.Clear(); await context.SaveChangesAsync(); } if (input.EntityToProcess.TopicNotifications != null) { var notificationsToDelete = new List <TopicNotification>(); notificationsToDelete.AddRange(input.EntityToProcess.TopicNotifications); foreach (var topicNotification in notificationsToDelete) { _notificationService.Delete(topicNotification); } input.EntityToProcess.TopicNotifications.Clear(); } // Also clear their points var userPoints = input.EntityToProcess.Points; if (userPoints.Any()) { var pointsList = new List <MembershipUserPoints>(); pointsList.AddRange(userPoints); foreach (var point in pointsList) { point.User = null; await _membershipUserPointsService.Delete(point); } input.EntityToProcess.Points.Clear(); } // Now clear all activities for this user var usersActivities = _activityService.GetDataFieldByGuid(input.EntityToProcess.Id); _activityService.Delete(usersActivities.ToList()); await context.SaveChangesAsync(); // Also clear their poll votes var userPollVotes = input.EntityToProcess.PollVotes; if (userPollVotes.Any()) { var pollList = new List <PollVote>(); pollList.AddRange(userPollVotes); foreach (var vote in pollList) { vote.User = null; _pollService.Delete(vote); } input.EntityToProcess.PollVotes.Clear(); await context.SaveChangesAsync(); } } catch (Exception ex) { input.AddError(ex.Message); _loggingService.Error(ex); } return(input); }
public static void Error(Exception ex, string message = null) { _loggingService.Error(ex, message); }
public async void ThrowUnknownErrorMessageBox(Exception ex) { _loggingService.Error(Properties.Resources.UnknownErrorMessageBoxTitle, ex); await this.ShowMessageAsync(Properties.Resources.UnknownErrorMessageBoxTitle , string.Format(Properties.Resources.UnknownErrorMessageBoxText, ex.Message)); }
public byte[] ServeCombinedContent(int ieVersion, NameValueCollection queryStringParms, Func <string, string> pathMapper, Func <string, string> fileReader, string imagesHostToPrepend) { string manualVersion = queryStringParms[CombinerConstantsAndSettings.VersionUrlKey]; string sharedVersion = queryStringParms[CombinerConstantsAndSettings.SharedVersionUrlKey]; string type = queryStringParms[CombinerConstantsAndSettings.TypeUrlKey]; string encodedFileUrls = queryStringParms[CombinerConstantsAndSettings.FilesUrlKey]; var resourceType = (CombinedResourceType)Enum.Parse(typeof(CombinedResourceType), type.ToLower()); string minifyQs = queryStringParms[CombinerConstantsAndSettings.MinifyUrlKey]; bool minify; if (!bool.TryParse(minifyQs, out minify)) { minify = true; // default value is true } string rewriteImagePathsQs = queryStringParms[CombinerConstantsAndSettings.RewriteImagePathsUrlKey]; bool rewriteImagePaths; if (!bool.TryParse(rewriteImagePathsQs, out rewriteImagePaths)) { rewriteImagePaths = false;// default value is false } var cacheKey = GetCacheKeyForCombinedContent(manualVersion, sharedVersion, resourceType, ieVersion, encodedFileUrls.GetHashCode().ToString(), minify, rewriteImagePaths); var syncRoot = LocksForCombinedContent.GetOrAdd(cacheKey, new AutoResetEvent(true)); var mappedFiles = new List <string>(); var result = _cacheService.Get( syncRoot, cacheKey, () => { var allScripts = new StringBuilder(); var unencryptedFileUrlsCsv = DecodeFrom64(encodedFileUrls); var fileUrlsList = unencryptedFileUrlsCsv.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string fileName in fileUrlsList) { string filePath; string fileName2 = null; try { // Remove any query string from fileName int indx = fileName.IndexOf("?"); fileName2 = fileName.Substring(0, (indx > 0 ? indx : fileName.Length)); // ----- Important: only allow files with extensions '.js' and '.css'! if (!fileName2.ToLower().EndsWith(".js") && !fileName2.EndsWith(".css")) { continue; } // ----- filePath = pathMapper(fileName2); mappedFiles.Add(filePath); } catch (Exception e) { _logger.Error("Exception mapping combined file path: " + fileName2 + ". Exception: " + e.Message); continue; } string content = "/*no content: " + filePath + "*/"; // this can be used for debugging purposes try { content = fileReader(filePath); // File.ReadAllText(filePath); } catch (Exception rExc) { _logger.Error("Exception reading resource: " + fileName2 + ". Exception: " + rExc.Message); } // If file is already minified just append the content, else minify before appending if (filePath.Contains(".min")) { allScripts.Append(content); } else { try { string minified; if (resourceType == CombinedResourceType.javascript) { // ***** Minify the script file and remove comments and white spaces minified = minify ? _minifier.MinifyJs(content) : content; // ******** } else { // ***** Convert all relative image paths to absolute paths content = FixImagePaths(content, fileName2, rewriteImagePaths, imagesHostToPrepend); // ******** // ***** Minify the css file and remove comments and white spaces minified = minify ? _minifier.MinifyCss(content) : content; // ******** } allScripts.Append(minified); } catch (Exception mExc) { _logger.Error("Exception Minimizing resource: " + fileName2 + ". Exception: " + mExc.Message); allScripts.Append(content); // add non-minified content if minification failed } } } // *** Get the combined content in bytes string minifiedAll = allScripts.ToString(); if (string.IsNullOrEmpty(minifiedAll)) { return(null); } byte[] bytes = Encoding.UTF8.GetBytes(minifiedAll); // ****** return(bytes); }, () => { var policy = new CacheItemPolicy { Priority = CacheItemPriority.Default }; policy.ChangeMonitors.Add(new HostFileChangeMonitor(mappedFiles)); return(policy); } ); return(result); }
public IndexModule( IMtgStore mtgStore, ILoggingService loggingService, ICardPriceStore priceStore ) { Get["/"] = parameters => { loggingService.Warning("GET request from {0}: Path '{1}' was invalid.", this.Request.UserHostAddress, this.Request.Path); return(View["index/index.html"]); }; #region Card Search Route Get["/api/search/{term?}/{type?text}", true] = async(parameters, ct) => { var sw = Stopwatch.StartNew(); int limit = 1000; string term = parameters.term; string searchType = parameters.type; if (string.IsNullOrEmpty(term) || term.StartsWith("?")) { return(Response.AsJson(new { SearchTerm = "", Limit = limit, Cards = new List <Card>() })); } List <Card> db_cards = null; if (searchType.ToLower() == "text") { db_cards = await mtgStore.FullTextSearch(term, limit); } else if (searchType.ToLower() == "name") { db_cards = await mtgStore.SearchCards(term, 0, limit); } if (db_cards == null) { string msg = string.Format("No cards found using name '{0}'", term); loggingService.Error(msg); return(Response.AsJson(new { SearchTerm = term, Limit = limit, Cards = new List <Card>() }).StatusCode = HttpStatusCode.NotAcceptable); } // Get price information var cards = db_cards.Select(c => new { Name = c.Name, Code = c.SetId, Set = c.SetName, Cost = c.Cost, CostSymbols = c.CostWithSymbols, Type = c.FullType, Rarity = c.Rarity, Img = c.Img, MultiverseId = c.MultiverseId, SearchName = c.SearchName, Symbol = c.SetAsKeyRuneIcon, Desc = c.Desc, DescSymbols = c.DescWithSymbols, ConvertedManaCost = c.Cmc, Prices = GetCardPrice(priceStore, c.MultiverseId) }); sw.Stop(); return(Response.AsJson(new { SearchTerm = term, Limit = limit, Elapsed = sw.Elapsed.ToString(), Cards = cards, })); }; // // Testing out paging Post["/api/0.x/search", true] = async(parameters, ct) => { var sw = Stopwatch.StartNew(); int limit = 1000; //string term = parameters.term; var query = this.Bind <SearchQuery>(); if (query == null) { return(HttpStatusCode.NotAcceptable); } if (string.IsNullOrEmpty(query.SearchTerm)) { return(HttpStatusCode.NotAcceptable); } var db_cards = await mtgStore.SearchCards(query.SearchTerm, query.Page, limit); if (db_cards == null) { string msg = string.Format("No cards found using name '{0}'", query.SearchTerm); loggingService.Error(msg); return(Response.AsJson(new { SearchTerm = query.SearchTerm, Limit = limit, Cards = new List <Card>() }).StatusCode = HttpStatusCode.NotAcceptable); } var cards = db_cards.Select(c => new { Name = c.Name, Code = c.SetId, Set = c.SetName, Cost = c.Cost, CostSymbols = c.CostWithSymbols, Type = c.FullType, Rarity = c.Rarity, Img = c.Img, MultiverseId = c.MultiverseId, SearchName = c.SearchName, Symbol = c.SetAsKeyRuneIcon, Desc = c.Desc, DescSymbols = c.DescWithSymbols, ConvertedManaCost = c.Cmc, Prices = GetCardPrice(priceStore, c.MultiverseId) }).OrderByDescending(c => c.SearchName); sw.Stop(); return(Response.AsJson(new { SearchTerm = query.SearchTerm, Limit = limit, Elapsed = sw.Elapsed.ToString(), Cards = cards })); }; #endregion // priceincreases route Get["/priceincreases/"] = parameters => { int limit = 10; List <CardPrice> prices = priceStore.GetCardsByPriceIncrease(limit); return(Response.AsJson <List <CardPrice> >(prices)); }; // pricedecreases route Get["/pricedecreases/"] = parameters => { int limit = 10; List <CardPrice> prices = priceStore.GetCardsByPriceDecrease(limit); return(Response.AsJson <List <CardPrice> >(prices)); }; // Price changes Get["/price-changes", true] = async(parameters, ct) => { int limit = 100; var sw = Stopwatch.StartNew(); List <CardPrice> db_increases = priceStore.GetCardsByPriceIncrease(limit); List <CardPrice> db_decreases = priceStore.GetCardsByPriceDecrease(limit); var increases = db_increases.Select(c => new { Name = c.Name, Code = c.SetCode, Symbol = c.SetAsKeyRuneIcon, MultiverseId = c.MultiverseId, PriceDiff = c.PriceDiff, PriceDiffValue = c.PriceDiffValue, PriceMid = c.PriceMid, PriceFoil = c.PriceFoil, Img = c.ImageUrl, LastUpdated = c.LastUpdated.ToShortDateString(), Url = c.Url }); var decreases = db_decreases.Select(c => new { Name = c.Name, Code = c.SetCode, Symbol = c.SetAsKeyRuneIcon, MultiverseId = c.MultiverseId, PriceDiff = c.PriceDiff, PriceDiffValue = c.PriceDiffValue, PriceMid = c.PriceMid, PriceFoil = c.PriceFoil, Img = c.ImageUrl, LastUpdated = c.LastUpdated.ToShortDateString(), Url = c.Url }); sw.Stop(); return(View["index/price-changes.html", new { Elapsed = sw.Elapsed.ToString(), Limit = limit, Increased = increases, Decreased = decreases }]); }; // Ruling route Get["/ruling/{id:int}", true] = async(parameters, ct) => { var sw = Stopwatch.StartNew(); int cardMultiverseId = parameters.id; var card = await mtgStore.GetCard(cardMultiverseId); if (card == null) { string msg = string.Format("No card found using multiverseId '{0}'", cardMultiverseId); loggingService.Error(msg); return(msg); } var set = await mtgStore.GetSetByCode(card.SetId); if (set == null) { string msg = string.Format("No set found using code '{0}'", card.SetId); loggingService.Error(msg); return(msg); } // Get price information var cardPrice = priceStore.GetCardPrice(card.MultiverseId); sw.Stop(); return(View["index/ruling.html", new { Elapsed = sw.Elapsed.ToString(), Card = card, SetCode = !string.IsNullOrEmpty(set.GathererCode) ? set.GathererCode : set.Code, CardPrices = new { Url = cardPrice != null ? cardPrice.Url : "", Low = cardPrice != null ? cardPrice.PriceLow : "", Mid = cardPrice != null ? cardPrice.PriceMid : "", Foil = cardPrice != null ? cardPrice.PriceFoil : "", Diff = cardPrice != null ? cardPrice.PriceDiff : "", } }]); }; // Get search results Get["/search/{term}", true] = async(parameters, ct) => { var sw = Stopwatch.StartNew(); int limit = 1000; string term = parameters.term; if (string.IsNullOrEmpty(term)) { return(HttpStatusCode.Accepted); } var db_cards = await mtgStore.FullTextSearch(term, limit); if (db_cards == null) { string msg = string.Format("No cards found using name '{0}'", term); loggingService.Error(msg); return(msg); } sw.Stop(); // Get price information var cards = db_cards.Select(c => new { Name = c.Name, Code = c.SetId, Set = c.SetName, Cost = c.Cost, CostSymbols = c.CostWithSymbols, Type = c.FullType, Rarity = c.Rarity, Img = c.Img, MultiverseId = c.MultiverseId, SearchName = c.SearchName, Symbol = c.SetAsKeyRuneIcon, Desc = c.Desc, DescSymbols = c.DescWithSymbols, ConvertedManaCost = c.Cmc, Prices = GetCardPrice(priceStore, c.MultiverseId) }).ToList(); sw.Stop(); return(View["index/search.html", new { SearchTerm = term, Limit = limit, Elapsed = sw.Elapsed.ToString(), Cards = cards, }]); }; #region Sets Get["/sets", true] = async(parameters, ct) => { var sets = await mtgStore.GetSets(); return(View["listSets.html", new { Sets = sets.Select(s => new { Name = s.Name, Code = s.Code, Block = s.Block, Type = s.Type, ReleasedOn = s.ReleasedOn.ToShortDateString(), ReleasedOnSort = s.ReleasedOn, Symbol = s.SetAsKeyRuneIcon }).OrderByDescending(s => s.ReleasedOnSort) }]); }; Get["/set/{set}", true] = async(parameters, ct) => { string setCode = parameters.set; var set = await mtgStore.GetSetByCode(setCode); // If set doesnt exist, redirect back to sets list if (set == null) { return(Response.AsRedirect("/sets", RedirectResponse.RedirectType.Temporary)); } var db_cards = await mtgStore.GetCardsBySet(set.Name); // Get price information var cards = db_cards.Select(c => new { Name = c.Name, Code = c.SetId, Set = c.SetName, Cost = c.Cost, CostSymbols = c.CostWithSymbols, Type = c.FullType, Rarity = c.Rarity, Img = c.Img, MultiverseId = c.MultiverseId, SearchName = c.SearchName, Symbol = c.SetAsKeyRuneIcon, Desc = c.Desc, DescSymbols = c.DescWithSymbols, ConvertedManaCost = c.Cmc, SetSymbol = c.SetAsKeyRuneIcon, Prices = GetCardPrice(priceStore, c.MultiverseId) }).OrderByDescending(c => c.SearchName); return(View["set.html", new { Set = set, Cards = cards }]); }; #endregion }
public ActionResult GetAllGames() { IEnumerable <GameViewModel> games; try { games = Mapper.Map <IEnumerable <GameDTO>, IEnumerable <GameViewModel> >(_gameService.GetAll()); } catch (InvalidOperationException e) { _logger.Error(e); return(HttpNotFound()); } return(Json(games, JsonRequestBehavior.AllowGet)); }
public static void Error(object message) { Service.Error(message); }
/// <inheritdoc /> public async Task <IPipelineProcess <Topic> > Process(IPipelineProcess <Topic> input, IMvcForumContext context) { _notificationService.RefreshContext(context); _activityService.RefreshContext(context); _localizationService.RefreshContext(context); try { // Get the Current user from ExtendedData var username = input.ExtendedData[Constants.ExtendedDataKeys.Username] as string; var loggedOnUser = await context.MembershipUser.FirstOrDefaultAsync(x => x.UserName == username); // Are we in an edit mode var isEdit = input.ExtendedData[Constants.ExtendedDataKeys.IsEdit] as bool? == true; // If the topic has tags then process if (input.EntityToProcess.Tags != null && input.EntityToProcess.Tags.Any()) { // Don't throw if badge fails as it's logged //await _badgeService.ProcessBadge(BadgeType.Tag, input.EntityToProcess.User); } if (isEdit == false) { // Subscribe the user to the topic as they have checked the checkbox if (input.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Subscribe)) { var subscribe = input.ExtendedData[Constants.ExtendedDataKeys.Subscribe] as bool?; if (subscribe == true) { var alreadyHasNotification = await context.TopicNotification .Include(x => x.Topic) .Include(x => x.User) .AnyAsync(x => x.Topic.Id == input.EntityToProcess.Id && x.User.Id == loggedOnUser.Id); if (alreadyHasNotification == false) { // Create the notification var topicNotification = new TopicNotification { Topic = input.EntityToProcess, User = loggedOnUser }; //save _notificationService.Add(topicNotification); } } } // Should we add the topic created activity if (input.EntityToProcess.Pending != true) { _activityService.TopicCreated(input.EntityToProcess); } // finally notify _notificationService.Notify(input.EntityToProcess, loggedOnUser, NotificationType.Topic); } // Was the post successful await context.SaveChangesAsync(); } catch (System.Exception ex) { input.AddError(ex.Message); _loggingService.Error(ex); } return(input); }
/// <inheritdoc /> public void Notify(Topic topic, MembershipUser loggedOnReadOnlyUser, NotificationType notificationType) { List <Guid> userIdsToNotify; var settings = _settingsService.GetSettings(); if (notificationType == NotificationType.Post) { userIdsToNotify = GetTopicNotificationsByTopic(topic).Select(x => x.User.Id).ToList(); } else { // Get all notifications for this category and for the tags on the topic userIdsToNotify = GetCategoryNotificationsByCategory(topic.Category).Select(x => x.User.Id).ToList(); // Merge and remove duplicate ids if (topic.Tags != null && topic.Tags.Any()) { var tagNotifications = GetTagNotificationsByTag(topic.Tags.ToList()).Select(x => x.User.Id) .ToList(); userIdsToNotify = userIdsToNotify.Union(tagNotifications).ToList(); } } if (userIdsToNotify.Any()) { // remove the current user from the notification, don't want to notify yourself that you // have just made a topic! userIdsToNotify.Remove(loggedOnReadOnlyUser.Id); if (userIdsToNotify.Count > 0) { try { // Now get all the users that need notifying var users = _context.MembershipUser .Where(x => userIdsToNotify.Contains(x.Id)) .AsNoTracking() .ToList(); // Create the email var sb = new StringBuilder(); sb.AppendFormat("<p>{0}</p>", string.Format(_localizationService.GetResourceString(notificationType == NotificationType.Post ? "Post.Notification.NewPosts" : "Topic.Notification.NewTopics"), topic.Category.Name)); sb.Append($"<p>{topic.Name}</p>"); if (ForumConfiguration.Instance.IncludeFullPostInEmailNotifications) { sb.Append(topic.LastPost.PostContent.ConvertPostContent()); } sb.AppendFormat("<p><a href=\"{0}\">{0}</a></p>", string.Concat(StringUtils.ReturnCurrentDomain(), topic.Category.NiceUrl)); // create the emails and only send them to people who have not had notifications disabled var emails = users .Where(x => x.DisableEmailNotifications != true && !x.IsLockedOut && x.IsBanned != true).Select( user => new Email { Body = _emailService.EmailTemplate(user.UserName, sb.ToString()), EmailTo = user.Email, NameTo = user.UserName, Subject = string.Concat( _localizationService.GetResourceString(notificationType == NotificationType.Post ? "Post.Notification.Subject" : "Topic.Notification.Subject"), settings.ForumName) }).ToList(); // and now pass the emails in to be sent _emailService.SendMail(emails); _context.SaveChanges(); } catch (Exception ex) { _context.RollBack(); _loggingService.Error(ex); } } } }
public IOrderDetails PlaceBuyOrder(BuyOptions options) { IOrderDetails orderDetails = null; trailingBuys.TryRemove(options.Pair, out BuyTrailingInfo buyTrailingInfo); trailingSells.TryRemove(options.Pair, out SellTrailingInfo sellTrailingInfo); if (tradingService.CanBuy(options, out string message)) { IPairConfig pairConfig = tradingService.GetPairConfig(options.Pair); ITradingPair tradingPair = tradingService.Account.GetTradingPair(options.Pair); decimal currentPrice = tradingService.GetCurrentPrice(options.Pair); options.Metadata.TradingRules = pairConfig.Rules.ToList(); if (options.Metadata.LastBuyMargin == null) { options.Metadata.LastBuyMargin = tradingPair?.CurrentMargin ?? 0; } string signalRule = options.Metadata.SignalRule ?? "N/A"; BuyOrder buyOrder = new BuyOrder { Type = pairConfig.BuyType, Date = DateTimeOffset.Now, Pair = options.Pair, Amount = options.Amount ?? (options.MaxCost.Value / currentPrice), Price = currentPrice }; if (!tradingService.Config.VirtualTrading) { loggingService.Info($"Place buy order for {tradingPair?.FormattedName ?? options.Pair}. Price: {buyOrder.Price:0.00000000}, Amount: {buyOrder.Amount:0.########}, Signal Rule: {signalRule}"); try { lock (tradingService.Account.SyncRoot) { orderDetails = tradingService.PlaceOrder(buyOrder); orderDetails.SetMetadata(options.Metadata); tradingService.Account.AddBuyOrder(orderDetails); tradingService.Account.Save(); tradingService.LogOrder(orderDetails); tradingPair = tradingService.Account.GetTradingPair(options.Pair); loggingService.Info("{@Trade}", orderDetails); loggingService.Info($"Buy order result for {tradingPair.FormattedName}: {orderDetails.Result} ({orderDetails.Message}). Price: {orderDetails.AveragePrice:0.00000000}, Amount: {orderDetails.Amount:0.########}, Filled: {orderDetails.AmountFilled:0.########}, Cost: {orderDetails.AverageCost:0.00000000}"); notificationService.Notify($"Bought {tradingPair.FormattedName}. Amount: {orderDetails.AmountFilled:0.########}, Price: {orderDetails.AveragePrice:0.00000000}, Cost: {orderDetails.AverageCost:0.00000000}"); } } catch (Exception ex) { loggingService.Error($"Unable to place buy order for {options.Pair}", ex); notificationService.Notify($"Unable to buy {options.Pair}: {ex.Message}"); } } else { loggingService.Info($"Place virtual buy order for {tradingPair?.FormattedName ?? options.Pair}. Price: {buyOrder.Price:0.00000000}, Amount: {buyOrder.Amount:0.########}, Signal Rule: {signalRule}"); lock (tradingService.Account.SyncRoot) { decimal roundedAmount = Math.Round(buyOrder.Amount, 4); orderDetails = new OrderDetails { Metadata = options.Metadata, OrderId = DateTime.Now.ToFileTimeUtc().ToString(), Side = OrderSide.Buy, Result = OrderResult.Filled, Date = buyOrder.Date, Pair = buyOrder.Pair, Amount = roundedAmount, AmountFilled = roundedAmount, Price = buyOrder.Price, AveragePrice = buyOrder.Price }; tradingService.Account.AddBuyOrder(orderDetails); tradingService.Account.Save(); tradingService.LogOrder(orderDetails); tradingPair = tradingService.Account.GetTradingPair(options.Pair); loggingService.Info("{@Trade}", orderDetails); loggingService.Info($"Virtual buy order result for {tradingPair.FormattedName}. Price: {orderDetails.AveragePrice:0.00000000}, Amount: {orderDetails.Amount:0.########}, Cost: {orderDetails.AverageCost:0.00000000}"); notificationService.Notify($"Bought {tradingPair.FormattedName}. Amount: {orderDetails.AmountFilled:0.########}, Price: {orderDetails.AveragePrice:0.00000000}, Cost: {orderDetails.AverageCost:0.00000000}"); } } tradingService.ReapplyTradingRules(); } else { loggingService.Info(message); } return(orderDetails); }
/// <inheritdoc /> public async Task <IPipelineProcess <MembershipUser> > Process(IPipelineProcess <MembershipUser> input, IMvcForumContext context) { _membershipService.RefreshContext(context); _settingsService.RefreshContext(context); _localizationService.RefreshContext(context); _emailService.RefreshContext(context); _activityService.RefreshContext(context); try { if (string.IsNullOrWhiteSpace(input.EntityToProcess.UserName)) { input.ProcessLog.Clear(); input.ProcessLog.Add(_membershipService.ErrorCodeToString(MembershipCreateStatus.InvalidUserName)); input.Successful = false; return(input); } // get by username if (_membershipService.GetUser(input.EntityToProcess.UserName, true) != null) { input.ProcessLog.Clear(); input.ProcessLog.Add(_membershipService.ErrorCodeToString(MembershipCreateStatus.DuplicateUserName)); input.Successful = false; return(input); } // Add get by email address if (_membershipService.GetUserByEmail(input.EntityToProcess.Email, true) != null) { input.ProcessLog.Clear(); input.ProcessLog.Add(_membershipService.ErrorCodeToString(MembershipCreateStatus.DuplicateEmail)); input.Successful = false; return(input); } if (string.IsNullOrWhiteSpace(input.EntityToProcess.Password)) { input.ProcessLog.Clear(); input.ProcessLog.Add(_membershipService.ErrorCodeToString(MembershipCreateStatus.InvalidPassword)); input.Successful = false; return(input); } // Get the settings var settings = _settingsService.GetSettings(false); var manuallyAuthoriseMembers = settings.ManuallyAuthoriseNewMembers; var memberEmailAuthorisationNeeded = settings.NewMemberEmailConfirmation == true; // Check social login var isSocialLogin = !string.IsNullOrWhiteSpace(input.EntityToProcess.FacebookAccessToken) || !string.IsNullOrWhiteSpace(input.EntityToProcess.GoogleAccessToken) || !string.IsNullOrWhiteSpace(input.EntityToProcess.MicrosoftAccessToken); // If this is a social login, and memberEmailAuthorisationNeeded is true then we need to ignore it // and set memberEmailAuthorisationNeeded to false because the email addresses are validated by the social media providers if (isSocialLogin && manuallyAuthoriseMembers == false) { memberEmailAuthorisationNeeded = false; input.EntityToProcess.IsApproved = true; } else if (manuallyAuthoriseMembers || memberEmailAuthorisationNeeded) { input.EntityToProcess.IsApproved = false; } else { input.EntityToProcess.IsApproved = true; } // See if this is a social login and we have their profile pic var socialProfileImageUrl = input.EntityToProcess.GetExtendedDataItem(Constants.ExtendedDataKeys.SocialProfileImageUrl); if (!string.IsNullOrWhiteSpace(socialProfileImageUrl)) { // We have an image url - Need to save it to their profile var image = socialProfileImageUrl.GetImageFromExternalUrl(); // Set upload directory - Create if it doesn't exist var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(ForumConfiguration.Instance.UploadFolderPath, input.EntityToProcess.Id)); if (uploadFolderPath != null && !Directory.Exists(uploadFolderPath)) { Directory.CreateDirectory(uploadFolderPath); } // Get the file name var fileName = Path.GetFileName(socialProfileImageUrl); // Create a HttpPostedFileBase image from the C# Image using (var stream = new MemoryStream()) { // Microsoft doesn't give you a file extension - See if it has a file extension // Get the file extension var fileExtension = Path.GetExtension(fileName); // Fix invalid Illegal charactors var regexSearch = $"{new string(Path.GetInvalidFileNameChars())}{new string(Path.GetInvalidPathChars())}"; var reg = new Regex($"[{Regex.Escape(regexSearch)}]"); fileName = reg.Replace(fileName, ""); if (string.IsNullOrWhiteSpace(fileExtension)) { // no file extension so give it one fileName = string.Concat(fileName, ".jpg"); } image.Save(stream, ImageFormat.Jpeg); stream.Position = 0; HttpPostedFileBase formattedImage = new MemoryFile(stream, "image/jpeg", fileName); // Upload the file var uploadResult = formattedImage.UploadFile(uploadFolderPath, _localizationService, true); // Don't throw error if problem saving avatar, just don't save it. if (uploadResult.UploadSuccessful) { input.EntityToProcess.Avatar = uploadResult.UploadedFileName; } } } input.EntityToProcess = context.MembershipUser.Add(input.EntityToProcess); var saved = await context.SaveChangesAsync(); if (saved <= 0) { input.ProcessLog.Add("Unable to save changes to the database"); input.Successful = false; return(input); } if (settings.EmailAdminOnNewMemberSignUp) { var sb = new StringBuilder(); sb.Append( $"<p>{string.Format(_localizationService.GetResourceString("Members.NewMemberRegistered"), settings.ForumName, settings.ForumUrl)}</p>"); sb.Append($"<p>{input.EntityToProcess.UserName} - {input.EntityToProcess.Email}</p>"); var email = new Email { EmailTo = settings.AdminEmailAddress, NameTo = _localizationService.GetResourceString("Members.Admin"), Subject = _localizationService.GetResourceString("Members.NewMemberSubject") }; email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString()); _emailService.SendMail(email); } // Only send the email if the admin is not manually authorising emails or it's pointless _emailService.SendEmailConfirmationEmail(input.EntityToProcess, manuallyAuthoriseMembers, memberEmailAuthorisationNeeded); // Now add a memberjoined activity _activityService.MemberJoined(input.EntityToProcess); // Set manuallyAuthoriseMembers, memberEmailAuthorisationNeeded in extendeddata input.ExtendedData.Add(Constants.ExtendedDataKeys.ManuallyAuthoriseMembers, manuallyAuthoriseMembers); input.ExtendedData.Add(Constants.ExtendedDataKeys.MemberEmailAuthorisationNeeded, memberEmailAuthorisationNeeded); } catch (Exception ex) { input.AddError(ex.Message); _loggingService.Error(ex); } if (input.Successful) { input.ProcessLog.Add("CreateNewUserPipe Successful"); } return(input); }
public void ProcessMail(List <Email> emails) { try { // See if there are any if (emails != null && emails.Any()) { // Get the mails settings var settings = _settingsService.GetSettings(false); var smtp = settings.SMTP; var smtpUsername = settings.SMTPUsername; var smtpPassword = settings.SMTPPassword; var smtpPort = settings.SMTPPort; var smtpEnableSsl = settings.SMTPEnableSSL; var fromEmail = settings.NotificationReplyEmail; // If no SMTP settings then log it if (string.IsNullOrWhiteSpace(smtp)) { // Not logging as it makes the log file massive //_loggingService.Error("There are no SMTP details in the settings, unable to send emails"); return; } // Set up the SMTP Client object and settings var mySmtpClient = new SmtpClient(smtp); if (!string.IsNullOrWhiteSpace(smtpUsername) && !string.IsNullOrWhiteSpace(smtpPassword)) { mySmtpClient.Credentials = new NetworkCredential(smtpUsername, smtpPassword); } if (smtpEnableSsl != null) { mySmtpClient.EnableSsl = (bool)smtpEnableSsl; } if (!string.IsNullOrWhiteSpace(smtpPort)) { mySmtpClient.Port = Convert.ToInt32(smtpPort); } // Loop through email email create a mailmessage and send foreach (var message in emails) { try { var msg = new MailMessage { IsBodyHtml = true, Body = message.Body, From = new MailAddress(fromEmail), Subject = message.Subject }; msg.To.Add(message.EmailTo); mySmtpClient.Send(msg); } catch (Exception ex) { _loggingService.Error($"EXCEPTION sending mail to {message.EmailTo}: {ex.Message}"); } } } } catch (Exception ex) { _loggingService.Error(ex); } }
public IOrderDetails PlaceBuyOrder(BuyOptions options) { OrderDetails orderDetails = new OrderDetails(); tradingService.StopTrailingBuy(options.Pair); tradingService.StopTrailingSell(options.Pair); try { ITradingPair tradingPair = tradingService.Account.GetTradingPair(options.Pair, includeDust: true); options.Price = tradingService.GetPrice(options.Pair, TradePriceType.Ask, normalize: false); options.Amount = options.Amount ?? (options.MaxCost.Value / (options.Pair.EndsWith(Constants.Markets.USDT) ? 1 : options.Price)); options.Price = tradingService.Exchange.ClampOrderPrice(options.Pair, options.Price.Value); options.Amount = tradingService.Exchange.ClampOrderAmount(options.Pair, options.Amount.Value); if (tradingService.CanBuy(options, out string message)) { IPairConfig pairConfig = tradingService.GetPairConfig(options.Pair); BuyOrder buyOrder = new BuyOrder { Type = pairConfig.BuyType, Date = DateTimeOffset.Now, Pair = options.Pair, Price = options.Price.Value, Amount = options.Amount.Value }; lock (tradingService.Account.SyncRoot) { loggingService.Info($"Place buy order for {tradingPair?.FormattedName ?? options.Pair}. " + $"Price: {buyOrder.Price:0.00000000}, Amount: {buyOrder.Amount:0.########}, Signal Rule: " + (options.Metadata.SignalRule ?? "N/A")); if (!tradingService.Config.VirtualTrading) { orderDetails = tradingService.Exchange.PlaceOrder(buyOrder) as OrderDetails; } else { string pairMarket = tradingService.Exchange.GetPairMarket(options.Pair); orderDetails = new OrderDetails { OrderId = DateTime.Now.ToFileTimeUtc().ToString(), Side = OrderSide.Buy, Result = OrderResult.Filled, Date = buyOrder.Date, Pair = buyOrder.Pair, Amount = buyOrder.Amount, AmountFilled = buyOrder.Amount, Price = buyOrder.Price, AveragePrice = buyOrder.Price, Fees = buyOrder.Amount * buyOrder.Price * tradingService.Config.VirtualTradingFees, FeesCurrency = pairMarket }; } NormalizeOrder(orderDetails, TradePriceType.Ask); options.Metadata.TradingRules = pairConfig.Rules.ToList(); options.Metadata.LastBuyMargin = options.Metadata.LastBuyMargin ?? tradingPair?.CurrentMargin ?? null; orderDetails.Metadata = options.Metadata; tradingService.Account.AddBuyOrder(orderDetails); tradingService.Account.Save(); tradingService.LogOrder(orderDetails); decimal fees = tradingService.CalculateOrderFees(orderDetails); tradingPair = tradingService.Account.GetTradingPair(orderDetails.Pair, includeDust: true); loggingService.Info("{@Trade}", orderDetails); loggingService.Info($"Buy order result for {orderDetails.OriginalPair ?? tradingPair.FormattedName}: {orderDetails.Result} ({orderDetails.Message}). " + $"Price: {orderDetails.AveragePrice:0.00000000}, Amount: {orderDetails.Amount:0.########}, " + $"Filled: {orderDetails.AmountFilled:0.########}, Cost: {orderDetails.Cost:0.00000000}, Fees: {fees:0.00000000}"); notificationService.Notify($"Bought {tradingPair.FormattedName}. Amount: {orderDetails.AmountFilled:0.########}, " + $"Price: {orderDetails.AveragePrice:0.00000000}, Cost: {(orderDetails.Cost + fees):0.00000000}"); } tradingService.ReapplyTradingRules(); } else { loggingService.Info(message); } } catch (Exception ex) { loggingService.Error($"Unable to place buy order for {options.Pair}", ex); notificationService.Notify($"Unable to buy {options.Pair}: {ex.Message}"); } return(orderDetails); }
public void ProcessMail(int amountToSend) { try { // Get the amount of emails to send in this batch var emails = _emailRepository.GetAll(amountToSend); // See if there are any if (emails != null && emails.Count > 0) { // Get the mails settings var settings = _settingsService.GetSettings(false); var smtp = settings.SMTP; var smtpUsername = settings.SMTPUsername; var smtpPassword = settings.SMTPPassword; var smtpPort = settings.SMTPPort; var smtpEnableSsl = settings.SMTPEnableSSL; var fromEmail = settings.NotificationReplyEmail; // If no SMTP settings then log it if (string.IsNullOrEmpty(smtp)) { _loggingService.Error("There are no SMTP details in the settings, unable to send emails"); return; } // Set up the SMTP Client object and settings var mySmtpClient = new SmtpClient(smtp); if (!string.IsNullOrEmpty(smtpUsername) && !string.IsNullOrEmpty(smtpPassword)) { mySmtpClient.Credentials = new NetworkCredential(smtpUsername, smtpPassword); } if (smtpEnableSsl != null) { mySmtpClient.EnableSsl = (bool)smtpEnableSsl; } if (!string.IsNullOrEmpty(smtpPort)) { mySmtpClient.Port = Convert.ToInt32(smtpPort); } // List to store the emails to delete after they are sent var emailsToDelete = new List <Email>(); // Loop through email email create a mailmessage and send it foreach (var message in emails) { var msg = new MailMessage { IsBodyHtml = true, Body = message.Body, From = new MailAddress(fromEmail), Subject = message.Subject }; msg.To.Add(message.EmailTo); mySmtpClient.Send(msg); emailsToDelete.Add(message); } // Loop through the sent emails and delete them foreach (var sentEmail in emailsToDelete) { _emailRepository.Delete(sentEmail); } } } catch (Exception ex) { _loggingService.Error(ex); } }
private void LoadNextSnapshots() { lock (backtestingService.SyncRoot) { if (loadedSignalSnapshots == 0 && loadedTickerSnapshots == 0) { loggingService.Info($"<<<--- Backtesting started. Total signals snapshots: {totalSignalSnapshots}, Total tickers snapshots: {totalTickerSnapshots} --->>>"); backtestingTimer = Stopwatch.StartNew(); } if (allSignalSnapshotPaths.TryDequeue(out string currentSignalsSnapshotPath)) { try { byte[] currentSignalsSnapshotBytes = File.ReadAllBytes(currentSignalsSnapshotPath); IEnumerable <ISignal> data = ZeroFormatterSerializer.Deserialize <IEnumerable <SignalData> >(currentSignalsSnapshotBytes).Select(s => s.ToSignal()).ToList(); currentSignals = data.GroupBy(s => s.Pair).ToDictionary(s => s.Key, s => s.AsEnumerable()); loadedSignalSnapshots++; var currentSignalsSnapshotFile = currentSignalsSnapshotPath.Substring(currentSignalsSnapshotPath.Length - 27); currentSignalsSnapshotFile = currentSignalsSnapshotFile.Replace('\\', '-').Replace('/', '-'); if (backtestingService.Config.ReplayOutput && loadedSignalSnapshots % 100 == 0) { loggingService.Info($"<<<--- ({loadedSignalSnapshots}/{totalSignalSnapshots}) Load signals snapshot file: {currentSignalsSnapshotFile} --->>>"); } healthCheckService.UpdateHealthCheck(Constants.HealthChecks.BacktestingSignalsSnapshotLoaded, $"File: {currentSignalsSnapshotFile}"); } catch (Exception ex) { loggingService.Error($"<<<--- Unable to load signals snapshot file: {currentSignalsSnapshotPath} --->>>", ex); } } if (allTickerSnapshotPaths.TryDequeue(out string currentTickersSnapshotPath)) { try { byte[] currentTickersSnapshotBytes = File.ReadAllBytes(currentTickersSnapshotPath); IEnumerable <ITicker> data = ZeroFormatterSerializer.Deserialize <IEnumerable <TickerData> >(currentTickersSnapshotBytes).Select(t => t.ToTicker()).ToList(); currentTickers = data.ToDictionary(t => t.Pair, t => t); loadedTickerSnapshots++; var currentTickersSnapshotFile = currentTickersSnapshotPath.Substring(currentTickersSnapshotPath.Length - 27); currentTickersSnapshotFile = currentTickersSnapshotFile.Replace('\\', '-').Replace('/', '-'); if (backtestingService.Config.ReplayOutput && loadedTickerSnapshots % 100 == 0) { loggingService.Info($"<<<--- ({loadedTickerSnapshots}/{totalTickerSnapshots}) Load tickers snapshot file: {currentTickersSnapshotFile} --->>>"); } healthCheckService.UpdateHealthCheck(Constants.HealthChecks.BacktestingTickersSnapshotLoaded, $"File: {currentTickersSnapshotFile}"); } catch (Exception ex) { loggingService.Error($"<<<--- Unable to load tickers snapshot file: {currentTickersSnapshotPath} --->>>", ex); } } if (currentSignalsSnapshotPath == null && currentTickersSnapshotPath == null) { isCompleted = true; backtestingTimer.Stop(); loggingService.Info($"<<<--- Backtesting finished in {Math.Round(backtestingTimer.Elapsed.TotalSeconds)} seconds --->>>"); backtestingService.Complete(totalSignalSnapshots - loadedSignalSnapshots, totalTickerSnapshots - loadedTickerSnapshots); } } }
protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); FFImageLoading.Forms.Platform.CachedImageRenderer.Init(enableFastRenderer: true); var context = Platform.AppContext; var activity = Platform.CurrentActivity; _cfg = new AndroidOnlineTelevizorConfiguration(); #if LOADCONFIG var loaded = _cfg.LoadCredentails("http://localhost:8080/OnlineTelevizor.configuration.json"); if (loaded.HasValue) { if (loaded.Value) { ShowToastMessage("Configuration loaded from localhost"); } else { if (_cfg.LoadCredentails("http://10.0.0.7/OnlineTelevizor.configuration.json").Value) { ShowToastMessage("Configuration loaded from 10.0.0.7"); } } } #endif var uiModeManager = (UiModeManager)GetSystemService(UiModeService); if (uiModeManager.CurrentModeType == UiMode.TypeTelevision) { _cfg.IsRunningOnTV = true; } if (_cfg.EnableLogging) { _loggingService = new BasicLoggingService(_cfg.LoggingLevel); } else { _loggingService = new DummyLoggingService(); } _app = new App(_cfg, _loggingService); MessagingCenter.Subscribe <string>(this, BaseViewModel.ToastMessage, (message) => { ShowToastMessage(message); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.UriMessage, (url) => { var intent = new Intent(Intent.ActionView); var uri = Android.Net.Uri.Parse(url); intent.SetDataAndType(uri, "video/*"); intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask); // necessary for Android 5 Android.App.Application.Context.StartActivity(intent); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.EnableFullScreen, (msg) => { SetFullScreen(true); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.DisableFullScreen, (msg) => { SetFullScreen(false); }); MessagingCenter.Subscribe <SettingsPage>(this, BaseViewModel.CheckBatterySettings, (sender) => { try { var pm = (PowerManager)Android.App.Application.Context.GetSystemService(Context.PowerService); bool ignoring = pm.IsIgnoringBatteryOptimizations("net.petrjanousek.OnlineTelevizor"); if (!ignoring) { MessagingCenter.Send <string>(string.Empty, BaseViewModel.RequestBatterySettings); } } catch (Exception ex) { _loggingService.Error(ex); } }); MessagingCenter.Subscribe <SettingsPage>(this, BaseViewModel.SetBatterySettings, (sender) => { try { var intent = new Intent(); intent.SetAction(Android.Provider.Settings.ActionIgnoreBatteryOptimizationSettings); intent.SetFlags(ActivityFlags.NewTask); Android.App.Application.Context.StartActivity(intent); } catch (Exception ex) { _loggingService.Error(ex); } }); MessagingCenter.Subscribe <MainPage, ChannelItem>(this, BaseViewModel.PlayInternalNotification, (sender, channel) => { Device.BeginInvokeOnMainThread(() => { Task.Run(async() => await ShowPlayingNotification(channel)); }); }); MessagingCenter.Subscribe <MainPageViewModel, ChannelItem>(this, BaseViewModel.UpdateInternalNotification, (sender, channel) => { Device.BeginInvokeOnMainThread(() => { Task.Run(async() => await ShowPlayingNotification(channel)); }); }); MessagingCenter.Subscribe <string>(string.Empty, BaseViewModel.StopPlayInternalNotification, (sender) => { Device.BeginInvokeOnMainThread(() => { StopPlayingNotification(); }); }); MessagingCenter.Subscribe <BaseViewModel, ChannelItem>(this, BaseViewModel.RecordNotificationMessage, (sender, channel) => { Device.BeginInvokeOnMainThread(() => { Task.Run(async() => await ShowRecordNotification(channel)); }); }); MessagingCenter.Subscribe <BaseViewModel, ChannelItem>(this, BaseViewModel.UpdateRecordNotificationMessage, (sender, channel) => { Device.BeginInvokeOnMainThread(() => { Task.Run(async() => await ShowRecordNotification(channel)); }); }); https://www.youtube.com/watch?v=jqimAYrC3Ro MessagingCenter.Subscribe <string>(string.Empty, BaseViewModel.StopRecordNotificationMessage, (sender) => { Device.BeginInvokeOnMainThread(() => { StopRecordNotification(); }); }); MessagingCenter.Subscribe <string>(string.Empty, BaseViewModel.StopPlayInternalNotificationAndQuit, (sender) => { Device.BeginInvokeOnMainThread(() => { StopPlayingNotification(); Android.OS.Process.KillProcess(Android.OS.Process.MyPid()); }); }); // prevent sleep: Window window = (Forms.Context as Activity).Window; window.AddFlags(WindowManagerFlags.KeepScreenOn); // https://stackoverflow.com/questions/39248138/how-to-hide-bottom-bar-of-android-back-home-in-xamarin-forms _defaultUiOptions = (int)Window.DecorView.SystemUiVisibility; _fullscreenUiOptions = _defaultUiOptions; _fullscreenUiOptions |= (int)SystemUiFlags.LowProfile; _fullscreenUiOptions |= (int)SystemUiFlags.Fullscreen; _fullscreenUiOptions |= (int)SystemUiFlags.HideNavigation; _fullscreenUiOptions |= (int)SystemUiFlags.ImmersiveSticky; if (_cfg.Fullscreen) { SetFullScreen(true); } _notificationHelper = new NotificationHelper(this); StartService(new Intent(this, typeof(OnlineTelevizorService))); LoadApplication(_app); }
/// <summary> /// The on exception. /// </summary> /// <param name="filterContext"> /// The filter context. /// </param> protected override void OnException(ExceptionContext filterContext) { LoggingService.Error(filterContext.Exception); }
void DisplayError(Exception ex) { loggingService.Error(null, ex); messageService.ShowError(ex.Message); }
public MainPage(ILoggingService loggingService, DVBTTelevizorConfiguration config, IDVBTDriverManager driverManager) { InitializeComponent(); _dlgService = new DialogService(this); _loggingService = loggingService; _config = config; _driver = driverManager; try { _playerPage = new PlayerPage(_driver, _config); } catch (Exception ex) { _loggingService.Error(ex, "Error while initializing player page"); } _channelService = new ConfigChannelService(_loggingService, _config); _tunePage = new TunePage(_loggingService, _dlgService, _driver, _config, _channelService); _servicePage = new ServicePage(_loggingService, _dlgService, _driver, _config, _playerPage); _settingsPage = new SettingsPage(_loggingService, _dlgService, _config, _channelService); _editChannelPage = new ChannelPage(_loggingService, _dlgService, _driver, _config); Core.Initialize(); _libVLC = new LibVLC(); _mediaPlayer = new MediaPlayer(_libVLC) { EnableHardwareDecoding = true }; videoView.MediaPlayer = _mediaPlayer; BindingContext = _viewModel = new MainPageViewModel(_loggingService, _dlgService, _driver, _config, _channelService); if (_config.AutoInitAfterStart) { Task.Run(() => { Xamarin.Forms.Device.BeginInvokeOnMainThread( new Action( delegate { MessagingCenter.Send("", BaseViewModel.MSG_Init); })); }); } CheckStreamCommand = new Command(async() => await CheckStream()); BackgroundCommandWorker.RunInBackground(CheckStreamCommand, 3, 5); _servicePage.Disappearing += anyPage_Disappearing; _servicePage.Disappearing += anyPage_Disappearing; _tunePage.Disappearing += anyPage_Disappearing; _settingsPage.Disappearing += anyPage_Disappearing; _editChannelPage.Disappearing += _editChannelPage_Disappearing; ChannelsListView.ItemSelected += ChannelsListView_ItemSelected; Appearing += MainPage_Appearing; MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_KeyDown, (key) => { OnKeyDown(key); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_EditChannel, (message) => { Xamarin.Forms.Device.BeginInvokeOnMainThread( delegate { EditSelectedChannel(); }); }); MessagingCenter.Subscribe <PlayStreamInfo> (this, BaseViewModel.MSG_PlayStream, (playStreamInfo) => { Task.Run(async() => { await ActionPlay(); }); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_DVBTDriverConfiguration, (message) => { _loggingService.Debug($"Received DVBTDriverConfiguration message: {message}"); if (!_driver.Started) { _viewModel.ConnectDriver(message); } }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_UpdateDriverState, (message) => { _viewModel.UpdateDriverState(); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_DVBTDriverConfigurationFailed, (message) => { Device.BeginInvokeOnMainThread(delegate { _viewModel.UpdateDriverState(); MessagingCenter.Send($"Device connection error ({message})", BaseViewModel.MSG_ToastMessage); }); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_PlayPreviousChannel, (msg) => { OnKeyUp(); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_PlayNextChannel, (msg) => { OnKeyDown(); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_StopStream, (msg) => { StopPlayback(); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_ImportChannelsList, (message) => { _viewModel.ImportCommand.Execute(message); }); }
internal async Task GatherItems(bool getChildren, string server, CancellationToken cancellationToken, bool ignoreRevId) { ChildrenItemDataModel buffer = null; while (!Completed) { try { Guid id; if (!ProcessingIds.TryTake(out id, int.MaxValue, cancellationToken)) { break; } lock (_locker) _processing++; if (buffer == null) { buffer = _remoteContent.GetRemoteItemDataWithChildren(id, server, ignoreRevId ? null : _sitecore.GetItemAndChildrenRevision(id)); } if (GatheredRemoteItems.Count >= _maxQueue) { await Task.Delay(1000); } else { foreach (var item in (getChildren ? buffer.Items : buffer.Items.Where(x => x.Key == id))) { if (item.Value != null) { IItemData itemData = _yamlSerializationService.DeserializeYaml(item.Value, item.Key.ToString()); GatheredRemoteItems.Add(itemData, cancellationToken); } else { GatheredRemoteItems.Add(_sitecore.GetItemData(item.Key), cancellationToken); } } if (getChildren && buffer.GrandChildren != null) { foreach (var child in buffer.GrandChildren) { ProcessingIds.Add(child, cancellationToken); } } buffer = null; } } catch (OperationCanceledException e) { _log.Warn("Content migration operation was cancelled", e, this); break; } catch (Exception e) { _log.Error("error processing ids to gather remote content", e, this); } lock (_locker) { _processing--; if (_processing > 0 || ProcessingIds.Count != 0) { continue; } } Completed = true; ProcessingIds.CompleteAdding(); GatheredRemoteItems.CompleteAdding(); } }
private void PreviewVideoBordersFix() { try { if (PlayingState == PlayingStateEnum.PlayingInPreview) { var videoTrack = GetVideoTrack(); if (!videoTrack.HasValue) { return; } var originalVideoWidth = videoTrack.Value.Data.Video.Width; var originalVideoHeight = videoTrack.Value.Data.Video.Height; if (IsPortrait) { var aspect = (double)originalVideoWidth / (double)originalVideoHeight; var newVideoHeight = VideoStackLayout.Width / aspect; var borderHeight = (VideoStackLayout.Height - newVideoHeight) / 2.0; var rect = new Rectangle() { Left = VideoStackLayout.X, Top = VideoStackLayout.Y + borderHeight, Width = VideoStackLayout.Width, Height = newVideoHeight }; if (rect.X != VideoStackLayout.X || rect.Y != VideoStackLayout.Y || rect.Width != VideoStackLayout.Width || rect.Height != VideoStackLayout.Height) { AbsoluteLayout.SetLayoutFlags(VideoStackLayout, AbsoluteLayoutFlags.None); AbsoluteLayout.SetLayoutBounds(VideoStackLayout, rect); } } else { var aspect = (double)originalVideoHeight / (double)originalVideoWidth; var newVideoWidth = VideoStackLayout.Height / aspect; var borderWidth = (VideoStackLayout.Width - newVideoWidth) / 2.0; var rect = new Rectangle() { Left = VideoStackLayout.X + borderWidth, Top = VideoStackLayout.Y, Width = newVideoWidth, Height = VideoStackLayout.Height }; if (rect.X != VideoStackLayout.X || rect.Y != VideoStackLayout.Y || rect.Width != VideoStackLayout.Width || rect.Height != VideoStackLayout.Height) { AbsoluteLayout.SetLayoutFlags(VideoStackLayout, AbsoluteLayoutFlags.None); AbsoluteLayout.SetLayoutBounds(VideoStackLayout, rect); } } } } catch (Exception ex) { _loggingService.Error(ex); } }