public HttpResponseMessage GetUserBadges(string id, string sortByKey, bool isAscending, int pageIndex, int pageSize) { if (ValidationService.AuthorizeToken(GetToken(), "get:/api/badge/userbadges?id=&sortByKey=&isAscending=&pageIndex=&pageSize=") == false) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("无访问权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); } Guid userId = new Guid(id); User user = myService.FindUser(userId); User currentUser = ValidationService.FindUserWithToken(GetToken()); //如果当前用户和user都是volunteer,必须是自己或者好友才能调用该web api看到badge if (user.UserRole.Contains(Role.Volunteer) && currentUser.UserRole.Contains(Role.Volunteer)) { if (currentUser.Id != userId) { if (FriendService.CheckIfWeAreFriends(currentUser.Id, userId) == false) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent("无访问权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); } } } List <BadgeEntity> source = BadgeService.FindAllUserGrantedBadgeEntity(userId, sortByKey, isAscending, pageIndex, pageSize); var result = transformBadgeEntityToListShow(source); StringWriter tw = new StringWriter(); JsonSerializer jsonSerializer = new JsonSerializer(); jsonSerializer.Serialize(tw, result, result.GetType()); return(new HttpResponseMessage { Content = new StringContent(tw.ToString(), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); }
public async void ServiceShouldSaveNewBadge() { //arrange Badge dummyBadge = new Badge { Id = 1 }; var mockBadgeRepository = new Mock <IBadgeRepository>(); mockBadgeRepository.Setup(ms => ms.AddAsync(It.IsAny <Badge>())); var mockUnitOfWork = new Mock <IUnitOfWork>(); mockUnitOfWork.Setup(_ => _.Badges).Returns(mockBadgeRepository.Object); var userManagerMock = MockUserManager <User>(); userManagerMock.Setup(um => um.Users).Returns(_users.AsQueryable); BadgeService BadgeService = new BadgeService(mockUnitOfWork.Object, userManagerMock.Object); //act var BadgeSaved = BadgeService.CreateBadge(dummyBadge).Result; BadgeSaved.Should().NotBeNull(); BadgeSaved.Should().Be(dummyBadge, because: "the Badge that was saved should be returned by the service."); mockBadgeRepository.Verify(_ => _.AddAsync(It.IsAny <Badge>()), Times.Once); mockUnitOfWork.Verify(_ => _.CommitAsync(), Times.Once()); }
public HttpResponseMessage GetUserBadgeDetail(string id, string badgeName) { if (ValidationService.AuthorizeToken(GetToken(), "get:/api/badge/userbadgedetail?id=&badgename=") == false) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("无访问权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); } List <BadgeEntity> badgeEntities = BadgeService.FindAllUserGrantedBadgeEntity(new Guid(id)); foreach (BadgeEntity badgeEntity in badgeEntities) { if (badgeEntity.BadgeName == badgeName) { BadgeDescription badgeDescription = BadgeService.FindBadgeDescriptionByName(badgeEntity.BadgeName); var result = new { badgeName = badgeEntity.BadgeName, badgeDescription = badgeDescription.Description, badgePicture = badgeDescription.Picture, badgeGrantedTime = badgeEntity.GrantedTime, badgeRequirementDescription = badgeDescription.RequirementDescription.Values }; StringWriter tw = new StringWriter(); JsonSerializer jsonSerializer = new JsonSerializer(); jsonSerializer.Serialize(tw, result, result.GetType()); return(new HttpResponseMessage { Content = new StringContent(tw.ToString(), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } } return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent("未找到该badge", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); }
public void ProducesSystemHealthBadge(BadgeStatus status) { // Arrange var badgeService = new BadgeService(); var report = new Mock <HealthReport>(); report .SetupGet(rep => rep.Health) .Returns(status == BadgeStatus.Success ? 94 : (status == BadgeStatus.Neutural ? 81 : 56)); // Act var badge = badgeService.GetSystemHealthBadge(report.Object); // Assert Assert.Equal(status, badge.Status); Assert.NotEqual(0, badge.TitleWidth); Assert.NotEqual(0, badge.MessageWidth); switch (status) { case BadgeStatus.Success: Assert.Contains(94.ToString(), badge.Message); break; case BadgeStatus.Neutural: Assert.Contains(81.ToString(), badge.Message); break; case BadgeStatus.Failure: Assert.Contains(56.ToString(), badge.Message); break; } Assert.Equal("System health".ToLower(), badge.Title.ToLower()); }
public Profile() { this.InitializeComponent(); User = new AppUser(); US = new UserService(Config.AppConfig.ApiKey, Config.AppConfig.UserAgent, User.Token); BS = new BadgeService(Config.AppConfig.ApiKey, Config.AppConfig.UserAgent, User.Token); }
public void ProducesUptimeBadge(BadgeStatus status) { // Act var badge = new BadgeService().GetUptimeBadge( "the-url.com", status == BadgeStatus.Success ? 98 : (status == BadgeStatus.Neutural ? 90 : 80) ); // Assert Assert.Equal(status, badge.Status); Assert.NotEqual(0, badge.TitleWidth); Assert.NotEqual(0, badge.MessageWidth); switch (status) { case BadgeStatus.Success: Assert.Contains(98.ToString(), badge.Message); break; case BadgeStatus.Neutural: Assert.Contains(90.ToString(), badge.Message); break; case BadgeStatus.Failure: Assert.Contains(80.ToString(), badge.Message); break; } Assert.Contains("uptime", badge.Title.ToLower()); Assert.Contains("the-url.com", badge.Title.ToLower()); }
public void ProducesMetricHealthBadge(BadgeStatus status) { // Arrange var badgeService = new BadgeService(); var label = status == BadgeStatus.Success ? AutoLabels.Normal : ( status == BadgeStatus.Neutural ? AutoLabels.Warning : AutoLabels.Critical ); // Act var badge = badgeService .GetMetricHealthBadge( "the-source", Metrics.CpuLoad, label ); // Assert Assert.Equal(status, badge.Status); Assert.NotEqual(0, badge.TitleWidth); Assert.NotEqual(0, badge.MessageWidth); Assert.Contains("the-source", badge.Title.ToLower()); Assert.Contains(Metrics.CpuLoad.ToString().ToLower(), badge.Title.ToLower()); Assert.Contains(label.ToString().ToLower(), badge.Message.ToLower()); }
/// <summary> /// Sends server control content to a provided <see cref="T:System.Web.UI.HtmlTextWriter" /> object, which writes the content to be rendered on the client. /// </summary> /// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter" /> object that receives the server control content.</param> protected override void Render(HtmlTextWriter writer) { #pragma warning disable CS0618 // Type or member is obsolete var personBadgeCache = new PersonBadgeCache(BadgeCache); #pragma warning restore CS0618 // Type or member is obsolete var badgeComponent = BadgeCache?.BadgeComponent; if (badgeComponent == null) { return; } var entity = Entity; if (entity == null) { entity = ContextEntityBlock?.Entity; } if (entity == null) { return; } if (!BadgeService.DoesBadgeApplyToEntity(BadgeCache, entity)) { return; } try { badgeComponent.ParentContextEntityBlock = ContextEntityBlock; badgeComponent.Entity = entity; badgeComponent.Render(BadgeCache, writer); #pragma warning disable CS0618 // Type or member is obsolete badgeComponent.Render(personBadgeCache, writer); #pragma warning restore CS0618 // Type or member is obsolete var script = badgeComponent.GetWrappedJavaScript(BadgeCache); if (!script.IsNullOrWhiteSpace()) { ScriptManager.RegisterStartupScript(this, GetType(), $"badge_{ClientID}", script, true); } } catch (Exception ex) { var errorMessage = $"An error occurred rendering badge: {BadgeCache?.Name }, badge-id: {BadgeCache?.Id}"; ExceptionLogService.LogException(new Exception(errorMessage, ex)); var badgeNameClass = BadgeCache?.Name.ToLower().RemoveAllNonAlphaNumericCharacters() ?? "error"; writer.Write($"<div class='badge badge-{badgeNameClass} badge-id-{BadgeCache?.Id} badge-error' data-toggle='tooltip' data-original-title='{errorMessage}'>"); writer.Write($" <i class='fa fa-exclamation-triangle badge-icon text-warning'></i>"); writer.Write("</div>"); } finally { const string script = "$('.badge[data-toggle=\"tooltip\"]').tooltip({html: true}); $('.badge[data-toggle=\"popover\"]').popover();"; ScriptManager.RegisterStartupScript(this, this.GetType(), "badge-popover", script, true); } }
public void ProducesIndividualHealthBadge(BadgeStatus status) { // Act var badge = new BadgeService().GetMetricHealthBadge( "the-source", Metrics.CpuLoad, status == BadgeStatus.Success ? AutoLabels.Normal : (status == BadgeStatus.Neutural ? AutoLabels.Warning : AutoLabels.Critical) ); // Assert Assert.Equal(status, badge.Status); Assert.NotEqual(0, badge.TitleWidth); Assert.NotEqual(0, badge.MessageWidth); switch (status) { case BadgeStatus.Success: Assert.Contains(AutoLabels.Normal.ToString().ToLower(), badge.Message.ToLower()); break; case BadgeStatus.Neutural: Assert.Contains(AutoLabels.Warning.ToString().ToLower(), badge.Message.ToLower()); break; case BadgeStatus.Failure: Assert.Contains(AutoLabels.Critical.ToString().ToLower(), badge.Message.ToLower()); break; } Assert.Contains(Metrics.CpuLoad.ToString().ToLower(), badge.Title.ToLower()); Assert.Contains("the-source", badge.Title.ToLower()); }
public MessagesController(IHubContext <ChatHub> hubContext, MessagesService messagesService, MembersService membersService, BadgeService badgeService) { this.hubContext = hubContext; this.messagesService = messagesService; this.membersService = membersService; this.badgeService = badgeService; }
public void VoteDownPost(VoteBadgeViewModel voteUpBadgeViewModel) { using (var unitOfwork = UnitOfWorkManager.NewUnitOfWork()) { try { var databaseUpdateNeededOne = BadgeService.ProcessBadge(BadgeType.VoteDown, CurrentMember, MemberPointsService, ActivityService); if (databaseUpdateNeededOne) { unitOfwork.SaveChanges(); } var post = PostService.Get(voteUpBadgeViewModel.PostId); var member = MemberService.Get(post.MemberId); var databaseUpdateNeededTwo = BadgeService.ProcessBadge(BadgeType.VoteDown, member, MemberPointsService, ActivityService); if (databaseUpdateNeededTwo) { unitOfwork.SaveChanges(); } if (databaseUpdateNeededOne || databaseUpdateNeededTwo) { unitOfwork.Commit(); } } catch (Exception ex) { unitOfwork.Rollback(); LogError(ex); } } }
/// <summary> /// Sends server control content to a provided <see cref="T:System.Web.UI.HtmlTextWriter" /> object, which writes the content to be rendered on the client. /// </summary> /// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter" /> object that receives the server control content.</param> protected override void Render(HtmlTextWriter writer) { #pragma warning disable CS0618 // Type or member is obsolete var personBadgeCache = new PersonBadgeCache(BadgeCache); #pragma warning restore CS0618 // Type or member is obsolete var badgeComponent = BadgeCache?.BadgeComponent; if (badgeComponent != null) { var contextEntityBlock = ContextEntityBlock; if (contextEntityBlock != null) { if (BadgeService.DoesBadgeApplyToEntity(BadgeCache, contextEntityBlock.Entity)) { badgeComponent.ParentContextEntityBlock = contextEntityBlock; badgeComponent.Entity = contextEntityBlock.Entity; badgeComponent.Render(BadgeCache, writer); #pragma warning disable CS0618 // Type or member is obsolete badgeComponent.Render(personBadgeCache, writer); #pragma warning restore CS0618 // Type or member is obsolete const string script = "$('.badge[data-toggle=\"tooltip\"]').tooltip({html: true}); $('.badge[data-toggle=\"popover\"]').popover();"; ScriptManager.RegisterStartupScript(this, this.GetType(), "badge-popover", script, true); } } } }
public ActionResult TicketVerification(AccountTicketVerificationViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = DataService.PerThread.BaseUserSet.OfType <User>().SingleOrDefault(x => x.Id == UserContext.Current.Id); if (user == null) { throw new Exception("Перезайдите"); } if (!ApiService.CheckPassword(model.TicketCode, model.TempPass)) { throw new ValidationException("Неверный одноразовый пароль"); } user.IsTicketVerified = true; DataService.PerThread.SaveChanges(); BadgeService.AwardUser <TicketVerifiedBadge>(user.Id); return(RedirectToAction("profile", "user")); }
public IActionResult Create([FromHeader(Name = USER_HEADER)] int userUtn, [FromBody] CreateActivityParameter createActivityParameter) { var user = GetUserBytUtn(userUtn); try { CreateUserActivity(user, createActivityParameter); BadgeService.GeneraterNewBadges(user.UserID); CommunicationService.GenerateNewCommunications(user.UserID); } catch (NotExistingUserException) { return(BadRequest(new ProblemDetails { Type = "https://www.assura.ch/problems/NotExistingUserException", Title = HttpStatusCode.BadRequest.ToString(), Status = (int)HttpStatusCode.BadRequest, Detail = $"No user with the UTN [{userUtn}] exist.", Instance = HttpContext.Request?.Path })); } catch (AlreadyExistingUserActivityException) { return(BadRequest(new ProblemDetails { Type = "https://www.assura.ch/problems/AlreadyExistingUserActivity", Title = HttpStatusCode.BadRequest.ToString(), Status = (int)HttpStatusCode.BadRequest, Detail = $"An activity with the externalId [{createActivityParameter.ExternalId}] already exist and we don't allow duplicates.", Instance = HttpContext.Request?.Path })); } catch (NotExistingActivityTypeCodeException) { return(BadRequest(new ProblemDetails { Type = "https://www.assura.ch/problems/NotExistingActivityTypeCode", Title = HttpStatusCode.BadRequest.ToString(), Status = (int)HttpStatusCode.BadRequest, Detail = $"Invalid Activity Type Code : [{createActivityParameter.ActivityTypeCode}]", Instance = HttpContext.Request?.Path })); } catch (Exception) { var result = new ObjectResult(new ProblemDetails { Type = "https://www.assura.ch/problems/NotExistingActivityTypeCode", Title = HttpStatusCode.InternalServerError.ToString(), Status = (int)HttpStatusCode.InternalServerError, Detail = "Invalid Activity Type Code", Instance = HttpContext.Request?.Path }); result.StatusCode = (int)HttpStatusCode.InternalServerError; return(result); } return(Ok()); }
protected void Application_Start() { // Start unity var unityContainer = UnityHelper.Start(); // Register routes AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); GlobalConfiguration.Configure(RegAPI); GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(unityContainer); RegisterRoutes(RouteTable.Routes); // Run scheduled tasks ScheduledRunner.Run(unityContainer); // Register Data annotations DataAnnotationsModelValidatorProviderExtensions.RegisterValidationExtensions(); // Store the value for use in the app Application["Version"] = AppHelpers.GetCurrentVersionNo(); // If the same carry on as normal LoggingService.Initialise(ConfigUtils.GetAppSettingInt32("LogFileMaxSizeBytes", 10000)); LoggingService.Error("START APP"); // Set default theme var defaultTheme = "Metro"; // Only load these IF the versions are the same if (AppHelpers.SameVersionNumbers()) { // Get the theme from the database. defaultTheme = SettingsService.GetSettings().Theme; // Do the badge processing using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { try { BadgeService.SyncBadges(); unitOfWork.Commit(); } catch (Exception ex) { LoggingService.Error(string.Format("Error processing badge classes: {0}", ex.Message)); } } } // Set the view engine ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new ForumViewEngine(defaultTheme)); // Initialise the events EventManager.Instance.Initialize(LoggingService); }
public GiversController(GiversService giversService, MembersService membersService, BadgeService badgeService, FileService fileService, IHostingEnvironment environment) { this.giversService = giversService; this.membersService = membersService; this.badgeService = badgeService; this.fileService = fileService; this.hostingEnvironment = environment; }
private void usePictureCommand() { var dataService = new DataService(fileService); var badgeService = new BadgeService(fileService); dataService.SavePhotoData(_currentFile, _score); badgeService.AddRecord(_score); this.eventAggregator.GetEvent <PhotoChangesEvent>().Publish(dataService.LoadPhotoData().ToList()); this.navigationService.NavigateAsync(@"MainTabbedPage\SmileListPage"); }
protected void Application_Start() { //先读config Jtext103.StringConfig.ConfigString.Load(HttpRuntime.AppDomainAppPath + "Static\\StringConfig"); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); //BundleConfig.RegisterBundles(BundleTable.Bundles); Configure(System.Web.Http.GlobalConfiguration.Configuration); string db = ConfigurationSettings.AppSettings["DataBase"]; string eventHandler = ConfigurationSettings.AppSettings["EventHandler"]; string connection = @"mongodb://115.156.252.5:27017"; //new service and inject to entity MongoDBRepository <Entity> entityRepository = new MongoDBRepository <Entity>(connection, db, "volunteer"); MongoDBRepository <Message> messageRepository = new MongoDBRepository <Message>(connection, db, "message"); MongoDBRepository <Message> feedRepository = new MongoDBRepository <Message>(connection, db, "feed"); MongoDBRepository <TagEntity> activityTagRepository = new MongoDBRepository <TagEntity>(connection, db, "activityTag"); MongoDBRepository <TagEntity> affiliationRepository = new MongoDBRepository <TagEntity>(connection, db, "affiliation"); MongoDBRepository <TokenModel> tokenRepository = new MongoDBRepository <TokenModel>(connection, db, "token"); MongoDBRepository <AuthorizationModel> authorizationRepository = new MongoDBRepository <AuthorizationModel>(connection, "Volunteer", "authorization"); MongoDBRepository <Event> eventRepository = new MongoDBRepository <Event>(connection, db, "event"); MongoDBRepository <Subscriber> subscriberRepository = new MongoDBRepository <Subscriber>(connection, db, "subscriber"); MongoDBRepository <BadgeDescription> badgeDescriptionRepository = new MongoDBRepository <BadgeDescription>(connection, db, "badgeDescription"); MongoDBRepository <BadgeEntity> badgeEntityRepository = new MongoDBRepository <BadgeEntity>(connection, db, "badgeEntity"); MongoDBRepository <FriendRelationshipEntity> friendRelationshipEntityRepository = new MongoDBRepository <FriendRelationshipEntity>(connection, db, "friendRelationship"); MongoDBRepository <ActionValidationModel> actionValidationRepository = new MongoDBRepository <ActionValidationModel>(connection, db, "actionValidation"); MongoDBRepository <CommentEntity> commentRepository = new MongoDBRepository <CommentEntity>(connection, db, "comment"); MongoDBRepository <BlogPostEntity> summaryRepository = new MongoDBRepository <BlogPostEntity>(connection, db, "summary"); //初始化service VolunteerService myService = new VolunteerService(entityRepository); TokenService tokenService = new TokenService(tokenRepository); MessageService messageService = new MessageService(messageRepository); MessageService feedService = new MessageService(feedRepository); TagService activityTagService = new TagService(activityTagRepository); TagService affiliationService = new TagService(affiliationRepository); ActionValidationService actionValidationService = new ActionValidationService(actionValidationRepository); BlogService blogService = new BlogService(commentRepository, summaryRepository); Entity.SetServiceContext(myService); EventService.InitService(eventRepository, subscriberRepository, 100, 1000, eventHandler); BadgeService.InitService(badgeDescriptionRepository, badgeEntityRepository); FriendService.InitService(friendRelationshipEntityRepository); ValidationService.InitService(tokenService, myService, authorizationRepository); myService.InitVolunteerService(messageService, feedService, activityTagService, affiliationService, actionValidationService, blogService); //新建badgeDescription BadgeService.RegisterBadgeDescriptions(getIBadge(EventService.EventHandlerList)); ShortMessageService shortMessageService = new ShortMessageService("VerifyShortMessageSenderAccount.xml"); MailService mailService = new MailService("NoReplyMailSenderAccount.xml"); //setActivityCover(myService); }
void gBadge_GridReorder(object sender, GridReorderEventArgs e) { var rockContext = new RockContext(); var service = new BadgeService(rockContext); var badges = service.Queryable().OrderBy(b => b.Order); service.Reorder(badges.ToList(), e.OldIndex, e.NewIndex); rockContext.SaveChanges(); BindGrid(); }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { Badge badge = null; var rockContext = new RockContext(); var badgeService = new BadgeService(rockContext); if (BadgeId != 0) { badge = badgeService.Get(BadgeId); } if (badge == null) { badge = new Badge(); badgeService.Add(badge); } badge.Name = tbName.Text; badge.Description = tbDescription.Text; badge.EntityTypeQualifierColumn = rtbQualifierColumn.Text; badge.EntityTypeQualifierValue = rtbQualifierValue.Text; badge.EntityTypeId = etpEntityType.SelectedEntityTypeId; if (!string.IsNullOrWhiteSpace(compBadgeType.SelectedValue)) { var badgeType = EntityTypeCache.Get(compBadgeType.SelectedValue.AsGuid()); if (badgeType != null) { badge.BadgeComponentEntityTypeId = badgeType.Id; } } badge.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, badge); if (!Page.IsValid) { return; } if (!badge.IsValid) { return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); badge.SaveAttributeValues(rockContext); }); NavigateToParentPage(); }
public async Task GetRecentWinnersAsync_Should_Return_Recent_Badge_Winners() { var mockBageStore = new Mock <IEmployeeBadgeRepository>(); var mockEmployeeStore = new Mock <IEmployeeRepository>(); mockBageStore.Setup(c => c.GetRecentBadgeWinners("one", 5)).ReturnsAsync(PagedEmployeeBadge); mockEmployeeStore.Setup(c => c.GetEmployee("1123")).ReturnsAsync(It.IsAny <Employee>); var BadgeService = new BadgeService(mockBageStore.Object, mockEmployeeStore.Object); var badges = await BadgeService.GetRecentBadgeWinners("one", 5); BadgeService.Should().NotBeNull(); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { BindEntityTypes(); lActionTitle.Text = ActionTitle.Add(Badge.FriendlyTypeName).FormatAsHtmlTitle(); BadgeId = PageParameter("BadgeId").AsInteger(); if (BadgeId != 0) { var badge = new BadgeService(new RockContext()).Get(BadgeId); if (badge != null) { lActionTitle.Text = ActionTitle.Edit(badge.Name).FormatAsHtmlTitle(); tbName.Text = badge.Name; tbDescription.Text = badge.Description; rtbQualifierValue.Text = badge.EntityTypeQualifierValue; rtbQualifierColumn.Text = badge.EntityTypeQualifierColumn; etpEntityType.SelectedEntityTypeId = badge.EntityTypeId; SyncBadgeComponentsWithEntityType(); var badgeComponentType = EntityTypeCache.Get(badge.BadgeComponentEntityTypeId); compBadgeType.SelectedValue = badgeComponentType.Guid.ToString().ToUpper(); BuildEditControls(badge, true); pdAuditDetails.SetEntity(badge, ResolveRockUrl("~")); } } else { // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } } else { if (!string.IsNullOrWhiteSpace(compBadgeType.SelectedValue)) { var badgeType = EntityTypeCache.Get(compBadgeType.SelectedValue.AsGuid()); if (badgeType != null) { var badge = new Badge { BadgeComponentEntityTypeId = badgeType.Id }; BuildEditControls(badge, false); } } } }
public ChallengesController(ILogger <ChallengesController> logger, ServiceFacade.Controller context, BadgeService badgeService, ChallengeService challengeService, SiteService siteService) : base(context) { _logger = Require.IsNotNull(logger, nameof(logger)); _badgeService = Require.IsNotNull(badgeService, nameof(badgeService)); _challengeService = Require.IsNotNull(challengeService, nameof(challengeService)); _siteService = Require.IsNotNull(siteService, nameof(SiteService)); PageTitle = "Challenges"; }
public HttpResponseMessage GetAllBadgeCount() { if (ValidationService.AuthorizeToken(GetToken(), "get:/api/badge/allbadgecount") == false) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("无访问权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); } var result = BadgeService.FindAllBadgeCount(); return(new HttpResponseMessage { Content = new StringContent(result.ToString(), System.Text.Encoding.GetEncoding("UTF-8"), "application/text") }); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); // WebApiConfig.Register(GlobalConfiguration.Configuration); System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); //This should be called once in the application live WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "Email", autoCreateTables: true); // Start unity var unityContainer = UnityHelper.Start(); // Run scheduled tasks ScheduledRunner.Run(unityContainer); // Register Data annotations DataAnnotationsModelValidatorProviderExtensions.RegisterValidationExtensions(); // Set default theme var defaultTheme = "Metro"; // Get the theme from the database. defaultTheme = SettingsService.GetSettings().Theme; // Do the badge processing using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { try { BadgeService.SyncBadges(); unitOfWork.Commit(); } catch (Exception exception) { LoggingService.Error(string.Format("Error processing badge classes: {0}", exception.Message)); LogService logservice = new LogService(); logservice.WriteError(exception.Message, exception.Message, exception.StackTrace, exception.Source); } } // Initialise the events EventManager.Instance.Initialize(LoggingService); }
public void AfterBadgeAwarded() { EventManager.Instance.AfterBadgeAwarded += _EventManagerInstance_AfterBadgeAwarded; var badgeRepository = Substitute.For <IBadgeRepository>(); var api = Substitute.For <IMVCForumAPI>(); var loggingService = Substitute.For <ILoggingService>(); var localisationService = Substitute.For <ILocalizationService>(); var badgeService = new BadgeService(badgeRepository, api, loggingService, localisationService, _activityService); badgeService.SyncBadges(); // Create a user with one post with one vote var post = new Post { Id = Guid.NewGuid(), Votes = new List <Vote> { new Vote { Id = Guid.NewGuid() } }, }; var user = new MembershipUser { Posts = new List <Post> { post }, Badges = new List <Badge>(), BadgeTypesTimeLastChecked = new List <BadgeTypeTimeLastChecked> { new BadgeTypeTimeLastChecked { BadgeType = BadgeType.VoteUp.ToString(), TimeLastChecked = BadgeServiceTests.GetTimeAllowsBadgeUpdate() } } }; badgeRepository.Get(Arg.Any <Guid>()).Returns(new Badge { Name = "PosterVoteUp" }); badgeService.ProcessBadge(BadgeType.VoteUp, user); Assert.IsTrue(user.Badges.Count == 1); Assert.IsTrue(user.Badges[0].Name == "PosterVoteUp" || user.Badges[0].Name == BadgeServiceTests.NameTestVoteUp); // Event has been called test Assert.IsTrue(user.Email == TestString); EventManager.Instance.AfterBadgeAwarded -= _EventManagerInstance_AfterBadgeAwarded; }
public ActionResult Badges(DialoguePage page) { using (UnitOfWorkManager.NewUnitOfWork()) { var allBadges = BadgeService.GetallBadges(); var badgesListModel = new AllBadgesViewModel(page) { AllBadges = allBadges, PageTitle = Lang("Badge.AllBadges.PageTitle") }; return(View(PathHelper.GetThemeViewPath("Badges"), badgesListModel)); } }
public void ProducesSystemHealthBadgeNoData() { // Arrange var badgeService = new BadgeService(); // Act var badge = badgeService.GetSystemHealthBadge(new HealthReport()); // Assert Assert.Equal(BadgeStatus.Failure, badge.Status); Assert.NotEqual(0, badge.TitleWidth); Assert.NotEqual(0, badge.MessageWidth); Assert.Contains(0.ToString(), badge.Message); Assert.Equal("System health".ToLower(), badge.Title.ToLower()); }
public TriggersController(ILogger <TriggersController> logger, ServiceFacade.Controller context, BadgeService badgeService, SiteService siteService, TriggerService triggerService, VendorCodeService vendorCodeService) : base(context) { _logger = Require.IsNotNull(logger, nameof(logger)); _badgeService = Require.IsNotNull(badgeService, nameof(badgeService)); _siteService = Require.IsNotNull(siteService, nameof(SiteService)); _triggerService = Require.IsNotNull(triggerService, nameof(triggerService)); _vendorCodeService = Require.IsNotNull(vendorCodeService, nameof(vendorCodeService)); PageTitle = "Triggers"; }
public async void Get_null_record() { var mock = new ServiceMockFacade <IBadgeRepository>(); mock.RepositoryMock.Setup(x => x.Get(It.IsAny <int>())).Returns(Task.FromResult <Badge>(null)); var service = new BadgeService(mock.LoggerMock.Object, mock.RepositoryMock.Object, mock.ModelValidatorMockFactory.BadgeModelValidatorMock.Object, mock.BOLMapperMockFactory.BOLBadgeMapperMock, mock.DALMapperMockFactory.DALBadgeMapperMock); ApiBadgeResponseModel response = await service.Get(default(int)); response.Should().BeNull(); mock.RepositoryMock.Verify(x => x.Get(It.IsAny <int>())); }
public void AfterBadgeAwarded() { EventManager.Instance.AfterBadgeAwarded += _EventManagerInstance_AfterBadgeAwarded; var badgeRepository = Substitute.For<IBadgeRepository>(); var api = Substitute.For<IMVCForumAPI>(); var loggingService = Substitute.For<ILoggingService>(); var localisationService = Substitute.For<ILocalizationService>(); var badgeService = new BadgeService(badgeRepository, api, loggingService, localisationService, _activityService); badgeService.SyncBadges(); // Create a user with one post with one vote var post = new Post { Id = Guid.NewGuid(), Votes = new List<Vote> { new Vote { Id = Guid.NewGuid() } }, }; var user = new MembershipUser { Posts = new List<Post> { post }, Badges = new List<Badge>(), BadgeTypesTimeLastChecked = new List<BadgeTypeTimeLastChecked> { new BadgeTypeTimeLastChecked { BadgeType = BadgeType.VoteUp.ToString() , TimeLastChecked = BadgeServiceTests.GetTimeAllowsBadgeUpdate()} } }; badgeRepository.Get(Arg.Any<Guid>()).Returns(new Badge { Name = "PosterVoteUp" }); badgeService.ProcessBadge(BadgeType.VoteUp, user); Assert.IsTrue(user.Badges.Count == 1); Assert.IsTrue(user.Badges[0].Name == "PosterVoteUp" || user.Badges[0].Name == BadgeServiceTests.NameTestVoteUp); // Event has been called test Assert.IsTrue(user.Email == TestString); EventManager.Instance.AfterBadgeAwarded -= _EventManagerInstance_AfterBadgeAwarded; }
public void Setup() { m_unitOfWork = new MemoryUnitOfWork(); m_repository = new MemoryRepository<Badge>(m_unitOfWork, (b) => null); m_target = new BadgeService(m_repository, m_unitOfWork); }
/// <summary> /// Initializes a new instance of the <see cref="TotalGeneratedBadgesBadgeBuilder"/> class. /// </summary> /// <param name="badgeService">The badge service.</param> public TotalGeneratedBadgesBadgeBuilder(BadgeService badgeService) : base("BadgesSharp") { Status = BadgeStatus.Success; Style.Success.Text = "{0:N0} badges generated".With(badgeService.CountBadges()); }
public void BeforeBadgeAwardedAllow() { EventManager.Instance.BeforeBadgeAwarded += _EventManagerInstance_BeforeBadgeAwardedAllow; var badgeRepository = Substitute.For<IBadgeRepository>(); var api = Substitute.For<IMVCForumAPI>(); var loggingService = Substitute.For<ILoggingService>(); var localisationService = Substitute.For<ILocalizationService>(); var badgeService = new BadgeService(badgeRepository, api, loggingService, localisationService, _activityService); badgeService.SyncBadges(); // Create a user with one post with one vote var post = new Post { Id = Guid.NewGuid(), Votes = new List<Vote> { new Vote { Id = Guid.NewGuid() } }, }; var user = new MembershipUser { Posts = new List<Post> { post }, Badges = new List<Badge>(), BadgeTypesTimeLastChecked = new List<BadgeTypeTimeLastChecked> { new BadgeTypeTimeLastChecked { BadgeType = BadgeType.VoteUp.ToString() , TimeLastChecked = BadgeServiceTests.GetTimeAllowsBadgeUpdate()} } }; badgeRepository.Get(Arg.Any<Guid>()).Returns(new Badge{Name="testbadge"}); badgeService.ProcessBadge(BadgeType.VoteUp, user); // Event should have cancelled the update Assert.IsTrue(user.Badges.Count == 2); EventManager.Instance.BeforeBadgeAwarded -= _EventManagerInstance_BeforeBadgeAwardedAllow; }