Example #1
0
        public ActionResult Create(BadgeAddModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var badgeToCreate = new Badge
            {
                Name = model.Name,
                Description = model.Description,
                Category = model.Category,
                ImageUrl = model.Category.ImageUrl,
                Creator = RepositoryFactory.UserRepository.Queryable.SingleOrDefault(
                    x => x.Identifier == CurrentUser.Identity.Name),
                CreatedOn = DateTime.UtcNow
            };

            foreach (var criterion in model.Criteria.Where(criteria => !string.IsNullOrWhiteSpace(criteria)))
            {
                badgeToCreate.AddCriteria(criterion);
            }

            if (badgeToCreate.BadgeCriterias.Count == 0)
            {
                Message = "You need to add at least one criteria to create a Badge.";
                return RedirectToAction("Index");
            }

            Message = "Congrats, your proposed badge has been forwarded to the proper dinosaur authorities.";
            RepositoryFactory.BadgeRepository.EnsurePersistent(badgeToCreate);

            return RedirectToAction("Index");
        }
Example #2
0
 public static Activity GenerateMappedRecord(Badge badge, MembershipUser user, DateTime timestamp)
 {
     return new Activity
                {
                    // badge=badgeId,user=userId
                    Data = KeyBadgeId + Equality + badge.Id + Separator + KeyUserId + Equality + user.Id,
                    Timestamp = timestamp,
                    Type = ActivityType.BadgeAwarded.ToString()
                };
 }
        public static void awardBadge(int userID)
        {
            var userInfo = (from user in db.UserMeta
                            where user.UserId == userID
                            select user).Single();

            Badge newBadge = new Badge() { Name = badgeName, UserId = userID, Created_At = StringToDateTime.ToUnixTimeStamp(DateTime.Now) };
            db.Badges.Add(newBadge);
            Message newMessage = new Message() { Content = "Hallo, \n U hebt een badge verdiend door uw eerste Tag aan te maken. \n De Badgenaam is: 1e Tag", ReceiverId = userID, SenderId = userID, Title = "Je hebt de tagbadge verdient" };
            db.Messages.Add(newMessage);
            db.SaveChanges();
        }
        public ActionResult Create(Badge badge)
        {
            if (ModelState.IsValid)
            {
                badge.Id = Guid.NewGuid();
                db.Badges.Add(badge);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(badge);
        }
Example #5
0
 public IEnumerable<Badge> Map(IEnumerable<XElement> elements)
 {
     var result = new List<Badge>();
     foreach (XElement element in elements)
     {
         var badge = new Badge();
         badge.Name = GetStringAttributeValue(element, "Name");
         badge.Date = GetDateAttributeValue(element, "Date");
         badge.UserId = GetIntAttributeValue(element, "UserId");
         result.Add(badge);
     }
     return result;
 }
        // POST api/Badge
        public HttpResponseMessage PostBadge(Badge badge)
        {
            if (ModelState.IsValid)
            {
                db.Badges.Add(badge);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, badge);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = badge.Id }));
                return response;
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
        // PUT api/Badge/5
        public HttpResponseMessage PutBadge(Guid id, Badge badge)
        {
            if (ModelState.IsValid && id == badge.Id)
            {
                db.Entry(badge).State = EntityState.Modified;

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    return Request.CreateResponse(HttpStatusCode.NotFound);
                }

                return Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
Example #8
0
 public void Label_for_new_owner()
 {
     Assert.Equal("Amare Osei - OWNER", Badge.Print(null, "Amare Osei", null));
 }
Example #9
0
 public void Label_for_new_employee()
 {
     Assert.Equal("Bogdan Rosario - MARKETING", Badge.Print(null, "Bogdan Rosario", "Marketing"));
 }
 public Badge Update(Badge item)
 {
     Repo.Update(item);
     Unit.SaveChanges();
     return(item);
 }
 partial void InsertBadge(Badge instance);
        public void EditBadge()
        {
            Console.Clear();
            Header();
            Console.WriteLine("=-=-=-=- Update a Badge -=-=-=-=");
            Console.WriteLine("What is the badge number to update:");
            int           badgeNum      = Convert.ToInt32(Console.ReadLine());
            Badge         badgeToUpdate = _repo.GetABadgeByID(badgeNum);
            List <string> doorsOnBadge  = new List <string>();

            if (badgeToUpdate != null)
            {
                doorsOnBadge = badgeToUpdate.Doors;
                bool looper = true;
                while (looper)
                {
                    Console.Clear();
                    Header();
                    Console.WriteLine("=-=-=-=- Update a Badge -=-=-=-=");
                    string doorsResult = string.Join(",", badgeToUpdate.Doors);
                    Console.WriteLine($"Badge #{badgeToUpdate.BadgeID} has access to doors: {doorsResult}.");
                    Console.WriteLine("What would you like to do?");
                    Console.WriteLine("     1> Remove a door");
                    Console.WriteLine("     2> Add a door");
                    Console.WriteLine("     3> Finish Updating Badge");
                    string menuSelect = Console.ReadLine();
                    switch (menuSelect)
                    {
                    case "1":
                        Console.WriteLine("Which door would you like to remove?");
                        string doorToRemove = Console.ReadLine();
                        doorsOnBadge.Remove(doorToRemove);
                        badgeToUpdate.Doors = doorsOnBadge;
                        Console.WriteLine("Door Removed");
                        doorsResult = string.Join(",", badgeToUpdate.Doors);
                        Console.WriteLine($"Badge #{badgeToUpdate.BadgeID} has access to doors: {doorsResult}.");
                        Console.WriteLine("Press any key to continue.");
                        Console.ReadKey();
                        break;

                    case "2":
                        Console.WriteLine("Which door would you like to add?");
                        string doorToAdd = Console.ReadLine();
                        doorsOnBadge.Add(doorToAdd);
                        badgeToUpdate.Doors = doorsOnBadge;
                        Console.WriteLine("Door Added");
                        doorsResult = string.Join(",", badgeToUpdate.Doors);
                        Console.WriteLine($"Badge #{badgeToUpdate.BadgeID} has access to doors: {doorsResult}.");
                        Console.WriteLine("Press any key to continue.");
                        Console.ReadKey();
                        break;

                    case "3":
                        looper = false;
                        break;
                    }
                }
                bool wasUpdate = _repo.UpdateExistingBadge(badgeNum, badgeToUpdate);
                if (wasUpdate == true)
                {
                    Console.WriteLine("Badge updated successfully");
                }
                else
                {
                    Console.WriteLine("Oops! Something went wrong.  Please try update again.");
                }
            }
            else
            {
                Console.WriteLine("Badge ID not found.");
            }
            Console.WriteLine("Press any key to return to the main menu");
            Console.ReadKey();
        }
Example #13
0
        public async Task <IActionResult> Create(EventsDetailViewModel model)
        {
            var requireSecretCode = await GetSiteSettingBoolAsync(
                SiteSettingKey.Events.RequireBadge);

            if (model.Event.AllDay)
            {
                if (model.Event.EndDate.HasValue && model.Event.StartDate > model.Event.EndDate)
                {
                    ModelState.AddModelError("Event.EndDate", "The End date cannot be before the Start date");
                }
            }
            else
            {
                if (model.Event.EndDate.HasValue && model.Event.StartDate.TimeOfDay
                    > model.Event.EndDate.Value.TimeOfDay)
                {
                    ModelState.AddModelError("Event.EndDate", "The End time cannot be before the Start time");
                }
            }
            if (model.UseLocation && !model.Event.AtLocationId.HasValue)
            {
                ModelState.AddModelError("Event.AtLocationId", "The At Location field is required.");
            }
            if (!model.UseLocation && !model.Event.AtBranchId.HasValue)
            {
                ModelState.AddModelError("Event.AtBranchId", "The At Branch field is required.");
            }
            if (model.IncludeSecretCode || requireSecretCode)
            {
                if (string.IsNullOrWhiteSpace(model.BadgeMakerImage) && model.BadgeUploadImage == null)
                {
                    ModelState.AddModelError("BadgemakerImage", "A badge is required.");
                }
                else if (model.BadgeUploadImage != null &&
                         (string.IsNullOrWhiteSpace(model.BadgeMakerImage) || !model.UseBadgeMaker) &&
                         (Path.GetExtension(model.BadgeUploadImage.FileName).ToLower() != ".jpg" &&
                          Path.GetExtension(model.BadgeUploadImage.FileName).ToLower() != ".jpeg" &&
                          Path.GetExtension(model.BadgeUploadImage.FileName).ToLower() != ".png"))
                {
                    ModelState.AddModelError("BadgeUploadImage", "Please use a .jpg or .png image.");
                }
            }
            else
            {
                ModelState.Remove(nameof(model.SecretCode));
                ModelState.Remove(nameof(model.AwardMessage));
                ModelState.Remove(nameof(model.AwardPoints));
            }

            if (!string.IsNullOrWhiteSpace(model.Event.ExternalLink))
            {
                try
                {
                    model.Event.ExternalLink = new UriBuilder(
                        model.Event.ExternalLink).Uri.AbsoluteUri;
                }
                catch (Exception)
                {
                    ModelState.AddModelError("Event.ExternalLink", "Invalid URL");
                }
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (model.Event.ChallengeId.HasValue)
                    {
                        model.Event.ChallengeGroupId = null;
                    }
                    if (model.Event.AllDay)
                    {
                        model.Event.StartDate = model.Event.StartDate.Date;
                        if (model.Event.EndDate.HasValue)
                        {
                            if (model.Event.EndDate.Value.Date == model.Event.StartDate.Date)
                            {
                                model.Event.EndDate = null;
                            }
                            else
                            {
                                model.Event.EndDate = model.Event.EndDate.Value.Date;
                            }
                        }
                    }
                    else
                    {
                        if (model.Event.EndDate.HasValue)
                        {
                            if (model.Event.EndDate.Value.TimeOfDay == model.Event.StartDate.TimeOfDay)
                            {
                                model.Event.EndDate = null;
                            }
                            else
                            {
                                model.Event.EndDate = model.Event.StartDate.Date
                                                      + model.Event.EndDate.Value.TimeOfDay;
                            }
                        }
                    }

                    int?triggerId = null;
                    if (model.IncludeSecretCode)
                    {
                        byte[] badgeBytes;
                        string filename;
                        if (!string.IsNullOrWhiteSpace(model.BadgeMakerImage) &&
                            (model.BadgeUploadImage == null || model.UseBadgeMaker))
                        {
                            var badgeString = model.BadgeMakerImage.Split(',').Last();
                            badgeBytes = Convert.FromBase64String(badgeString);
                            filename   = "badge.png";
                        }
                        else
                        {
                            using (var fileStream = model.BadgeUploadImage.OpenReadStream())
                            {
                                using (var ms = new MemoryStream())
                                {
                                    fileStream.CopyTo(ms);
                                    badgeBytes = ms.ToArray();
                                }
                            }
                            filename = Path.GetFileName(model.BadgeUploadImage.FileName);
                        }
                        Badge newBadge = new Badge()
                        {
                            Filename = filename
                        };
                        var badge = await _badgeService.AddBadgeAsync(newBadge, badgeBytes);

                        Trigger trigger = new Trigger
                        {
                            Name         = $"Event '{model.Event.Name}' code",
                            SecretCode   = model.SecretCode,
                            AwardMessage = model.AwardMessage,
                            AwardPoints  = model.AwardPoints,
                            AwardBadgeId = badge.Id,
                        };
                        triggerId = (await _triggerService.AddAsync(trigger)).Id;
                    }

                    var graEvent = model.Event;
                    if (model.UseLocation)
                    {
                        graEvent.AtBranchId = null;
                    }
                    else
                    {
                        graEvent.AtLocationId = null;
                    }
                    graEvent.IsActive = true;
                    graEvent.IsValid  = true;

                    if (triggerId.HasValue)
                    {
                        graEvent.RelatedTriggerId = triggerId;
                    }

                    await _eventService.Add(graEvent);

                    ShowAlertSuccess($"Event '{graEvent.Name}' created.");
                    if (graEvent.IsCommunityExperience)
                    {
                        return(RedirectToAction("CommunityExperiences"));
                    }
                    return(RedirectToAction("Index"));
                }
                catch (GraException gex)
                {
                    ShowAlertWarning("Could not create event: ", gex.Message);
                }
            }
            PageTitle = "Create Event";

            var systemList = await _siteService.GetSystemList(true);

            var branchList = await _siteService.GetBranches(model.SystemId, true);

            var locationList = await _eventService.GetLocations();

            var programList = await _siteService.GetProgramList();

            model.SystemList        = new SelectList(systemList, "Id", "Name");
            model.BranchList        = new SelectList(branchList, "Id", "Name");
            model.LocationList      = new SelectList(locationList, "Id", "Name");
            model.ProgramList       = new SelectList(programList, "Id", "Name");
            model.RequireSecretCode = requireSecretCode;
            return(View(model));
        }
        BadgeFolder GetBadgeFolder(Badge apuc)
        {
            DependencyObject findSource = apuc;

            // Find the ScatterViewItem object that is being touched.
            while (findSource != null)
            {
                findSource = VisualTreeHelper.GetParent(findSource);
                if (findSource is BadgeFolder)
                    return (BadgeFolder)findSource;
            }

            return null;
        }
        private void AddBadge(Badge badge, StackPanel list, bool achieved)
        {
            Grid grid = new Grid();
            grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
            grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
			grid.RowDefinitions.Add(new RowDefinition());
			grid.RowDefinitions.Add(new RowDefinition());
            Image image = new Image()
            {
                Width = 50,
                Height = 50,
				Source = new BitmapImage(new Uri(achieved ? "ms-appx:///Assets/brightBell.png" : "ms-appx:///Assets/dullBell.png", UriKind.Absolute))
            };
            Grid.SetColumn(image, 0);
            Grid.SetRow(image, 0);
			Grid.SetRowSpan(image, 2);

            TextBlock text = new TextBlock
            {
                Text = badge.Title,
                TextWrapping = TextWrapping.Wrap,
                FontSize = 25
            };
            Grid.SetColumn(text, 1);
            Grid.SetRow(text, 0);

			TextBlock description = new TextBlock
			{
				Text = badge.Description,
				TextWrapping = TextWrapping.Wrap,
				FontSize = 15
			};
			Grid.SetColumn(description, 1);
			Grid.SetRow(description, 1);

            grid.Children.Add(image);
			grid.Children.Add(text);
			grid.Children.Add(description);

            list.Children.Add(grid);
        }
Example #16
0
 public static MvcHtmlString UxBadge(this HtmlHelper helper, Badge badge)
 {
     return helper.RenderUxControl(badge);
 }
Example #17
0
 public static MvcHtmlString UxBadge(this HtmlHelper helper, string text, bool pullRight = false, string clientId = null)
 {
     var badge = new Badge(text, pullRight, clientId);
     return UxBadge(helper, badge);
 }
 public ActionResult Edit(Badge badge)
 {
     if (ModelState.IsValid)
     {
         db.Entry(badge).State = EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(badge);
 }
Example #19
0
        private static void PopulateDb(FluentConfiguration config)
        {
            using (var session = config.BuildSessionFactory().OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    PopulateLookups(session);

                    var studentRole = new Role(RoleNames.Student) {Name = "Student"};
                    var instructorRole = new Role(RoleNames.Instructor) {Name = "Instructor"};
                    var adminRole = new Role(RoleNames.Administrator) {Name = "Administrator"};
                    session.SaveOrUpdate(studentRole);
                    session.SaveOrUpdate(instructorRole);
                    session.SaveOrUpdate(adminRole);

                    var user = new User {Identifier = "postit"};
                    user.Profile = new Profile(user)
                        {
                            FirstName = "Scott",
                            LastName = "Kirkland",
                            Email = "*****@*****.**",
                            ImageUrl = WebConfigurationManager.AppSettings["DefaultProfilePictureUrl"]
                        };
                    user.Roles.Add(studentRole);

                    session.SaveOrUpdate(user);

                    var hermes = new User {Identifier = "hconrad"};
                    hermes.AssociateProfile(new Profile(hermes)
                        {
                            FirstName = "Hermes",
                            LastName = "Conrad",
                            Email = "*****@*****.**",
                            ImageUrl = WebConfigurationManager.AppSettings["DefaultProfilePictureUrl"]
                        });
                    hermes.Roles.Add(instructorRole);

                    session.SaveOrUpdate(hermes);

                    var farnsworth = new User { Identifier = "hfarnsworth" };
                    farnsworth.AssociateProfile(new Profile(farnsworth)
                    {
                        FirstName = "Hubert",
                        LastName = "Farnsworth",
                        Email = "*****@*****.**",
                        ImageUrl = WebConfigurationManager.AppSettings["DefaultProfilePictureUrl"]
                    });

                    session.SaveOrUpdate(farnsworth);

                    var instructor = new Instructor
                        {
                            FirstName = "Hubert",
                            LastName = "Farnsworth",
                            Email = "*****@*****.**",
                            Identifier = "hfarnworth",
                            User = farnsworth
                        };

                    var instructor2 = new Instructor
                    {
                        FirstName = "Hermes",
                        LastName = "Conrad",
                        Email = "*****@*****.**",
                        Identifier = "hconrad",
                        User = hermes
                    };

                    session.SaveOrUpdate(instructor);
                    session.SaveOrUpdate(instructor2);

                    var etype = new ExperienceType { Name = "Exploration", Icon = "icon-flag" };
                    session.SaveOrUpdate(etype);
                    session.SaveOrUpdate(new ExperienceType {Name = "Collaboration", Icon = "icon-group"});

                    var outcome = new Outcome {Name = "Outcome 1", Description = "Some outcome", ImageUrl = string.Empty};
                    session.SaveOrUpdate(outcome);
                    session.SaveOrUpdate(new Outcome
                        {
                            Name = "Super Skills",
                            Description = "Pretty good skillz",
                            ImageUrl = string.Empty
                        });

                    var experience = new Experience
                        {
                            Creator = user,
                            ExperienceType = etype,
                            Name = "Sample Experience",
                            Description = "This is a bit of text about exactly what I did in this experience",
                            Start = DateTime.Now,
                            Location = "moab, ut",
                            CoverImageUrl = "https://ucdbadges.blob.core.windows.net/publicimagesdev/e600f3de-a969-45af-b70b-7d2f5285e572"
                        };

                    experience.AddInstructor(instructor);
                    experience.AddInstructor(instructor2);

                    session.SaveOrUpdate(experience);

                    //Badges
                    var category = new BadgeCategory
                        {
                            Name = "SampleCategory",
                            ImageUrl = "https://ucdbadges.blob.core.windows.net/publicimagesdev/12da4d70-207a-45e5-b6e4-f1b418c1802a"
                        };

                    session.SaveOrUpdate(category);

                    var badge = new Badge
                        {
                            Approved = true,
                            Category = category,
                            CreatedOn = DateTime.UtcNow,
                            Name = "First Badge",
                            Description = "Really interesting badge for being awesome",
                            Creator = user,
                            ImageUrl = "https://ucdbadges.blob.core.windows.net/publicimagesdev/12da4d70-207a-45e5-b6e4-f1b418c1802a"
                        };

                    badge.AddCriteria("You need to do a, b, c");
                    badge.AddCriteria("Also you need to be a human");

                    session.SaveOrUpdate(badge);

                    tx.Commit();
                }

            }
        }
Example #20
0
 public void SendActivationConfirmation(Badge badge)
 {
     this.mailService.SendMail(badge.Owner.EmailAddresses[0], badge.ActivationMailConfirmationFrom, badge.ActivationMailConfirmationBody, badge.ActivationMailConfirmationSubject);
     this.smsService.Send(badge.Owner.Mobiles[0], badge.ActivationSmsConfirmation);
 }
 /// <summary>
 /// Clears the badge cache.
 /// </summary>
 /// <param name="controller">The controller.</param>
 /// <param name="badge">The badge.</param>
 public static void ClearBadgeCache(ApiController controller, Badge badge)
 {
     var cache = controller.Configuration.CacheOutputConfiguration().GetCacheOutputProvider(controller.Request);
     cache.RemoveStartsWith(MakeBadgeCacheKey(badge.Owner, badge.Repository, badge.Name));
     cache.RemoveStartsWith(MakeBadgeCacheKey("giacomelli", "BadgesSharp", "TotalGeneratedBadges"));
 }
Example #22
0
        public async Task <IActionResult> Edit(ProgramDetailViewModel model)
        {
            var currentProgram = await _siteService.GetProgramByIdAsync(model.Program.Id);

            if (string.IsNullOrWhiteSpace(model.Program.JoinBadgeName) &&
                (!string.IsNullOrWhiteSpace(model.BadgeMakerImage) ||
                 model.BadgeUploadImage != null ||
                 currentProgram.JoinBadgeId.HasValue))
            {
                ModelState.AddModelError("Program.JoinBadgeName", "Please provide a name for the badge");
            }

            if (!string.IsNullOrWhiteSpace(model.Program.JoinBadgeName) &&
                string.IsNullOrWhiteSpace(model.BadgeMakerImage) &&
                model.BadgeUploadImage == null &&
                currentProgram.JoinBadgeId.HasValue == false)
            {
                ModelState.AddModelError("BadgemakerImage", "Please provide an image for the badge.");
            }

            if (model.BadgeUploadImage != null &&
                (string.IsNullOrWhiteSpace(model.BadgeMakerImage) || !model.UseBadgeMaker) &&
                (Path.GetExtension(model.BadgeUploadImage.FileName).ToLower() != ".jpg" &&
                 Path.GetExtension(model.BadgeUploadImage.FileName).ToLower() != ".jpeg" &&
                 Path.GetExtension(model.BadgeUploadImage.FileName).ToLower() != ".png"))
            {
                ModelState.AddModelError("BadgeUploadImage", "Please use a .jpg or .png image.");
            }

            if (model.Program.AgeMaximum < model.Program.AgeMinimum)
            {
                ModelState.AddModelError("Program.AgeMaximum", "The maximum age cannot be lower than the minimum age.");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (model.BadgeUploadImage != null ||
                        !string.IsNullOrWhiteSpace(model.BadgeMakerImage))
                    {
                        byte[] badgeBytes;
                        string filename;
                        if (!string.IsNullOrWhiteSpace(model.BadgeMakerImage) &&
                            (model.BadgeUploadImage == null || model.UseBadgeMaker))
                        {
                            var badgeString = model.BadgeMakerImage.Split(',').Last();
                            badgeBytes = Convert.FromBase64String(badgeString);
                            filename   = "badge.png";
                        }
                        else
                        {
                            using (var fileStream = model.BadgeUploadImage.OpenReadStream())
                            {
                                using (var ms = new MemoryStream())
                                {
                                    fileStream.CopyTo(ms);
                                    badgeBytes = ms.ToArray();
                                }
                            }
                            filename = Path.GetFileName(model.BadgeUploadImage.FileName);
                        }
                        if (model.Program.JoinBadgeId.HasValue)
                        {
                            var existing = await _badgeService
                                           .GetByIdAsync(model.Program.JoinBadgeId.Value);

                            existing.Filename = Path.GetFileName(model.BadgePath);
                            await _badgeService.ReplaceBadgeFileAsync(existing, badgeBytes);
                        }
                        else
                        {
                            var newBadge = new Badge
                            {
                                Filename = filename
                            };
                            var badge = await _badgeService.AddBadgeAsync(newBadge, badgeBytes);

                            model.Program.JoinBadgeId = badge.Id;
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(model.Program.JoinBadgeName))
                    {
                        model.Program.JoinBadgeName = model.Program.JoinBadgeName.Trim();
                    }

                    model.Program.AskAge         = model.AgeValues >= 1;
                    model.Program.AgeRequired    = model.AgeValues == 2;
                    model.Program.AskSchool      = model.SchoolValues >= 1;
                    model.Program.SchoolRequired = model.SchoolValues == 2;
                    model.Program.Name           = model.Program.Name.Trim();
                    await _siteService.UpdateProgramAsync(model.Program);

                    ShowAlertSuccess($"Saved Program \"{model.Program.Name}\"!");
                    return(RedirectToAction(nameof(Edit), new { id = model.Program.Id }));
                }
                catch (GraException gex)
                {
                    ShowAlertDanger("Unable to edit Program: ", gex);
                }
            }
            var dailyLiteracyTipList = await _dailyLiteracyTipService.GetListAsync();

            var pointTranslationList = await _pointTranslationService.GetListAsync();

            model.DailyLiteracyTipList = new SelectList(dailyLiteracyTipList, "Id", "Name");
            model.PointTranslationList = new SelectList(pointTranslationList, "Id",
                                                        "TranslationName");
            PageTitle = "Edit Program";
            return(View("Detail", model));
        }
Example #23
0
 /// <summary>
 /// Constructor - useful when constructing a badge activity after reading database
 /// </summary>
 public BadgeActivity(Activity activity, Badge badge, MembershipUser user)
 {
     ActivityMapped = activity;
     Badge = badge;
     User = user;
 }
Example #24
0
 public void Delete(Badge badge)
 {
     _badgeRepository.Delete(badge);
 }
 partial void UpdateBadge(Badge instance);
Example #26
0
        public void SaveBadgeExtendedAttributes(Badge obj, GridView gv1, GridView gv2, GridView gv3, GridView gv4)
        {
            var    gv             = gv1;
            string checkedMembers = string.Empty;

            foreach (GridViewRow row in gv.Rows)
            {
                if (((CheckBox)row.FindControl("isMember")).Checked)
                {
                    checkedMembers = string.Format("{0},{1}", checkedMembers, ((Label)row.FindControl("CID")).Text);
                }
            }
            if (checkedMembers.Length > 0)
            {
                checkedMembers = checkedMembers.Substring(1, checkedMembers.Length - 1);
            }
            obj.UpdateBadgeCategories(checkedMembers);

            gv             = gv2;
            checkedMembers = string.Empty;
            foreach (GridViewRow row in gv.Rows)
            {
                if (((CheckBox)row.FindControl("isMember")).Checked)
                {
                    checkedMembers = string.Format("{0},{1}", checkedMembers, ((Label)row.FindControl("CID")).Text);
                }
            }
            if (checkedMembers.Length > 0)
            {
                checkedMembers = checkedMembers.Substring(1, checkedMembers.Length - 1);
            }
            obj.UpdateBadgeAgeGroups(checkedMembers);


            gv             = gv3;
            checkedMembers = string.Empty;
            foreach (GridViewRow row in gv.Rows)
            {
                if (((CheckBox)row.FindControl("isMember")).Checked)
                {
                    checkedMembers = string.Format("{0},{1}", checkedMembers, ((Label)row.FindControl("CID")).Text);
                }
            }
            if (checkedMembers.Length > 0)
            {
                checkedMembers = checkedMembers.Substring(1, checkedMembers.Length - 1);
            }
            obj.UpdateBadgeBranches(checkedMembers);

            gv             = gv4;
            checkedMembers = string.Empty;
            foreach (GridViewRow row in gv.Rows)
            {
                if (((CheckBox)row.FindControl("isMember")).Checked)
                {
                    checkedMembers = string.Format("{0},{1}", checkedMembers, ((Label)row.FindControl("CID")).Text);
                }
            }
            if (checkedMembers.Length > 0)
            {
                checkedMembers = checkedMembers.Substring(1, checkedMembers.Length - 1);
            }
            obj.UpdateBadgeLocations(checkedMembers);
        }
 public ActionResult BadgeAdd()
 {
     Badge newBadge = new Badge
     {
         Achievement = "",
         Description = ""
     };
     ViewBag.BadgeCategories = GetBadgeCategories();
     return View("Badge", newBadge);
 }
 public Badge Create(Badge item)
 {
     Repo.Create(item);
     Unit.SaveChanges();
     return(item);
 }
 public ActionResult BadgeSave(Badge b)
 {
     Badge badge;
     if (b.Id == null || b.Id == Guid.Empty)
     {
         badge = new Badge();
         db.Badges.Add(badge);
     }
     else
     {
         badge = db.Badges.FirstOrDefault(x => x.Id == b.Id);
     }
     badge.BadgeCategoryId = b.BadgeCategoryId;
     badge.Achievement = b.Achievement;
     badge.Description = b.Description;
     db.SaveChanges();
     return RedirectClient("/Mentor/Badges");
 }
Example #30
0
 public BadgeDrop(Badge badge, int x, int y, int width, int height)
     : base(Utilities.GetImgOfBadge(badge), x, y, width, height)
 {
     Badge = badge;
 }
Example #31
0
        /// <summary>
        /// Returns badges for a given user.
        /// API Uri: https://api.foursquare.com/v2/users/USER_ID/badges
        /// Documentation: https://developer.foursquare.com/docs/users/badges.html
        /// </summary>
        /// <returns></returns>
        public List<UnlockedBadge> GetBadges()
        {
            try {
                List<UnlockedBadge> UnlockedBadges = new List<UnlockedBadge>();
                // Get the badges
                String foursquareBadgeUri = String.Format("https://api.foursquare.com/v2/users/self/badges?oauth_token={0}{1}",
                    AccessToken,
                    EndpointHelper.GetVerifiedDateParamForApi());
                var responseBadges = WebRequestHelper.WebRequest(WebRequestHelper.Method.GET, foursquareBadgeUri.ToString(), string.Empty);
                var jsonBadges = JObject.Parse(responseBadges);

                if (int.Parse(jsonBadges["meta"]["code"].ToString()) == 200) {
                    List<UserBadgeCategory> UnlockedBadgeIds = new List<UserBadgeCategory>();
                    JArray badgeList = (JArray)jsonBadges["response"]["sets"]["groups"];
                    foreach (var fbi in badgeList) {
                        if (fbi["type"].ToString().Replace("\"", "").ToLower() != "all") {
                            foreach (var fbid in fbi["items"]) {
                                UserBadgeCategory tempBadgeCategory = new UserBadgeCategory();
                                switch (fbi["type"].ToString().Replace("\"", "").ToLower()) {
                                    case "foursquare":
                                        tempBadgeCategory.UserBadgeId = fbid.ToString().Replace("\"", "");
                                        tempBadgeCategory.Type = BadgeType.foursquare;
                                        UnlockedBadgeIds.Add(tempBadgeCategory);
                                        break;
                                    case "expertise":
                                        tempBadgeCategory.UserBadgeId = fbid.ToString().Replace("\"", "");
                                        tempBadgeCategory.Type = BadgeType.expertise;
                                        UnlockedBadgeIds.Add(tempBadgeCategory);
                                        break;
                                    case "partner":
                                        tempBadgeCategory.UserBadgeId = fbid.ToString().Replace("\"", "");
                                        tempBadgeCategory.Type = BadgeType.partner;
                                        UnlockedBadgeIds.Add(tempBadgeCategory);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                    }

                    if (UnlockedBadgeIds.Count > 0) {
                        foreach (UserBadgeCategory ubc in UnlockedBadgeIds) {
                            JObject b = JObject.Parse(jsonBadges["response"]["badges"][ubc.UserBadgeId].ToString());
                            UnlockedBadge ub = new UnlockedBadge();
                            if (b["id"] != null && (b["id"].ToString().Replace("\"", "") != b["badgeId"].ToString().Replace("\"", ""))) {
                                ub.BadgeId = b["id"].ToString().Replace("\"", "");

                                Badge badge = new Badge();
                                badge.Name = b["name"] != null ? b["name"].ToString().Replace("\"", "") : "";
                                badge.Description = b["description"] != null
                                    ? b["description"].ToString().Replace("\"", "")
                                    : b["hint"].ToString() != "" ? String.Format("Hint: {0}", b["hint"].ToString().Replace("\"", ""))
                                    : "No hint";
                                badge.FoursquareBadgeId = b["badgeId"] != null ? b["badgeId"].ToString().Replace("\"", "") : "";
                                if (b["image"]["prefix"] != null && b["image"]["name"] != null) {
                                    badge.ImageUri = b["image"]["prefix"].ToString().Replace("\"", "") + "{0}" + b["image"]["name"].ToString().Replace("\"", "");
                                } else
                                    badge.ImageUri = "";
                                badge.Type = ubc.Type;

                                // Create Checkins
                                if (b["unlocks"] != null) {
                                    foreach (var u in b["unlocks"]) {
                                        if (u["checkins"] != null) {
                                            foreach (var c in u["checkins"]) {
                                                Checkin checkin = new Checkin();
                                                checkin.CheckinId = c["id"] != null ? c["id"].ToString().Replace("\"", "") : "";
                                                checkin.CreatedAt = EndpointHelper.FromUnixTime(long.Parse(c["createdAt"].ToString().Replace("\"", "")));
                                                checkin.IsMayor = c["isMayor"] != null ? bool.Parse(c["isMayor"].ToString().Replace("\"", "")) : false;
                                                String checkinType = c["type"] != null ? c["type"].ToString().Replace("\"", "") : "";
                                                checkin.Type = checkinType;

                                                if (checkinType != "venueless") {
                                                    Venue v = new Venue();
                                                    v.VenueId = c["venue"]["id"] != null ? c["venue"]["id"].ToString().Replace("\"", "") : "";
                                                    v.Name = c["venue"]["name"] != null ? c["venue"]["name"].ToString().Replace("\"", "") : "";
                                                    v.ItemId = c["venue"]["itemId"] != null ? c["venue"]["itemId"].ToString().Replace("\"", "") : "";
                                                    v.ContactInfo = c["venue"]["contact"] != null ? Contact.Parse(c["venue"]["contact"].ToString()) : null;
                                                    v.LocationInfo = c["venue"]["location"] != null ? Location.Parse(c["venue"]["location"].ToString()) : null;
                                                    if (c["venue"]["categories"] != null && c["venue"]["categories"].ToString().Replace("\"", "") != "") {
                                                        JArray categories = (JArray)c["venue"]["categories"];
                                                        if (categories.Count > 0) {
                                                            v.Categories = new List<VenueCategory>();
                                                            foreach (var vc in categories) {
                                                                v.Categories.Add(VenueCategory.Parse(vc.ToString()));
                                                            }
                                                        } else
                                                            v.Categories = null;
                                                    } else
                                                        v.Categories = null;
                                                    v.Statistics = c["venue"]["stats"] != null ? VenueStatistics.Parse(c["venue"]["stats"].ToString()) : null;
                                                    v.Verified = c["venue"]["verified"] != null ? bool.Parse(c["venue"]["verified"].ToString().Replace("\"", "")) : true;
                                                    v.VenueUri = c["venue"]["url"] != null ? c["venue"]["url"].ToString().Replace("\"", "") : "";

                                                    checkin.CheckinVenue = v;
                                                }

                                                ub.Checkin = checkin;
                                            }
                                        }
                                    }
                                }

                                ub.Badge = badge;
                                ub.Level = b["level"] != null ? int.Parse(b["level"].ToString()) : 0;
                                UnlockedBadges.Add(ub);
                            }
                            //else
                            //{
                            //    var errorId = b["badgeId"];
                            //    return null;
                            //}
                        }
                    }
                }

                if (UnlockedBadges != null && UnlockedBadges.Count > 0)
                    return UnlockedBadges;
                return null;
            } catch (Exception ex) {
                string error = ex.Message;
                return null;
            }
        }
Example #32
0
 public void Label_for_owner()
 {
     Assert.Equal("[59] - Julie Sokato - OWNER", Badge.Print(59, "Julie Sokato", null));
 }
Example #33
0
        /// <summary>
        /// Adds the given content to the list of badges.
        /// This procedure modifies only the local in-memory content of the snippet.
        /// </summary>
        /// <param name="addingBadge"></param>
        public void AddBadge(Badge addingBadge)
        {
            if (addingBadge == null)
                return;

            //if the badge is not yet present in the list, add it:
            if (m_badges == null)
                m_badges = new List<Badge>();
            else
            {
                if (m_badges.Contains(addingBadge))
                    return;
            }

            m_badges.Add(addingBadge);
        }
Example #34
0
 public void Label_for_employee()
 {
     Assert.Equal("[17] - Ryder Herbert - MARKETING", Badge.Print(17, "Ryder Herbert", "Marketing"));
 }
Example #35
0
 /// <summary>
 /// Replaces the given content in the list of badges, if not yet present.
 /// This procedure modifies only the local in-memory content of the snippet.
 /// </summary>
 /// <param name="addingBadge"></param>
 /// <param name="existingBadge"></param>
 public void ReplaceBadge(Badge existingBadge, Badge newBadge)
 {
     if (m_badges == null)
         m_badges = new List<Badge>();
     if (existingBadge != null)
         m_badges.Remove(existingBadge);
     if ((newBadge != null) && !m_badges.Contains(newBadge))
         m_badges.Add(newBadge);
 }
Example #36
0
 public async Task <Badge> UpdateBadgeAsync(Badge badge)
 {
     badge.SiteId = GetCurrentSiteId();
     return(await _badgeRepository.AddSaveAsync(GetClaimId(ClaimType.UserId), badge));
 }
        public void Save_New_Created()
        {
            var badge = new Badge()
            {
                Owner = "owner1",
                Repository = "repository1",
                Name = "FxCop",
                Svg = "saved one"
            };

            m_target.SaveBadge(badge);
            m_unitOfWork.Commit();

            Assert.AreEqual(1, m_target.CountBadges());
            var actual = m_target.GetBadge("owner1", "repository1", "FxCop");
            Assert.IsNotNull(actual);
            Assert.AreEqual("owner1", actual.Owner);
        }
Example #38
0
 public ListItem(Badge badge)
 {
     this._badge = badge;
     _icon.Copy(BadgeBanner.Image(badge.Image));
     _label.Text(badge.Description);
 }
Example #39
0
 public void Add(Badge badge)
 {
     BadgeContext.GetDatabase().Insert(badge);
 }
Example #40
0
 /// <summary>
 /// New badge has been awarded
 /// </summary>
 /// <param name="badge"></param>
 /// <param name="user"> </param>
 /// <param name="timestamp"> </param>
 public void BadgeAwarded(Badge badge, MembershipUser user, DateTime timestamp)
 {
     var badgeActivity = BadgeActivity.GenerateMappedRecord(badge, user, timestamp);
     Add(badgeActivity);
 }
Example #41
0
        private void LoadBadges()
        {
            List <int> badgesIds = new List <int>();

            if (user.GetId() == 0)
            {
                badgesIds.Add(1);
                badgesIds.Add(3);
                badgesIds.Add(4);
                badgesIds.Add(5);
                badgesIds.Add(6);
            }
            else if (user.GetId() == 1)
            {
                badgesIds.Add(6);
                badgesIds.Add(4);
                badgesIds.Add(2);
                badgesIds.Add(1);
                badgesIds.Add(8);
            }
            else if (user.GetId() == 2)
            {
                badgesIds.Add(3);
                badgesIds.Add(1);
                badgesIds.Add(7);
                badgesIds.Add(6);
                badgesIds.Add(8);
            }
            else if (user.GetId() == 3)
            {
                badgesIds.Add(7);
                badgesIds.Add(1);
                badgesIds.Add(6);
                badgesIds.Add(8);
                badgesIds.Add(2);
            }
            else if (user.GetId() == 4)
            {
                badgesIds.Add(4);
                badgesIds.Add(3);
                badgesIds.Add(5);
                badgesIds.Add(8);
                badgesIds.Add(1);
            }

            for (int i = 0; i < 5; i++)
            {
                SqlCommand getBadge = new SqlCommand();
                getBadge.Connection  = Statics.conn;
                getBadge.CommandText = "SELECT * FROM Badges WHERE Id = @id";
                getBadge.Parameters.AddWithValue("@id", badgesIds[i]);

                SqlDataReader reader = getBadge.ExecuteReader();
                if (reader.Read())
                {
                    Badge badge = new Badge(int.Parse(reader[0].ToString()), reader[1].ToString(), reader[2].ToString(), null);

                    if (i == 0)
                    {
                        BadgeName1.Text = badge.GetName();
                        BadgeName.Text  = badge.GetName();
                        loadLogo(badge.GetId(), BadgePicture1);
                        loadLogo(badge.GetId(), BadgePicture);
                        atasareAvatar(ProfilePicture, user.GetId());
                    }
                    else if (i == 1)
                    {
                        BadgeName2.Text = badge.GetName();
                        loadLogo(badge.GetId(), BadgePicture2);
                    }
                    else if (i == 2)
                    {
                        BadgeName3.Text = badge.GetName();
                        loadLogo(badge.GetId(), BadgePicture3);
                    }
                    else if (i == 3)
                    {
                        BadgeName4.Text = badge.GetName();
                        loadLogo(badge.GetId(), BadgePicture4);
                    }
                    else if (i == 4)
                    {
                        BadgeName5.Text = badge.GetName();
                        loadLogo(badge.GetId(), BadgePicture5);
                    }
                }
                reader.Close();
            }
        }
Example #42
0
        public void TestGetBadgeByID()
        {
            Badge badgeByID = _badgeDictionary.GetBadgeByID(1);

            Assert.AreEqual(badgeByID, _entry1);
        }
        /// <summary>
        /// New badge has been awarded
        /// </summary>
        /// <param name="badge"></param>
        /// <param name="user"> </param>
        /// <param name="timestamp"> </param>
        public void BadgeAwarded(Badge badge, Member user, DateTime timestamp)
        {
            var badgeActivity = BadgeActivity.GenerateMappedRecord(badge, user, timestamp);

            Add(badgeActivity);
        }
        protected void DvItemCommand(object sender, DetailsViewCommandEventArgs e)
        {
            string returnURL = "~/ControlRoom/Modules/Setup/BadgeList.aspx";

            if (e.CommandName.ToLower() == "back")
            {
                Response.Redirect(returnURL);
            }
            if (e.CommandName.ToLower() == "refresh")
            {
                try
                {
                    odsData.DataBind();
                    //Page.DataBind();
                    dv.DataBind();
                    dv.ChangeMode(DetailsViewMode.Edit);


                    var masterPage = (IControlRoomMaster)Master;
                    if (masterPage != null)
                    {
                        masterPage.PageMessage = SRPResources.RefreshOK;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }

            if (e.CommandName.ToLower() == "add" || e.CommandName.ToLower() == "addandback")
            {
                try
                {
                    var obj = new Badge();
                    obj.AdminName           = ((TextBox)((DetailsView)sender).FindControl("AdminName")).Text.Trim();
                    obj.UserName            = ((TextBox)((DetailsView)sender).FindControl("UserName")).Text.Trim();
                    obj.CustomDescription   = ((HtmlTextArea)((DetailsView)sender).FindControl("CustomDescription")).InnerHtml;
                    obj.CustomEarnedMessage = ((HtmlTextArea)((DetailsView)sender).FindControl("CustomEarnedMessage")).InnerHtml;
                    obj.HiddenFromPublic    = ((DropDownList)((DetailsView)sender).FindControl("HiddenFromPublic")).SelectedIndex > 0;

                    obj.AddedDate   = DateTime.Now;
                    obj.AddedUser   = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username; //"N/A";  // Get from session
                    obj.LastModDate = obj.AddedDate;
                    obj.LastModUser = obj.AddedUser;

                    if (obj.IsValid(BusinessRulesValidationMode.INSERT))
                    {
                        obj.Insert();
                        new SessionTools(Session).RemoveCache(Cache, CacheKey.BadgesActive);

                        try
                        {
                            var badgePath = string.Format(Server.MapPath("~/images/Badges/"));
                            System.IO.File.Copy(string.Format("{0}no_badge.png", badgePath),
                                                string.Format("{0}{1}.png", badgePath, obj.BID));
                            System.IO.File.Copy(string.Format("{0}no_badge_sm.png", badgePath),
                                                string.Format("{0}sm_{1}.png", badgePath, obj.BID));
                        }
                        catch (Exception ex)
                        {
                            this.Log().Error("Couldn't copy no_badge images into new badge: {0}",
                                             ex.Message);
                        }

                        if (e.CommandName.ToLower() == "addandback")
                        {
                            Response.Redirect(returnURL);
                        }

                        lblPK.Text = obj.BID.ToString();

                        odsData.DataBind();
                        dv.DataBind();
                        dv.ChangeMode(DetailsViewMode.Edit);

                        var masterPage = (IControlRoomMaster)Master;
                        masterPage.PageMessage = SRPResources.AddedOK;
                    }
                    else
                    {
                        var    masterPage = (IControlRoomMaster)Master;
                        string message    = String.Format(SRPResources.ApplicationError1, "<ul>");
                        foreach (BusinessRulesValidationMessage m in obj.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}</ul>", message);
                        masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }
            if (e.CommandName.ToLower() == "save" || e.CommandName.ToLower() == "saveandback")
            {
                try
                {
                    var obj = new Badge();
                    //int pk = int.Parse(((DetailsView)sender).Rows[0].Cells[1].Text);
                    int pk = int.Parse(lblPK.Text);
                    obj.Fetch(pk);

                    obj.AdminName = ((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("AdminName")).Text.Trim();
                    obj.UserName  = ((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("UserName")).Text.Trim();

                    obj.HideDefaultDescriptionFlag = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("HideDefaultDescription")).Checked;
                    obj.CustomDescription          = ((HtmlTextArea)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("CustomDescription")).InnerHtml;
                    obj.CustomEarnedMessage        = ((HtmlTextArea)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("CustomEarnedMessage")).InnerHtml;
                    obj.IncludesPhysicalPrizeFlag  = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("IncludesPhysicalPrizeFlag")).Checked;
                    obj.PhysicalPrizeName          = ((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("PhysicalPrizeName")).Text;
                    obj.HiddenFromPublic           = ((DropDownList)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("HiddenFromPublic")).SelectedIndex > 0;

                    obj.GenNotificationFlag = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("GenNotificationFlag")).Checked;
                    obj.NotificationSubject = ((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("NotificationSubject")).Text.Trim();
                    obj.NotificationBody    = ((HtmlTextArea)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("NotificationBody")).InnerHtml;


                    obj.AssignProgramPrizeCode = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel3").FindControl("AssignProgramPrizeCode")).Checked;
                    obj.PCNotificationSubject  = ((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel3").FindControl("PCNotificationSubject")).Text.Trim();
                    obj.PCNotificationBody     = ((HtmlTextArea)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel3").FindControl("PCNotificationBody")).InnerHtml;

                    obj.LastModDate = DateTime.Now;
                    obj.LastModUser = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username;  //"N/A";  // Get from session

                    if (obj.IsValid(BusinessRulesValidationMode.UPDATE))
                    {
                        obj.Update();
                        new SessionTools(Session).RemoveCache(Cache, CacheKey.BadgesActive);
                        SaveBadgeExtendedAttributes(obj,
                                                    (GridView)
                                                    ((DetailsView)sender).FindControl("TabContainer1").FindControl(
                                                        "TabPanel4").FindControl("gvCat"),
                                                    (GridView)
                                                    ((DetailsView)sender).FindControl("TabContainer1").FindControl(
                                                        "TabPanel4").FindControl("gvAge"),
                                                    (GridView)
                                                    ((DetailsView)sender).FindControl("TabContainer1").FindControl(
                                                        "TabPanel4").FindControl("gvBranch"),
                                                    (GridView)
                                                    ((DetailsView)sender).FindControl("TabContainer1").FindControl(
                                                        "TabPanel4").FindControl("gvLoc"));

                        if (e.CommandName.ToLower() == "saveandback")
                        {
                            Response.Redirect(returnURL);
                        }
                        odsData.DataBind();
                        dv.DataBind();
                        dv.ChangeMode(DetailsViewMode.Edit);

                        var masterPage = (IControlRoomMaster)Master;
                        masterPage.PageMessage = SRPResources.SaveOK;
                    }
                    else
                    {
                        var    masterPage = (IControlRoomMaster)Master;
                        string message    = String.Format(SRPResources.ApplicationError1, "<ul>");
                        foreach (BusinessRulesValidationMessage m in obj.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}</ul>", message);
                        masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }
        }
Example #45
0
        public void UpdateBadgeAccess()
        {
            Console.Clear();

            Badge badge = new Badge();

            Console.Write("Enter the Badge ID: ");
            // Verifying user input
            string possibleID = Console.ReadLine();

            if (Int32.TryParse(possibleID, out int userInput))
            {
                badge.BadgeID = Convert.ToInt32(possibleID);
            }
            else
            {
                Console.WriteLine("\n" +
                                  "Invalid Badge ID, please try again.\n" +
                                  "Press any key to continue...");
                Console.ReadKey();
                UpdateBadgeAccess();
            }
            // Verifying the badge exists
            if (accessLog.DoesListContainBadgeID(badge) == true)
            {
                Console.Clear();
                // Displays chosen badge ID
                Console.WriteLine($"Badge ID: {accessLog.DisplayBadgeID(userInput)}");
                // Displays chosen badge door access separated by ','
                Console.WriteLine($"Current door access: {accessLog.DisplayBadgeAccess(userInput)}");
                Console.WriteLine("");
                Console.WriteLine("What would you like to do: \n" +
                                  "[1] Add a door access\n" +
                                  "[2] Remove a door access\n" +
                                  "[3] Cancel\n" +
                                  "");
                string updateOption = Console.ReadLine();
                Console.Clear();
                switch (updateOption)
                {
                // AddBadgeAccess()
                case "1":
                    Console.WriteLine($"Current door access: {accessLog.DisplayBadgeAccess(userInput)}");
                    Console.Write("\n" +
                                  "What door access would you like to add?: ");
                    // Setting all proper inputs to correct format
                    string addAccess = Console.ReadLine().ToUpper();
                    if (possibleDoors.Contains(addAccess))
                    {
                        if (accessLog.CheckAssignedBadgeAccess(userInput, addAccess) == true)
                        {
                            Console.WriteLine("\n" +
                                              "Current badge has already been given access to chosen door. \n" +
                                              "Press any key to continue...");
                            Console.ReadKey();
                            MainMenu();
                        }
                        else
                        {
                            Console.Write($"\n" +
                                          $"You want to add\n" +
                                          $"\n" +
                                          $"Door access: {addAccess} \n" +
                                          $"To Badge ID: {accessLog.DisplayBadgeID(userInput)}\n" +
                                          $"\n" +
                                          $"Correct (y/n)?: ");
                            string confirmUpdate = Console.ReadLine();
                            if (confirmUpdate == "y" || confirmUpdate == "Y")
                            {
                                accessLog.AddBadgeAccess(userInput, addAccess);
                                Console.WriteLine("\n" +
                                                  "Door access added.");
                            }
                            else
                            {
                                Console.WriteLine("\n" +
                                                  "Update cancelled.");
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("\n" +
                                          "Assignment of unrecognized door, could not complete request.\n" +
                                          "Press any key to continue...");
                        Console.ReadKey();
                        MainMenu();
                    }
                    break;

                // RemoveBadgeAccess()
                case "2":
                    Console.WriteLine($"Current door access: {accessLog.DisplayBadgeAccess(userInput)}");
                    Console.Write("\n" +
                                  "What door access would you like to remove?: ");
                    string removeAccess = Console.ReadLine().ToUpper();
                    // Verifying proper input
                    if (possibleDoors.Contains(removeAccess))
                    {
                        // Verifying badge being updated has been assigned access to door for removal
                        if (accessLog.CheckAssignedBadgeAccess(userInput, removeAccess) == true)
                        {
                            Console.Write($"\n" +
                                          $"You want to remove\n" +
                                          $"\n" +
                                          $"Door access: {removeAccess} \n" +
                                          $"From Badge ID: {accessLog.DisplayBadgeID(userInput)}\n" +
                                          $"\n" +
                                          $"Correct (y/n)?");
                            string confirmRemoval = Console.ReadLine();
                            if (confirmRemoval == "y" || confirmRemoval == "Y")
                            {
                                accessLog.RemoveBadgeAccess(userInput, removeAccess);
                                Console.WriteLine("\n" +
                                                  "Door access removed");
                            }
                            else
                            {
                                Console.WriteLine("\n" +
                                                  "Removal cancelled.");
                            }
                        }
                        else
                        {
                            Console.WriteLine($"\n" +
                                              $"Selected badge currently does not have access to door {removeAccess}.\n" +
                                              $"Press any key to continue...");
                            Console.ReadKey();
                            MainMenu();
                        }
                    }
                    else
                    {
                        Console.WriteLine("\n" +
                                          "Please enter proper door access.\n" +
                                          "Press any key to continue...");
                        Console.ReadKey();
                        MainMenu();
                    }
                    break;

                default:
                    MainMenu();
                    break;
                }
                // ReturnToMainMenu()
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
                MainMenu();
                //
            }
            else
            {
                Console.WriteLine("\n" +
                                  "Selected Badge ID does not exist.\n" +
                                  "Press any key to continue...");
                Console.ReadKey();
                MainMenu();
            }
        }
Example #46
0
 internal void update(Badge badge)
 {
     BadgeContext.GetDatabase().Update(badge);
 }
 partial void DeleteBadge(Badge instance);
Example #48
0
 public static void OnBadgeAdded(Badge badge)
 => BadgeAdded?.Invoke(badge);
Example #49
0
 internal void delete(Badge badge)
 {
     BadgeContext.GetDatabase().Delete(badge);
 }
 static private void SetPosition(Badge badge, Control ctl)
 {
    badge.Location = new Point(ctl.Width - badge.Width - 5, 
                               ctl.Height - badge.Height - 5);
 }
Example #51
0
 /// <summary>
 /// Add a new badge (expected id already assigned)
 /// </summary>
 /// <param name="newBadge"></param>
 public Badge Add(Badge newBadge)
 {
     return(_context.Badge.Add(newBadge));
 }
Example #52
0
        public void AddBadge()
        {
            Console.Clear();

            Badge         newBadge = new Badge();
            List <string> access   = new List <string>();

            Console.Write("Enter a badge number: ");
            string possibleID = Console.ReadLine();

            // Checking to make sure that user input is a valid ID option (an integer)   // Declaring an initializing 'int newBadgeID' if 'possibleID' is valid
            if (Int32.TryParse(possibleID, out int newBadgeID))
            {
                newBadge.BadgeID = Convert.ToInt32(possibleID);
                // Checks to make sure Badge ID isn't already being used
                if (accessLog.DoesListContainBadgeID(newBadge) == true)
                {
                    Console.WriteLine("\n" +
                                      "Badge ID already being used, choose another Badge ID.\n" +
                                      "Press any key to continue...");
                    Console.ReadKey();
                    AddBadge();
                }
                else
                {
                    newBadge.BadgeID = newBadgeID;
                }
            }
            else
            {
                Console.WriteLine("\n" +
                                  "Enter a proper Badge ID.\n" +
                                  "Press any key to continue...");
                Console.ReadKey();
                AddBadge();
            }
            Console.Write($"What door does it have access to: ");
            string doorAccess = Console.ReadLine().ToUpper();

            //
            // user is able to input in multiple of the same door access
            //
            if (possibleDoors.Contains(doorAccess))
            {
                access.Add(doorAccess);
            }
            else
            {
                Console.WriteLine("Assignment of unrecognized door access, could not complete request.\n" +
                                  "Press any key to continue...");
                Console.ReadKey();
                MainMenu();
            }
            Console.Write("Any other doors (y/n)?: ");
            string userInput = Console.ReadLine();

            if (userInput == "y" || userInput == "Y")
            {
                while (userInput == "y" || userInput == "Y")
                {
                    Console.Write("Enter door access: ");
                    doorAccess = Console.ReadLine().ToUpper();
                    if (possibleDoors.Contains(doorAccess))
                    {
                        access.Add(doorAccess);
                    }
                    else
                    {
                        Console.WriteLine("Assignment of unrecognized door access, could not complete request.");
                    }
                    Console.Write("Any other doors (y/n)?: ");
                    userInput = Console.ReadLine();
                }
                newBadge.Access = access;
                accessLog.AddBadgeToCollection(newBadge);
                Console.WriteLine("\n" +
                                  "New badge created.\n" +
                                  "Press any key to continue...");
                Console.ReadKey();
                MainMenu();
            }
            else if (userInput == "n" || userInput == "N")
            {
                newBadge.Access = access;
                accessLog.AddBadgeToCollection(newBadge);
                Console.WriteLine("\n" +
                                  "New badge created.\n" +
                                  "Press any key to continue...");
                Console.ReadKey();
                MainMenu();
            }
            else
            {
                Console.WriteLine("Did not recognze value, input 'y' or 'n' when prompted, unable to complete request.\n" +
                                  "Press any key to continue...");
                Console.ReadKey();
                AddBadge();
            }
        }
Example #53
0
 /// <summary>
 /// Generic single entity delete
 /// </summary>
 /// <param name="badge"></param>
 public void Delete(Badge badge)
 {
     badge.Users.Clear();
     _context.Badge.Remove(badge);
 }
Example #54
0
 public async Task UpdateBadge(Badge badge)
 {
     _badgeRepository.Update(badge);
     await _unit.Commit();
 }
Example #55
0
 public void PrintAccessSummary(Badge badge)
 {
     Console.WriteLine($"{badge.BadgeId} has access to doors " +
                       $"{String.Join(", ", badge.AccessibleDoors)}.");
 }