示例#1
0
        public Person(Canvas canvas, Graph graph, Point point, CurrentPerson cp, ToolTip tp)
        {
            image = new Image();
            var img = new BitmapImage();
            img.BeginInit();
            img.UriSource = new Uri("pack://application:,,,/program_final;component/Resources/miku.gif");
            img.EndInit();
            ImageBehavior.SetAnimatedSource(image, img);

            image.MouseLeftButtonUp += Person_MouseLeftButtonUp;
            image.ToolTip = tp;
            ToolTipService.SetInitialShowDelay(image, 0);
            ToolTipService.SetShowDuration(image, 60000);

            canvas.Children.Add(image);
            Canvas.SetZIndex(image, 1);
            point = graph.closestNode(point).getPoint();
            Canvas.SetLeft(image, point.X - 16);
            Canvas.SetTop(image, point.Y - 34);

            this.location = point;
            this.graph = graph;
            this.canvas = canvas;
            this.moving = false;
            this.cp = cp;
        }
        public GridJsonNetJObjectResult <vTreatmentBMPDetailedWithTreatmentBMPEntity> TreatmentBMPsInTreatmentBMPTypeGridJsonData(TreatmentBMPTypePrimaryKey treatmentBmpTypePrimaryKey)
        {
            var treatmentBmpType = treatmentBmpTypePrimaryKey.EntityObject;
            var stormwaterJurisdictionIDsPersonCanView = CurrentPerson.GetStormwaterJurisdictionIDsPersonCanView();
            var showDelete    = new JurisdictionManageFeature().HasPermissionByPerson(CurrentPerson);
            var showEdit      = new JurisdictionEditFeature().HasPermissionByPerson(CurrentPerson);
            var gridSpec      = new TreatmentBMPsInTreatmentBMPTypeGridSpec(CurrentPerson, showDelete, showEdit, treatmentBmpType);
            var treatmentBMPs =
                HttpRequestStorage.DatabaseEntities.TreatmentBMPs
                .Include(x => x.WaterQualityManagementPlan)
                .Include(x => x.CustomAttributes)
                .Include(x => x.CustomAttributes.Select(y => y.CustomAttributeValues))
                .Where(x => stormwaterJurisdictionIDsPersonCanView.Contains(x.StormwaterJurisdictionID) && x.TreatmentBMPTypeID == treatmentBmpType.TreatmentBMPTypeID)
                .ToList()
                .Join(HttpRequestStorage.DatabaseEntities.vTreatmentBMPDetaileds,
                      x => x.TreatmentBMPID,
                      y => y.TreatmentBMPID,
                      (x, y) => new vTreatmentBMPDetailedWithTreatmentBMPEntity(x, y))
                .ToList();
            var gridJsonNetJObjectResult = new GridJsonNetJObjectResult <vTreatmentBMPDetailedWithTreatmentBMPEntity>(treatmentBMPs, gridSpec);

            return(gridJsonNetJObjectResult);
        }
示例#3
0
        private void LoadFilters()
        {
            LoadStatusList();
            LoadLocationList();
            LoadMinistryList();
            LoadFiscalYearList();
            //SetRequesterFilter( 0 );

            CurrentPerson.LoadAttributes();
            ddlMinistry.Visible    = UserCanEdit || CurrentPerson.AttributeValues[AttributeCache.Get(GetAttributeValue("MinistryAttribute").AsGuid()).Key].Value.Split(',').Count() > 0;
            ddlSCCLocation.Visible = UserCanEdit;
            requester.Visible      = UserCanEdit;
            txtGLAccount.Visible   = UserCanEdit;
            ddlFiscalYear.Visible  = UserCanEdit;

            SetRequestedByAllOption(UserCanEdit);

            Group locationAdminGroup = new GroupService(new RockContext()).Get(GetAttributeValue("LocationAdminGroup").AsGuid());

            if (!(UserCanEdit || (locationAdminGroup != null && locationAdminGroup.ActiveMembers().Where(m => m.PersonId == CurrentPerson.Id).Any())))
            {
                cblShow.Items.Remove(cblShow.Items.FindByValue("Location"));
            }
        }
        public ViewResult DelineationMap(int?treatmentBMPID)
        {
            var treatmentBMP = treatmentBMPID.HasValue
                ? HttpRequestStorage.DatabaseEntities.TreatmentBMPs.GetTreatmentBMP(
                treatmentBMPID.Value)
                : null;

            if (treatmentBMP != null)
            {
                var permissionCheckResult = new TreatmentBMPEditFeature().HasPermission(CurrentPerson, treatmentBMP);
                Check.Assert(permissionCheckResult.HasPermission, permissionCheckResult.PermissionDeniedMessage);
            }

            var neptunePage = NeptunePage.GetNeptunePageByPageType(NeptunePageType.DelineationMap);
            var stormwaterJurisdictionsPersonCanView   = CurrentPerson.GetStormwaterJurisdictionsPersonCanView().ToList();
            var stormwaterJurisdictionIDsPersonCanView = stormwaterJurisdictionsPersonCanView.Select(x => x.StormwaterJurisdictionID);
            var treatmentBMPs          = HttpRequestStorage.DatabaseEntities.TreatmentBMPs.Include(x => x.Delineations).Where(x => stormwaterJurisdictionIDsPersonCanView.Contains(x.StormwaterJurisdictionID)).ToList();
            var delineationMapInitJson = new DelineationMapInitJson("delineationMap", treatmentBMPs, BoundingBox.GetBoundingBox(stormwaterJurisdictionsPersonCanView));
            var bulkUploadTreatmentBMPDelineationsUrl = SitkaRoute <DelineationUploadController> .BuildUrlFromExpression(x => x.UpdateDelineationGeometry());

            var viewData = new DelineationMapViewData(CurrentPerson, neptunePage, delineationMapInitJson, treatmentBMP, bulkUploadTreatmentBMPDelineationsUrl);

            return(RazorView <DelineationMap, DelineationMapViewData>(viewData));
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="opportunityId">The opportunity identifier.</param>
        public void ShowDetail(int opportunityId)
        {
            using (var rockContext = new RockContext())
            {
                // load campus dropdown
                var campuses = CampusCache.All();
                cpCampus.Campuses = campuses;
                cpCampus.Visible  = campuses.Count > 1;

                var opportunity = new ConnectionOpportunityService(rockContext).Get(opportunityId);
                if (opportunity == null)
                {
                    pnlSignup.Visible = false;
                    ShowError("Incorrect Opportunity Type", "The requested opportunity does not exist.");
                    return;
                }

                pnlSignup.Visible = true;

                if (!string.IsNullOrWhiteSpace(opportunity.IconCssClass))
                {
                    lIcon.Text = string.Format("<i class='{0}' ></i>", opportunity.IconCssClass);
                }

                lTitle.Text = opportunity.Name.FormatAsHtmlTitle();

                pnHome.Visible   = GetAttributeValue("DisplayHomePhone").AsBoolean();
                pnMobile.Visible = GetAttributeValue("DisplayMobilePhone").AsBoolean();

                if (CurrentPerson != null)
                {
                    tbFirstName.Text = CurrentPerson.FirstName.EncodeHtml();
                    tbLastName.Text  = CurrentPerson.LastName.EncodeHtml();
                    tbEmail.Text     = CurrentPerson.Email.EncodeHtml();

                    if (pnHome.Visible && _homePhone != null)
                    {
                        var homePhoneNumber = CurrentPerson.PhoneNumbers.Where(p => p.NumberTypeValueId == _homePhone.Id).FirstOrDefault();
                        if (homePhoneNumber != null)
                        {
                            pnHome.Number      = homePhoneNumber.NumberFormatted;
                            pnHome.CountryCode = homePhoneNumber.CountryCode;
                        }
                    }

                    if (pnMobile.Visible && _cellPhone != null)
                    {
                        var cellPhoneNumber = CurrentPerson.PhoneNumbers.Where(p => p.NumberTypeValueId == _cellPhone.Id).FirstOrDefault();
                        if (cellPhoneNumber != null)
                        {
                            pnMobile.Number      = cellPhoneNumber.NumberFormatted;
                            pnMobile.CountryCode = cellPhoneNumber.CountryCode;
                        }
                    }

                    var campus = CurrentPerson.GetCampus();
                    if (campus != null)
                    {
                        cpCampus.SelectedCampusId = campus.Id;
                    }
                }
                else
                {
                    // set the campus to the context
                    if (GetAttributeValue("EnableCampusContext").AsBoolean())
                    {
                        var campusEntityType = EntityTypeCache.Read("Rock.Model.Campus");
                        var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                        if (contextCampus != null)
                        {
                            cpCampus.SelectedCampusId = contextCampus.Id;
                        }
                    }
                }

                // show debug info
                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("Opportunity", new ConnectionOpportunityService(rockContext).Get(PageParameter("OpportunityId").AsInteger()));
                mergeFields.Add("CurrentPerson", CurrentPerson);
                if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
                {
                    lDebug.Visible = true;
                    lDebug.Text    = mergeFields.lavaDebugInfo();
                }
            }
        }
示例#6
0
        private void DisplayResults()
        {
            RockContext rockContext = new RockContext();

            var statementYear = RockDateTime.Now.Year;

            if (Request["StatementYear"] != null)
            {
                Int32.TryParse(Request["StatementYear"].ToString(), out statementYear);
            }

            FinancialTransactionDetailService financialTransactionDetailService = new FinancialTransactionDetailService(rockContext);

            var qry = financialTransactionDetailService.Queryable().AsNoTracking()
                      .Where(t => t.Transaction.AuthorizedPersonAlias.Person.GivingId == CurrentPerson.GivingId);

            qry = qry.Where(t => t.Transaction.TransactionDateTime.Value.Year == statementYear);

            if (string.IsNullOrWhiteSpace(GetAttributeValue("Accounts")))
            {
                qry = qry.Where(t => t.Account.IsTaxDeductible);
            }
            else
            {
                var accountGuids = GetAttributeValue("Accounts").Split(',').Select(Guid.Parse).ToList();
                qry = qry.Where(t => accountGuids.Contains(t.Account.Guid));
            }

            qry = qry.OrderByDescending(t => t.Transaction.TransactionDateTime);

            var mergeFields = new Dictionary <string, object>();

            mergeFields.Add("StatementStartDate", "1/1/" + statementYear.ToString());
            if (statementYear == RockDateTime.Now.Year)
            {
                mergeFields.Add("StatementEndDate", RockDateTime.Now);
            }
            else
            {
                mergeFields.Add("StatementEndDate", "12/31/" + statementYear.ToString());
            }

            var familyGroupTypeId = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY).Id;
            var groupMemberQry    = new GroupMemberService(rockContext).Queryable().Where(m => m.Group.GroupTypeId == familyGroupTypeId);

            // get giving group members in order by family role (adult -> child) and then gender (male -> female)
            var givingGroup = new PersonService(rockContext).Queryable().AsNoTracking()
                              .Where(p => p.GivingId == CurrentPerson.GivingId)
                              .GroupJoin(
                groupMemberQry,
                p => p.Id,
                m => m.PersonId,
                (p, m) => new { p, m })
                              .SelectMany(x => x.m.DefaultIfEmpty(), (y, z) => new { Person = y.p, GroupMember = z })
                              .Select(p => new { FirstName = p.Person.NickName, LastName = p.Person.LastName, FamilyRoleOrder = p.GroupMember.GroupRole.Order, Gender = p.Person.Gender, PersonId = p.Person.Id })
                              .DistinctBy(p => p.PersonId)
                              .OrderBy(p => p.FamilyRoleOrder).ThenBy(p => p.Gender)
                              .ToList();

            string salutation = string.Empty;

            if (givingGroup.GroupBy(g => g.LastName).Count() == 1)
            {
                salutation = string.Join(", ", givingGroup.Select(g => g.FirstName)) + " " + givingGroup.FirstOrDefault().LastName;
                if (salutation.Contains(","))
                {
                    salutation = salutation.ReplaceLastOccurrence(",", " &");
                }
            }
            else
            {
                salutation = string.Join(", ", givingGroup.Select(g => g.FirstName + " " + g.LastName));
                if (salutation.Contains(","))
                {
                    salutation = salutation.ReplaceLastOccurrence(",", " &");
                }
            }
            mergeFields.Add("Salutation", salutation);

            var homeAddress = CurrentPerson.GetHomeLocation();

            if (homeAddress != null)
            {
                mergeFields.Add("StreetAddress1", homeAddress.Street1);
                mergeFields.Add("StreetAddress2", homeAddress.Street2);
                mergeFields.Add("City", homeAddress.City);
                mergeFields.Add("State", homeAddress.State);
                mergeFields.Add("PostalCode", homeAddress.PostalCode);
                mergeFields.Add("Country", homeAddress.Country);
            }
            else
            {
                mergeFields.Add("StreetAddress1", string.Empty);
                mergeFields.Add("StreetAddress2", string.Empty);
                mergeFields.Add("City", string.Empty);
                mergeFields.Add("State", string.Empty);
                mergeFields.Add("PostalCode", string.Empty);
                mergeFields.Add("Country", string.Empty);
            }

            mergeFields.Add("TransactionDetails", qry.ToList());

            mergeFields.Add("AccountSummary", qry.GroupBy(t => t.Account.Name).Select(s => new AccountSummary {
                AccountName = s.Key, Total = s.Sum(a => a.Amount), Order = s.Max(a => a.Account.Order)
            }).OrderBy(s => s.Order));

            // pledge information
            var pledges = new FinancialPledgeService(rockContext).Queryable().AsNoTracking()
                          .Where(p =>
                                 p.PersonAlias.Person.GivingId == CurrentPerson.GivingId &&
                                 (p.StartDate.Year == statementYear || p.EndDate.Year == statementYear))
                          .GroupBy(p => p.Account)
                          .Select(g => new PledgeSummary {
                AccountId       = g.Key.Id,
                AccountName     = g.Key.Name,
                AmountPledged   = g.Sum(p => p.TotalAmount),
                PledgeStartDate = g.Min(p => p.StartDate),
                PledgeEndDate   = g.Max(p => p.EndDate)
            })
                          .ToList();

            // add detailed pledge information
            foreach (var pledge in pledges)
            {
                var adjustedPedgeEndDate = pledge.PledgeEndDate.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
                pledge.AmountGiven = new FinancialTransactionDetailService(rockContext).Queryable()
                                     .Where(t =>
                                            t.AccountId == pledge.AccountId &&
                                            t.Transaction.TransactionDateTime >= pledge.PledgeStartDate &&
                                            t.Transaction.TransactionDateTime <= adjustedPedgeEndDate)
                                     .Sum(t => t.Amount);

                pledge.AmountRemaining = (pledge.AmountGiven > pledge.AmountPledged) ? 0 : (pledge.AmountPledged - pledge.AmountGiven);

                if (pledge.AmountPledged > 0)
                {
                    var test = (double)pledge.AmountGiven / (double)pledge.AmountPledged;
                    pledge.PercentComplete = (int)((pledge.AmountGiven * 100) / pledge.AmountPledged);
                }
            }

            mergeFields.Add("Pledges", pledges);

            var template = GetAttributeValue("LavaTemplate");

            lResults.Text = template.ResolveMergeFields(mergeFields);

            // show debug info
            if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
            {
                lDebug.Visible = true;
                lDebug.Text    = mergeFields.lavaDebugInfo();
            }
        }
示例#7
0
        public ActionResult Invite(InviteViewModel viewModel)
        {
            var toolDisplayName = MultiTenantHelpers.GetToolDisplayName();
            var homeUrl         = SitkaRoute <HomeController> .BuildAbsoluteUrlHttpsFromExpression(x => x.Index());

            var supportUrl = SitkaRoute <HelpController> .BuildAbsoluteUrlHttpsFromExpression(x => x.RequestSupport());

            var tenantAttribute        = MultiTenantHelpers.GetTenantAttributeFromCache();
            var primaryContactFullName = tenantAttribute.PrimaryContactPerson
                                         .GetFullNameFirstLast();
            var primaryContactOrganizationName = tenantAttribute.PrimaryContactPerson
                                                 .Organization.OrganizationName;
            var primaryContactEmail = tenantAttribute.PrimaryContactPerson.Email;

            KeystoneService.KeystoneApiResponse <KeystoneService.KeystoneNewUserModel> keystoneNewUserResponse = null;

            var theSelectedOrganization = HttpRequestStorage.DatabaseEntities.Organizations.GetOrganization(viewModel.OrganizationID);

            Check.EnsureNotNull(theSelectedOrganization);
            bool organizationSelectedIsNotUnknownOrg = !theSelectedOrganization.IsUnknown();

            if (organizationSelectedIsNotUnknownOrg && theSelectedOrganization.KeystoneOrganizationGuid == null)
            {
                // If we pick an Org, it must already be in Keystone, and so the local dbo.Organization must have a valid OrganizationGuid
                ModelState.AddModelError("OrganizationID", $"Organization is not in Keystone");
            }
            else
            {
                var inviteModel = new KeystoneService.KeystoneInviteModel
                {
                    FirstName   = viewModel.FirstName,
                    LastName    = viewModel.LastName,
                    Email       = viewModel.Email,
                    SiteName    = toolDisplayName,
                    Subject     = $"Invitation to {toolDisplayName}",
                    WelcomeText =
                        $"You have been invited by {CurrentPerson.GetFullNameFirstLast()} at {CurrentPerson.Organization.OrganizationName} ({CurrentPerson.Email}), to create an account in <a href=\"{homeUrl}\">{toolDisplayName}</a>.",
                    RedirectURL      = homeUrl,
                    SupportBlock     = $"If you have any questions, please visit our <a href=\"{supportUrl}\">support page</a> or contact {primaryContactFullName} at {primaryContactOrganizationName} ({primaryContactEmail})",
                    OrganizationGuid = theSelectedOrganization.KeystoneOrganizationGuid,
                    SignatureBlock   = $"The {toolDisplayName} team"
                };

                var keystoneService = new KeystoneService(HttpRequestStorage.GetHttpContextUserThroughOwin());
                keystoneNewUserResponse = keystoneService.Invite(inviteModel);
                if (keystoneNewUserResponse.StatusCode != HttpStatusCode.OK || keystoneNewUserResponse.Error != null)
                {
                    ModelState.AddModelError("Email", $"There was a problem inviting the user to Keystone: {keystoneNewUserResponse.Error.Message}.");
                    if (keystoneNewUserResponse.Error.ModelState != null)
                    {
                        foreach (var modelStateKey in keystoneNewUserResponse.Error.ModelState.Keys)
                        {
                            foreach (var err in keystoneNewUserResponse.Error.ModelState[modelStateKey])
                            {
                                ModelState.AddModelError(modelStateKey, err);
                            }
                        }
                    }
                }
                else
                {
                    // Sanity check - did we get back the same Organization GUID we asked for?
                    // (The GUID could also be null here, for the unknown org, but in that case we'll also get back null so this check is still valid.)
                    var keystoneUserTmp = keystoneNewUserResponse.Payload.Claims;
                    if (keystoneUserTmp.OrganizationGuid != inviteModel.OrganizationGuid)
                    {
                        string errorMessage = $"There was a problem with the Keystone Organization GUID Invited:{inviteModel.OrganizationGuid} Received back: {keystoneUserTmp.OrganizationGuid}. Please contact Sitka for assistance.";
                        _logger.Error(errorMessage);
                        ModelState.AddModelError("OrganizationID", errorMessage);
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                return(ViewInvite(viewModel));
            }

            var keystoneUser = keystoneNewUserResponse.Payload.Claims;
            var existingUser = HttpRequestStorage.DatabaseEntities.People.GetPersonByPersonGuid(keystoneUser.UserGuid);

            if (existingUser != null)
            {
                SetMessageForDisplay($"{existingUser.GetFullNameFirstLastAndOrgAsUrl(CurrentFirmaSession)} already has an account.</a>.");
                return(RedirectToAction(new SitkaRoute <UserController>(x => x.Detail(existingUser))));
            }

            var newUser = CreateNewFirmaPerson(keystoneUser, keystoneUser.OrganizationGuid);

            HttpRequestStorage.DatabaseEntities.SaveChanges();

            newUser.RoleID = Role.Normal.RoleID;

            HttpRequestStorage.DatabaseEntities.SaveChanges();

            if (!viewModel.DoNotSendInviteEmailIfExisting && !keystoneNewUserResponse.Payload.Created)
            {
                SendExistingKeystoneUserCreatedMessage(newUser, CurrentPerson);
            }

            SetMessageForDisplay(
                $"{newUser.GetFullNameFirstLastAndOrgAsUrl(CurrentFirmaSession)} successfully added. You may want to assign them a role</a>.");
            return(RedirectToAction(new SitkaRoute <UserController>(x => x.Detail(newUser))));
        }
示例#8
0
 protected override bool IsCurrentUserAnonymous()
 {
     return(CurrentPerson == null || CurrentPerson.IsAnonymousUser());
 }
        public override MobileBlock GetMobile(string parameter)
        {
            if (CurrentPerson == null)
            {
                return(new MobileBlock()
                {
                    BlockType = "Avalanche.Blocks.Null",
                    Attributes = CustomAttributes
                });
            }

            AvalancheUtilities.SetActionItems(GetAttributeValue("ActionItem"),
                                              CustomAttributes,
                                              CurrentPerson, AvalancheUtilities.GetMergeFields(CurrentPerson),
                                              GetAttributeValue("EnabledLavaCommands"),
                                              parameter);

            var valueGuid = GetAttributeValue("Component");
            var value     = DefinedValueCache.Get(valueGuid);

            if (value != null)
            {
                CustomAttributes["Component"] = value.GetAttributeValue("ComponentType");
            }

            CustomAttributes["InitialRequest"] = parameter; //Request for pull to refresh

            var family = new List <ListElement>();

            family.Add(
                new ListElement
            {
                Image       = GlobalAttributesCache.Value("InternalApplicationRoot") + CurrentPerson.PhotoUrl,
                Id          = CurrentPersonAlias.Guid.ToString(),
                Title       = CurrentPerson.FullName,
                Description = GetInfo(CurrentPerson, true)
            });

            foreach (var member in CurrentPerson.GetFamilyMembers())
            {
                family.Add(new ListElement
                {
                    Image       = GlobalAttributesCache.Value("InternalApplicationRoot") + member.Person.PhotoUrl,
                    Id          = member.Person.PrimaryAlias.Guid.ToString(),
                    Title       = member.Person.FullName,
                    Description = GetInfo(member.Person, false)
                });
            }

            family.Add(new ListElement
            {
                Id    = "0",
                Title = "Add New Family Member"
            });

            var additionalChanges = GetAttributeValue("AdditionalChangesLink");

            var additionalChangesPage = PageCache.Get(additionalChanges);

            if (additionalChangesPage != null)
            {
                family.Add(new ListElement
                {
                    ActionType = "1",
                    Resource   = additionalChangesPage.Id.ToString(),
                    Title      = "Request Additional Changes",
                    Id         = "1"
                });
            }



            CustomAttributes["Content"] = JsonConvert.SerializeObject(family);

            return(new MobileBlock()
            {
                BlockType = "Avalanche.Blocks.ListViewBlock",
                Attributes = CustomAttributes
            });
        }
示例#10
0
        private void GetFollowUps()
        {
            if (!CurrentPerson.HasALine())
            {
                leaderControlRow.Visible = false;
            }

            var rockContext = new RockContext();
            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            IQueryable <Person> people;
            bool isMyLine = tViewLineType.Checked;

            if (isMyLine)
            {
                people = CurrentPerson.GetPersonsLine(rockContext);
            }
            else // My Line's Follow Ups
            {
                people = LineQuery.GetLineMembersAndFollowUps(new PersonService(rockContext), CurrentPerson,
                                                              rockContext, false);
            }

            var option = GetOption();

            switch (option)
            {
            case ViewOption.All:
                break;

            case ViewOption.New:
                people = people.Where(
                    f => f.ConnectionStatusValueId == org.kcionline.bricksandmortarstudio.Constants.DefinedValue.GET_CONNECTED);
                break;

            case ViewOption.Ready:
                break;

            case ViewOption.InGroup:
                people = people.ToList().Where(f => f.InAGroup(rockContext)).AsQueryable();
                break;

            case ViewOption.NotInGroup:
                people = people.ToList().Where(f => !f.InAGroup(rockContext)).AsQueryable();
                break;

            case ViewOption.Ongoing:
                people = people.Where(
                    f => f.ConnectionStatusValueId == org.kcionline.bricksandmortarstudio.Constants.DefinedValue.CONNECTED);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            IQueryable <FollowUpSummary> followUpSummaries;

            if (isMyLine)
            {
                followUpSummaries =
                    people.ToList().Select(f => new FollowUpSummary()
                {
                    Person = f, Consolidator = CurrentPerson
                })
                    .AsQueryable();
            }
            else
            {
                followUpSummaries =
                    people.ToList().Select(f => new FollowUpSummary()
                {
                    Person = f, Consolidator = f.GetConsolidator()
                })
                    .AsQueryable();
            }

            if (ppFilter.SelectedValue.HasValue)
            {
                if (option.IsGuaranteedToHaveConsolidator())
                {
                    followUpSummaries = followUpSummaries.Where(f => f.Consolidator != null && f.Consolidator.Id == ppFilter.SelectedValue);

                    followUpSummaries = followUpSummaries
                                        .OrderByDescending(f => f.Person.ConnectionStatusValue.Value == "GetConnected")
                                        .ThenBy(f => f.Consolidator.Id);
                }
                else
                {
                    // Defer this work in order to avoid hammering queries unless we need to
                    foreach (var followUpSummary in followUpSummaries)
                    {
                        followUpSummary.Group = followUpSummary.Person.GetPersonsPrimaryKciGroup(rockContext);
                    }
                    var person = new PersonService(rockContext).Get(ppFilter.SelectedValue.Value);
                    var groups = person.GetGroupsLead(rockContext);
                    followUpSummaries = followUpSummaries
                                        .Where(f => f.Group != null && groups.Select(g => g.Id).Contains(f.Group.Id));

                    followUpSummaries = followUpSummaries
                                        .OrderByDescending(f => f.Group.Id)
                                        .ThenBy(f => f.Consolidator.Id);

                    if (option == ViewOption.All)
                    {
                        followUpSummaries = followUpSummaries
                                            .OrderBy(p => p.Person.FirstName);
                    }
                    else
                    {
                        followUpSummaries = followUpSummaries
                                            .OrderByDescending(f => f.Group.Id)
                                            .ThenBy(f => f.Consolidator.Id);
                    }
                }
            }

            mergeFields["FollowUps"] = followUpSummaries.ToList();
            mergeFields["MyLine"]    = isMyLine;
            mergeFields["View"]      = ViewOptionText[option];

            string template = GetAttributeValue("LavaTemplate");

            // show debug info
            bool enableDebug = GetAttributeValue("EnableDebug").AsBoolean();

            if (enableDebug && IsUserAuthorized(Authorization.EDIT))
            {
                lDebug.Visible = true;
                lDebug.Text    = mergeFields.lavaDebugInfo();
            }

            lContent.Text = template.ResolveMergeFields(mergeFields);
        }
示例#11
0
        /// <summary>
        /// Fills the current person's information if it's available (e.g. passed by the person impersonation parameter)
        /// </summary>
        private void SetCurrentPersonDetails()
        {
            if (CurrentPerson == null)
            {
                return;
            }

            tbFirstName.Text = CurrentPerson.NickName;
            tbLastName.Text  = CurrentPerson.LastName;

            if (ValidateUsernameAsEmail)
            {
                tbUserName.Text = CurrentPerson.Email;
            }
            else
            {
                tbEmail.Text = CurrentPerson.Email;
            }

            switch (CurrentPerson.Gender)
            {
            case Gender.Male:
                ddlGender.SelectedValue = "M";
                break;

            case Gender.Female:
                ddlGender.SelectedValue = "F";
                break;

            default:
                ddlGender.SelectedValue = "U";
                break;
            }

            bdaypBirthDay.SelectedDate = CurrentPerson.BirthDate;

            var homeGroupTypeLocation = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME);
            var familyLocation        = CurrentPerson.PrimaryFamily.GroupLocations.Where(gl => gl.IsMailingLocation && gl.GroupLocationTypeValueId == homeGroupTypeLocation.Id).OrderBy(gl => gl.Order).FirstOrDefault();

            if (familyLocation != null && familyLocation.Location != null)
            {
                acAddress.Street1    = familyLocation.Location.Street1;
                acAddress.Street2    = familyLocation.Location.Street2;
                acAddress.City       = familyLocation.Location.City;
                acAddress.County     = familyLocation.Location.County;
                acAddress.State      = familyLocation.Location.State;
                acAddress.Country    = familyLocation.Location.Country;
                acAddress.PostalCode = familyLocation.Location.PostalCode;
            }

            foreach (RepeaterItem item in rPhoneNumbers.Items)
            {
                if (item.ItemType != ListItemType.Item)
                {
                    continue;
                }

                var phoneNumberType = ( HiddenField )item.FindControl("hfPhoneType");
                var phoneNumberBox  = ( PhoneNumberBox )item.FindControl("pnbPhone");
                var cbSms           = ( CheckBox )item.FindControl("cbSms");
                var cbIsUnlisted    = ( CheckBox )item.FindControl("cbUnlisted");

                if (phoneNumberBox == null || phoneNumberType == null || phoneNumberType.Value.IsNullOrWhiteSpace())
                {
                    continue;
                }

                var phoneNumber = CurrentPerson.PhoneNumbers.FirstOrDefault(pn => pn.NumberTypeValueId.HasValue && pn.NumberTypeValueId.Value == phoneNumberType.ValueAsInt());
                if (phoneNumber == null)
                {
                    continue;
                }

                phoneNumberBox.Number      = phoneNumber.NumberFormatted;
                phoneNumberBox.CountryCode = phoneNumberBox.CountryCode;
                cbSms.Checked        = phoneNumber.IsMessagingEnabled;
                cbIsUnlisted.Checked = phoneNumber.IsUnlisted;
            }

            if (cpCampus.Visible)
            {
                cpCampus.SetValue(CurrentPerson.GetCampus());
            }
        }
        /// <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)
        {
            if (GetAttributeValue(AttributeKeys.DisplayTerms).AsBoolean() && !cbTOS.Checked)
            {
                nbTOS.Visible = true;
                return;
            }

            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);

            var person = GetPerson(personService);

            var personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));

            if (person.Id != 0)
            {
                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };


                if (person.PhotoId != imgPhoto.BinaryFileId)
                {
                    changeRequest.EvaluatePropertyChange(person, "PhotoId", imgPhoto.BinaryFileId);
                    if (person.Photo != null)
                    {
                        changeRequest.EvaluatePropertyChange(person.Photo, "IsTemporary", true, true);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
                changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
                changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
                changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);
                changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

                var birthMonth = person.BirthMonth;
                var birthDay   = person.BirthDay;
                var birthYear  = person.BirthYear;

                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date is not greater than today.
                    var today = RockDateTime.Today;
                    while (birthday.Value.CompareTo(today) > 0)
                    {
                        birthday = birthday.Value.AddYears(-100);
                    }

                    changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month);
                    changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day);

                    if (birthday.Value.Year != DateTime.MinValue.Year)
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year);
                    }
                    else
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", ( int? )null);
                    }
                }

                if (ddlGradePicker.Visible)
                {
                    changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);
                }
                changeRequest.EvaluatePropertyChange(person, "Gender", rblGender.SelectedValue.ConvertToEnum <Gender>());

                var primaryFamilyMembers = person.GetFamilyMembers(true).Where(m => m.PersonId == person.Id).ToList();
                foreach (var member in primaryFamilyMembers)
                {
                    changeRequest.EvaluatePropertyChange(member, "GroupRoleId", rblRole.SelectedValue.AsInteger(), true);
                }

                var primaryFamily       = person.GetFamily(rockContext);
                var familyChangeRequest = new ChangeRequest
                {
                    EntityTypeId     = EntityTypeCache.Get(typeof(Group)).Id,
                    EntityId         = primaryFamily.Id,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };

                // update campus
                bool showCampus = GetAttributeValue("ShowCampusSelector").AsBoolean();
                if (showCampus)
                {
                    // Only update campus for adults
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    var adultGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();
                    var adultRole = groupTypeRoleService.Get(adultGuid);
                    if (rblRole.SelectedValue.AsInteger() == adultRole.Id)
                    {
                        familyChangeRequest.EvaluatePropertyChange(primaryFamily, "CampusId", cpCampus.SelectedCampusId);
                    }
                }

                //Evaluate PhoneNumbers
                bool showPhoneNumbers = GetAttributeValue("ShowPhoneNumbers").AsBoolean();
                if (showPhoneNumbers)
                {
                    var  phoneNumberTypeIds = new List <int>();
                    var  phoneNumbersScreen = new List <PhoneNumber>();
                    bool smsSelected        = false;
                    foreach (RepeaterItem item in rContactInfo.Items)
                    {
                        HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                        PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                        CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                        CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                        if (hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null)
                        {
                            int phoneNumberTypeId;
                            if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                            {
                                var    phoneNumberList = person.PhoneNumbers.Where(n => n.NumberTypeValueId == phoneNumberTypeId).ToList();
                                var    phoneNumber     = phoneNumberList.FirstOrDefault(pn => pn.Number == PhoneNumber.CleanNumber(pnbPhone.Number));
                                string oldPhoneNumber  = string.Empty;

                                if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                                {
                                    phoneNumber = new PhoneNumber
                                    {
                                        PersonId           = person.Id,
                                        NumberTypeValueId  = phoneNumberTypeId,
                                        CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                        IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                        Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                                    };
                                    var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                                    changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                                else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                                {
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                            }
                        }
                    }
                    //Remove old phone numbers or changed
                    var phoneNumbersToRemove = person.PhoneNumbers
                                               .Where(n => !phoneNumbersScreen.Any(n2 => n2.Number == n.Number && n2.NumberTypeValueId == n.NumberTypeValueId)).ToList();

                    foreach (var number in phoneNumbersToRemove)
                    {
                        var phoneComment = string.Format("{0}: {1}.", number.NumberTypeValue.Value, number.NumberFormatted);
                        changeRequest.DeleteEntity(number, true, phoneComment);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text.Trim());
                changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>());
                changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>());

                // if they used the ImageEditor, and cropped it, the non-cropped file is still in BinaryFile. So clean it up
                if (imgPhoto.CropBinaryFileId.HasValue)
                {
                    if (imgPhoto.CropBinaryFileId != person.PhotoId)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value);
                        if (binaryFile != null && binaryFile.IsTemporary)
                        {
                            string errorMessage;
                            if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                            {
                                binaryFileService.Delete(binaryFile);
                                rockContext.SaveChanges();
                            }
                        }
                    }
                }


                // save family information
                if (pnlAddress.Visible)
                {
                    var      currentLocation = person.GetHomeLocation();
                    Location location        = new Location
                    {
                        Street1    = acAddress.Street1,
                        Street2    = acAddress.Street2,
                        City       = acAddress.City,
                        State      = acAddress.State,
                        PostalCode = acAddress.PostalCode,
                    };
                    var globalAttributesCache = GlobalAttributesCache.Get();
                    location.Country = globalAttributesCache.OrganizationCountry;
                    location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

                    if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) ||
                        (currentLocation != null && currentLocation.Street1 != location.Street1))
                    {
                        LocationService locationService = new LocationService(rockContext);
                        locationService.Add(location);
                        rockContext.SaveChanges();

                        var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                        var homeLocationType     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

                        GroupLocation groupLocation = new GroupLocation
                        {
                            CreatedByPersonAliasId  = CurrentPersonAliasId,
                            ModifiedByPersonAliasId = CurrentPersonAliasId,
                            GroupId    = primaryFamily.Id,
                            LocationId = location.Id,
                            GroupLocationTypeValueId = homeLocationType.Id,
                            IsMailingLocation        = true,
                            IsMappedLocation         = true
                        };

                        var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString());

                        var homelocations = primaryFamily.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id);
                        foreach (var homelocation in homelocations)
                        {
                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "GroupLocationTypeValue",
                                previousLocationType,
                                true,
                                homelocation.Location.ToString());

                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "IsMailingLocation",
                                false,
                                true,
                                homelocation.Location.ToString());
                        }
                    }
                }

                // Handle both Child and Adult attributes together here
                var attributeGuids = GetAttributeValue(AttributeKeys.PersonAttributesAdult).SplitDelimitedValues().AsGuidList();
                attributeGuids.AddRange(GetAttributeValue(AttributeKeys.PersonAttributesChild).SplitDelimitedValues().AsGuidList());
                if (attributeGuids.Count > 0)
                {
                    person.LoadAttributes();
                    Helper.GetEditValues(phAttributes, person);
                    changeRequest.EvaluateAttributes(person);
                }

                List <string> errors;

                if (changeRequest.ChangeRecords.Any() ||
                    (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace()))
                {
                    changeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(changeRequest);
                    rockContext.SaveChanges();

                    changeRequest.CompleteChanges(rockContext, out errors);
                }

                if (familyChangeRequest.ChangeRecords.Any())
                {
                    familyChangeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(familyChangeRequest);
                    rockContext.SaveChanges();
                    familyChangeRequest.CompleteChanges(rockContext, out errors);
                }
            }
            else
            {
                var primaryFamily = CurrentPerson.GetFamily(rockContext);

                person.PhotoId = imgPhoto.BinaryFileId;

                if (imgPhoto.BinaryFileId.HasValue)
                {
                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                    var binaryFile = binaryFileService.Get(imgPhoto.BinaryFileId.Value);
                    binaryFile.IsTemporary = false;
                }

                person.FirstName     = tbFirstName.Text;
                person.NickName      = tbNickName.Text;
                person.LastName      = tbLastName.Text;
                person.TitleValueId  = ddlTitle.SelectedValue.AsIntegerOrNull();
                person.SuffixValueId = ddlSuffix.SelectedValue.AsIntegerOrNull();
                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date is not greater than today.
                    var today = RockDateTime.Today;
                    while (birthday.Value.CompareTo(today) > 0)
                    {
                        birthday = birthday.Value.AddYears(-100);
                    }

                    person.BirthMonth = birthday.Value.Month;
                    person.BirthDay   = birthday.Value.Day;

                    if (birthday.Value.Year != DateTime.MinValue.Year)
                    {
                        person.BirthYear = birthday.Value.Year;
                    }
                    else
                    {
                        person.BirthYear = null;
                    }
                }

                person.Gender          = rblGender.SelectedValue.ConvertToEnum <Gender>();
                person.Email           = tbEmail.Text;
                person.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();

                if (ddlGradePicker.Visible)
                {
                    person.GraduationYear = ypGraduation.SelectedYear;
                }


                GroupMember groupMember = new GroupMember
                {
                    PersonId    = person.Id,
                    GroupId     = primaryFamily.Id,
                    GroupRoleId = rblRole.SelectedValue.AsInteger()
                };

                PersonService.AddPersonToFamily(person, true, primaryFamily.Id, rblRole.SelectedValue.AsInteger(), rockContext);

                PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);

                foreach (RepeaterItem item in rContactInfo.Items)
                {
                    HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                    PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                    CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                    CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                    if (hfPhoneType != null &&
                        pnbPhone != null &&
                        cbSms != null &&
                        cbUnlisted != null &&
                        pnbPhone.Number.IsNotNullOrWhiteSpace())
                    {
                        int phoneNumberTypeId;
                        if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                        {
                            var phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            phoneNumberService.Add(phoneNumber);
                        }
                    }
                }
                rockContext.SaveChanges();

                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0,
                    RequestorComment = "Added as new person from My Account."
                };

                if (tbComments.Text.IsNotNullOrWhiteSpace())
                {
                    changeRequest.RequestorComment += "<br><br>Comment: " + tbComments.Text;
                }

                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(changeRequest);
                rockContext.SaveChanges();

                List <string> errors;
                changeRequest.CompleteChanges(rockContext, out errors);
            }

            NavigateToParentPage();
        }
        public ViewResult Detail(WaterQualityManagementPlanPrimaryKey waterQualityManagementPlanPrimaryKey)
        {
            var waterQualityManagementPlan = waterQualityManagementPlanPrimaryKey.EntityObject;

            var parcels = waterQualityManagementPlan.WaterQualityManagementPlanParcels
                          .Select(x => x.Parcel).ToList();
            var parcelGeoJsonFeatureCollection = parcels.ToGeoJsonFeatureCollection();
            var treatmentBMPs = CurrentPerson.GetInventoriedBMPsForWQMP(waterQualityManagementPlanPrimaryKey);
            var treatmentBmpGeoJsonFeatureCollection =
                treatmentBMPs.ToGeoJsonFeatureCollection();

            treatmentBmpGeoJsonFeatureCollection.Features.ForEach(x =>
            {
                var treatmentBmpID = x.Properties.ContainsKey("TreatmentBMPID")
                    ? int.Parse(x.Properties["TreatmentBMPID"].ToString())
                    : (int?)null;
                if (treatmentBmpID != null)
                {
                    x.Properties.Add("PopupUrl", SitkaRoute <TreatmentBMPController> .BuildUrlFromExpression(c => c.MapPopup(treatmentBmpID)));
                }
            });

            //var boundingBoxGeometries = new List<DbGeometry>();
            //boundingBoxGeometries.AddRange(treatmentBMPs.Select(x=>x.LocationPoint4326));
            //boundingBoxGeometries.AddRange(parcels.Select(x=>x.ParcelGeometry4326));

            var layerGeoJsons = new List <LayerGeoJson>
            {
                new LayerGeoJson(FieldDefinitionType.Parcel.GetFieldDefinitionLabelPluralized(),
                                 parcelGeoJsonFeatureCollection,
                                 ParcelModelExtensions.ParcelColor,
                                 1,
                                 LayerInitialVisibility.Show),
                new LayerGeoJson(FieldDefinitionType.TreatmentBMP.GetFieldDefinitionLabelPluralized(),
                                 treatmentBmpGeoJsonFeatureCollection,
                                 "#935f59",
                                 1,
                                 LayerInitialVisibility.Show)
            };
            //var mapInitJson = new MapInitJson("waterQualityManagementPlanMap", 0, layerGeoJsons,
            //    new BoundingBox(boundingBoxGeometries));

            var mapInitJson = new MapInitJson("waterQualityManagementPlanMap", 0, layerGeoJsons,
                                              BoundingBox.MakeBoundingBoxFromLayerGeoJsonList(layerGeoJsons));

            if (treatmentBMPs.Any(x => x.Delineation != null))
            {
                mapInitJson.Layers.Add(StormwaterMapInitJson.MakeDelineationLayerGeoJson(
                                           treatmentBMPs.Where(x => x.Delineation != null).Select(x => x.Delineation)));
            }

            var waterQualityManagementPlanVerifies = HttpRequestStorage.DatabaseEntities.WaterQualityManagementPlanVerifies.Where(x =>
                                                                                                                                  x.WaterQualityManagementPlanID == waterQualityManagementPlan.PrimaryKey).OrderByDescending(x => x.VerificationDate).ToList();
            var waterQualityManagementPlanVerifyDraft = waterQualityManagementPlanVerifies.SingleOrDefault(x => x.IsDraft);

            var waterQualityManagementPlanVerifyQuickBMP =
                HttpRequestStorage.DatabaseEntities.WaterQualityManagementPlanVerifyQuickBMPs.Where(x =>
                                                                                                    x.WaterQualityManagementPlanVerify.WaterQualityManagementPlanID ==
                                                                                                    waterQualityManagementPlan.WaterQualityManagementPlanID).ToList();
            var waterQualityManagementPlanVerifyTreatmentBMP =
                HttpRequestStorage.DatabaseEntities.WaterQualityManagementPlanVerifyTreatmentBMPs.Where(x =>
                                                                                                        x.WaterQualityManagementPlanVerify.WaterQualityManagementPlanID ==
                                                                                                        waterQualityManagementPlan.WaterQualityManagementPlanID).ToList();

            var anyLspcBasins = waterQualityManagementPlan.WaterQualityManagementPlanBoundary != null && HttpRequestStorage.DatabaseEntities.LSPCBasins.Any(x =>
                                                                                                                                                            x.LSPCBasinGeometry.Intersects(waterQualityManagementPlan.WaterQualityManagementPlanBoundary));

            var dryWeatherFlowOverrides = DryWeatherFlowOverride.All;
            var waterQualityManagementPlanModelingApproaches = WaterQualityManagementPlanModelingApproach.All;

            var viewData = new DetailViewData(CurrentPerson, waterQualityManagementPlan,
                                              waterQualityManagementPlanVerifyDraft, mapInitJson, treatmentBMPs, new ParcelGridSpec(),
                                              waterQualityManagementPlanVerifies, waterQualityManagementPlanVerifyQuickBMP,
                                              waterQualityManagementPlanVerifyTreatmentBMP,
                                              new HRUCharacteristicsViewData(waterQualityManagementPlan,
                                                                             ((IHaveHRUCharacteristics)waterQualityManagementPlan).GetHRUCharacteristics().ToList()),
                                              anyLspcBasins, dryWeatherFlowOverrides, waterQualityManagementPlanModelingApproaches, new ModeledPerformanceViewData(waterQualityManagementPlan, CurrentPerson));

            return(RazorView <Detail, DetailViewData>(viewData));
        }
示例#14
0
        protected override void OnLoad(EventArgs e)
        {
            if (!IsPostBack)
            {
                var campusCacheEnabled = CampusCache.All().AsQueryable().Where(c => c.IsActive == true).ToList();
                cpCampus.DataSource = campusCacheEnabled;
                cpCampus.DataBind();

                // Resolve the text field merge fields
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, _targetPerson);
                if (_targetPerson != null)
                {
                    mergeFields.Add("Person", _targetPerson);
                }

                lPartnershipText.Text = GetAttributeValue("PartnershipText").ResolveMergeFields(mergeFields);
            }

            int ageRequirement = Convert.ToInt32(GetAttributeValue("AgeRequirement"));

            RequiredAge = GetAttributeValue("AgeRequirement");


            if (DateTime.Now.Month == 12)
            {
                CurrentYearAdd++;
                CurrentDateTime = CurrentDateTime.AddYears(CurrentYearAdd);
            }

            lYear.Text = CurrentDateTime.Year.ToString();


            if (CurrentPerson != null)
            {
                _targetPerson = CurrentPerson;
                var currentPersonCampus = CurrentPerson.GetCampus();

                if (currentPersonCampus == null)
                {
                    mdCampus.Show();
                    tbSignature.Required = false;
                }

                if (_targetPerson.Age != null)
                {
                    if (_targetPerson.Age < ageRequirement)
                    {
                        mdNotLoggedIn.Show(String.Format("Sorry, you must be at least {0} to sign the NewPointe Partnership Covenant", RequiredAge), ModalAlertType.Alert);

                        pnlSignup.Visible     = false;
                        pnlNotSixteen.Visible = true;
                        pnlSignature.Visible  = false;
                    }
                }
                else
                {
                    mdAge.Show();
                    tbSignature.Required = false;
                }

                lPersonInfo.Text = _targetPerson.FullName;
            }
            else
            {
                string path = HttpContext.Current.Request.Url.AbsolutePath;
                path = path.UrlEncode();

                mdNotLoggedIn.Show(string.Format("Before you can sign the Partnership Covenant, you must log in with your MyNewPointe account.<br /><br /> <p class=\"text-center\"><a href = \"https://newpointe.org/Login?returnurl={0} \" class=\"btn btn-newpointe\">LOG IN</a> <a href = \"https://newpointe.org/NewAccount?returnurl={0} \" class=\"btn btn-newpointe\">REGISTER</a></p>", path), ModalAlertType.Alert);

                pnlSignup.Visible      = false;
                pnlNotLoggedIn.Visible = true;
                pnlSignature.Visible   = false;
            }
        }
示例#15
0
        protected override void OnLoad(EventArgs e)
        {
            nbAlert.Visible = false;

            if (CurrentPerson == null)
            {
                nbAlert.Visible = true;
                nbAlert.Text    = "Please log in to continue.";
                return;
            }
            if (!Page.IsPostBack)
            {
                RockContext rockContext   = new RockContext();
                var         familyMembers = CurrentPerson.GetFamilies().SelectMany(f => f.Members).Select(m => m.Person).ToList();

                AddCaretakees(familyMembers, rockContext);


                var groupTypeStrings = GetAttributeValue("GroupTypes").SplitDelimitedValues();
                var groupTypeIds     = new List <int>();
                foreach (var groupType in groupTypeStrings)
                {
                    var groupTypeCache = GroupTypeCache.Get(groupType.AsGuid());
                    if (groupTypeCache != null)
                    {
                        groupTypeIds.Add(groupTypeCache.Id);
                    }
                }

                var groups = new GroupService(rockContext).Queryable()
                             .Where(g => g.IsActive && !g.IsArchived && groupTypeIds.Contains(g.GroupTypeId));
                if (!groups.Any())
                {
                    nbAlert.Visible = true;
                    nbAlert.Text    = "Please configure this block.";
                    return;
                }

                var members = groups.SelectMany(g => g.Members);


                var gridData = new List <GridData>();
                AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);
                foreach (var person in familyMembers)
                {
                    //Get all the camp group members for this person
                    List <GroupMember> medicalMembers = members.Where(m => m.PersonId == person.Id).ToList();

                    if (!medicalMembers.Any())
                    {
                        continue;
                    }

                    GridData data = new GridData
                    {
                        Id          = person.PrimaryAlias.Guid,
                        Name        = person.FullName,
                        Group       = string.Join("<br>", medicalMembers.Select(m => m.Group.Name)),
                        Medications = "No Medication Information"
                    };
                    person.LoadAttributes();
                    var attribute       = person.GetAttributeValue(GetAttributeValue("MedicationMatrixKey"));
                    var attributeMatrix = attributeMatrixService.Get(attribute.AsGuid());
                    if (attributeMatrix != null)
                    {
                        var lava     = attributeMatrix.AttributeMatrixTemplate.FormattedLava;
                        var template = attributeMatrix.AttributeMatrixTemplate;
                        template.LoadAttributes();
                        AttributeMatrixItem tempAttributeMatrixItem = new AttributeMatrixItem();
                        tempAttributeMatrixItem.AttributeMatrix = attributeMatrix;
                        tempAttributeMatrixItem.LoadAttributes();
                        Dictionary <string, object> mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, null, new Rock.Lava.CommonMergeFieldsOptions {
                            GetLegacyGlobalMergeFields = false
                        });
                        mergeFields.Add("AttributeMatrix", attributeMatrix);
                        mergeFields.Add("ItemAttributes", tempAttributeMatrixItem.Attributes.Select(a => a.Value).OrderBy(a => a.Order).ThenBy(a => a.Name));
                        mergeFields.Add("AttributeMatrixItems", attributeMatrix.AttributeMatrixItems.OrderBy(a => a.Order));
                        var medications = lava.ResolveMergeFields(mergeFields);
                        data.Medications = medications;
                    }
                    gridData.Add(data);
                }

                gGrid.DataSource = gridData;
                gGrid.DataBind();
            }
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (_family == null)
            {
                FamilyMember you    = null;
                FamilyMember spouse = null;

                if (CurrentPerson != null)
                {
                    _family = CurrentPerson.Family();

                    you = _family.FamilyMembers.FindByGuid(CurrentPerson.PersonGUID);

                    spouse = _family.Spouse(CurrentPerson);
                }
                else
                {
                    _family = new Family();

                    you            = new FamilyMember();
                    you.PersonGUID = Guid.NewGuid();
                    you.FamilyRole = new Lookup(SystemLookup.FamilyRole_Adult);
                    you.Gender     = Arena.Enums.Gender.Unknown;
                    _family.FamilyMembers.Add(you);
                }

                // Save Spouse
                if (spouse == null)
                {
                    spouse            = new FamilyMember();
                    spouse.PersonGUID = Guid.NewGuid();
                    spouse.FamilyRole = new Lookup(SystemLookup.FamilyRole_Adult);
                    if (CurrentPerson != null && CurrentPerson.Gender == Arena.Enums.Gender.Male)
                    {
                        you.Gender = Arena.Enums.Gender.Female;
                    }
                    else if (CurrentPerson != null && CurrentPerson.Gender == Arena.Enums.Gender.Female)
                    {
                        you.Gender = Arena.Enums.Gender.Male;
                    }
                    else
                    {
                        you.Gender = Arena.Enums.Gender.Unknown;
                    }
                    _family.FamilyMembers.Add(spouse);
                }

                // Save Guids
                hfYouGuid.Value    = you.PersonGUID.ToString();
                hfSpouseGuid.Value = spouse.PersonGUID.ToString();
            }

            if (Page.IsPostBack)
            {
                UpdateChanges();
            }
            else
            {
                ShowYou();
            }
        }
示例#17
0
        private static void Debug()
        {
            ConsoleHandler.Start();
            Game = new Game();
            Game.Load();
            Game.Current = new Round(1);
            Game.UpdateStatic();

            ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(DependencyObject), new FrameworkPropertyMetadata(Int32.MaxValue));
            GameInterface = new GameInterface();
            ((Interface.GameWindow)GameInterface.Window).grid.Children.Add(Map = Map.TileGenerator.CreateTiles());

            #region Debug
            //- Player
            CurrentPerson           = (Person)Game.FindCitizen(0);
            CurrentPerson.ImageName = "person_geecku";
            CurrentPerson.Culture   = Game.FindCulture(History.Cultures.Cultures.Deutsch);
            CurrentPerson.Ideology  = Game.FindIdeology(1);
            CurrentPerson.Party     = CurrentPerson.Location.CountryOwner.Government.RegisteredParties[0];

            //- Banks
            Bank test_bank = new Bank("Bank von Bayern");
            test_bank.GoldQuanity = 7;
            Game.Banks.Add(test_bank, test_bank.ID);

            //- Provinces
            Game.FindProvince(1).SetOwner(Game.FindCountry(1));
            Game.FindProvince(2).SetOwner(Game.FindCountry(1));
            Game.FindProvince(5).SetOwner(Game.FindCountry(1));

            //- Eckard
            Person person = (Person)Game.FindCitizen(10);
            person.Ideology = Game.FindIdeology(1);
            person.Culture  = Game.FindCulture(History.Cultures.Cultures.Deutsch);

            CurrentPerson.TalkTo(person);
            CurrentPerson.ChangeFollower(person);

            //- Göring
            person = (Person)Game.FindCitizen(11);
            person.JoinArmy(Game.FindArmy(1));
            person.Army.PromotePerson(person, 8);

            //- von Kahr
            person = (Person)Game.FindCitizen(12);
            person.Party.DefineNewLeader(person);

            //- von Lossow
            person = (Person)Game.FindCitizen(13);
            person.JoinArmy(Game.FindArmy(1));
            person.Army.PromotePerson(person, 2);
            person.Army.DefineNewLeader(person);

            //- Röhm
            person = (Person)Game.FindCitizen(14);
            person.JoinArmy(Game.FindArmy(1));
            person.Army.PromotePerson(person, 9);

            //- Hitler
            person = (Person)Game.FindCitizen(16);
            person.JoinArmy(Engine.Game.FindArmy(1));
            person.Army.PromotePerson(person, 19);

            //- Mayer
            person = (Person)Game.FindCitizen(15);
            person.JoinArmy(Engine.Game.FindArmy(1));
            person.Army.PromotePerson(person, 8);
            #endregion

            #region Historical OOB
            //- 'Infanterieführer VII (Reichswehr)' (17. Infanterie-Division)
            Person franz_epp = (Person)Game.FindCitizen(17);
            franz_epp.JoinArmy(Game.FindArmy(1));
            franz_epp.Army.PromotePerson(franz_epp, 3);

            Division inf_vii = new Division(franz_epp.LocationID);
            Game.Units.Add(inf_vii, inf_vii.ID);
            inf_vii.Name = "Infanterieführer VII. (Reichswehr)";
            inf_vii.DefineNewCommander(franz_epp);
            inf_vii.ClearLocalUnits();
            inf_vii.Owner   = Game.FindCountry(0);
            inf_vii.HQ.Name = "Divisions Kommando VII. der Reichswehr";

            #region Division LocalUnits
            RegularCavalry cav2 = new RegularCavalry(inf_vii);
            cav2.Name = "Divisions-Kavallerie 302";
            cav2.SetUnitType(UnitTypes.Platoon);
            inf_vii.AddLocalUnit(cav2);

            RegularInfantry inf = new RegularInfantry(inf_vii);
            inf.Name = "Guard Infanterie 'Landwehr'";
            inf.SetUnitType(UnitTypes.Group);
            inf_vii.AddLocalUnit(inf);

            RegularCavalry cav1 = new RegularCavalry(inf_vii);
            cav1.Name = "Kavalleriestand Reichswehr";
            cav1.SetUnitType(UnitTypes.Team);
            inf_vii.AddLocalUnit(cav1);
            #endregion

            #region Regiments
            //- 19. Infanterie-Regiment "Friedrich von Haack"
            Person p1 = (Person)Game.FindCitizen(18);
            p1.JoinArmy(Game.FindArmy(1));
            p1.Army.PromotePerson(p1, 5);
            Regiment reg1 = Regiment.CreateDefault(p1.LocationID);
            inf_vii.AddSubUnit(reg1);
            reg1.Name  = "19. Infanterie-Regiment";
            reg1.Owner = Game.FindCountry(0);
            reg1.DefineNewCommander(p1);
            reg1.Parent = inf_vii;

            //- 20. Infanterie-Regiment "Ludwig Leupold"
            Person p2 = (Person)Game.FindCitizen(19);
            p2.JoinArmy(Game.FindArmy(1));
            p2.Army.PromotePerson(p2, 5);
            Regiment reg2 = new Regiment(p2.LocationID);
            inf_vii.AddSubUnit(reg2);
            reg2.Name  = "20. Infanterie-Regiment";
            reg2.Owner = Game.FindCountry(0);
            reg2.DefineNewCommander(p2);
            reg2.Parent = inf_vii;
            Game.Units.Add(reg2, reg2.ID);
            #region 20. Inf-Regiment
            Person    c  = (Person)Game.FindCitizen(14);
            Bataillon b1 = Bataillon.CreateDefault(p2.LocationID);
            b1.Name   = "1. Bataillon 'Rheinmayer-Köln'";
            b1.Owner  = Game.FindCountry(0);
            b1.Parent = reg2;
            b1.DefineNewCommander(c);
            reg2.AddSubUnit(b1);
            reg2.LinkUp(b1);

            Bataillon b2 = Bataillon.CreateDefault(114);
            b2.Name   = "2. Bataillon 'Pait'";
            b2.Owner  = Game.FindCountry(0);
            b2.Parent = reg2;
            reg2.AddSubUnit(b2);

            Bataillon b3 = Bataillon.CreateDefault(151);
            b3.Name   = "3. Bataillon 'Kaiser'";
            b3.Owner  = Game.FindCountry(0);
            b3.Parent = reg2;
            reg2.AddSubUnit(b3);
            #endregion

            //- 21. Infanterie-Regiment "Leonhard Haussel"
            Person p3 = (Person)Game.FindCitizen(20);
            p3.JoinArmy(Game.FindArmy(1));
            p3.Army.PromotePerson(p3, 5);
            Regiment reg3 = Regiment.CreateDefault(p3.LocationID);
            inf_vii.AddSubUnit(reg3);
            reg3.Name  = "21. Infanterie-Regiment";
            reg3.Owner = Game.FindCountry(0);
            reg3.DefineNewCommander(p3);
            reg3.Parent = inf_vii;
            #endregion

            #endregion


            Game.AfterMapLoad();
        }
示例#18
0
        private Dictionary <string, string> BuildFilter()
        {
            Dictionary <string, string> Filter = new Dictionary <string, string>();

            System.Text.StringBuilder StatusSB = new System.Text.StringBuilder();

            foreach (ListItem item in cbListStatus.Items)
            {
                if (item.Selected)
                {
                    StatusSB.Append(item.Value + ",");
                }
            }
            StatusSB.Append("0");
            Filter.Add("StatusLUID", StatusSB.ToString());

            System.Text.StringBuilder RequisitionTypeSB = new System.Text.StringBuilder();
            foreach (ListItem item in cbListType.Items)
            {
                if (item.Selected)
                {
                    StatusSB.Append(item.Value + ",");
                }
            }
            StatusSB.Append("0");
            Filter.Add("TypeLUID", StatusSB.ToString());

            foreach (ListItem item in cbShow.Items)
            {
                Filter.Add(string.Format("Show_{0}", item.Value), item.Selected.ToString());
            }

            int poNumber;

            if (int.TryParse(txtPONumber.Text, out poNumber) && poNumber > 0)
            {
                Filter.Add("PONumber", poNumber.ToString());
            }

            if (txtFilterSubmitted.LowerValue.HasValue)
            {
                Filter.Add("SubmitOnStart", txtFilterSubmitted.LowerValue.Value.ToShortDateString());
            }

            if (txtFilterSubmitted.UpperValue.HasValue)
            {
                Filter.Add("SubmitOnEnd", txtFilterSubmitted.UpperValue.Value.ToShortDateString());
            }

            if (hfFilterSubmittedBy.Visible && hfFilterSubmittedBy.StaffPersonAliasId.HasValue)
            {
                Filter.Add("RequesterID", hfFilterSubmittedBy.StaffPersonAliasId.ToString());
            }

            int MinistryID = 0;

            if (ddlMinistry.Visible && int.TryParse(ddlMinistry.SelectedValue, out MinistryID))
            {
                Filter.Add("MinistryLUID", MinistryID.ToString());
            }

            int LocationID = 0;

            if (ddlLocation.Visible && int.TryParse(ddlLocation.SelectedValue, out LocationID))
            {
                Filter.Add("LocationLUID", LocationID.ToString());
            }

            bool ShowInactive = false;

            if (chkShowInactive.Visible)
            {
                ShowInactive = chkShowInactive.Checked;
            }

            Filter.Add("ShowInactive", ShowInactive.ToString());


            Filter.Add("PersonID", CurrentPerson.Id.ToString());
            UserLoginService loginService = new UserLoginService(new RockContext());

            Filter.Add("UserName", string.Join(",", loginService.GetByPersonId(CurrentPerson.Id).Select(l => l.UserName)));
            CurrentPerson.LoadAttributes();
            bool skipLocation = false;

            if (MinistryAreaAttributeIDSetting != null)
            {
                var ministryValue = DefinedValueCache.Get(CurrentPerson.AttributeValues[AttributeCache.Get(MinistryAreaAttributeIDSetting).Key].Value);
                if (ministryValue != null)
                {
                    Filter.Add("MyMinistryID", ministryValue.Id.ToString());
                }

                // If the current person is in the security group, skip the location lookup
                var groupGuid = ministryValue.GetAttributeValue("ChurchWidePurchasingSecurityGroup").AsGuidOrNull();
                if (groupGuid.HasValue)
                {
                    GroupService groupService = new GroupService(new RockContext());
                    Group        group        = groupService.Get(groupGuid.Value);
                    skipLocation = group.Members.Where(gm => gm.PersonId == CurrentPerson.Id).Any();
                }
            }

            if (MinistryLocationAttributeIDSetting != null && !skipLocation)
            {
                var locationValue = DefinedValueCache.Get(CurrentPerson.AttributeValues[AttributeCache.Get(MinistryLocationAttributeIDSetting).Key].Value);

                if (locationValue != null)
                {
                    Filter.Add("MyLocationID", locationValue.Id.ToString());
                }
            }
            return(Filter);
        }
示例#19
0
        /// <summary>
        /// Loads the campuses
        /// </summary>
        protected void LoadDropdowns()
        {
            var campusEntityType = EntityTypeCache.Get(typeof(Campus));
            var currentCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

            var campusIdString = Request.QueryString["campusId"];

            if (campusIdString != null)
            {
                var campusId = campusIdString.AsInteger();

                // if there is a query parameter, ensure that the Campus Context cookie is set (and has an updated expiration)
                // note, the Campus Context might already match due to the query parameter, but has a different cookie context, so we still need to ensure the cookie context is updated
                currentCampus = SetCampusContext(campusId, false);
            }

            // if the currentCampus isn't determined yet, and DefaultToCurrentUser, and the person has a CampusId, use that as the campus context
            if (currentCampus == null && GetAttributeValue("DefaultToCurrentUser").AsBoolean() && CurrentPerson != null)
            {
                var campusId = CurrentPerson.GetFamily().CampusId;
                if (campusId.HasValue)
                {
                    currentCampus = SetCampusContext(campusId.Value, false);
                }
            }

            if (currentCampus != null)
            {
                var mergeObjects = new Dictionary <string, object>();
                mergeObjects.Add("CampusName", currentCampus.Name);
                lCurrentSelection.Text = GetAttributeValue("CurrentItemTemplate").ResolveMergeFields(mergeObjects);
            }
            else
            {
                lCurrentSelection.Text = GetAttributeValue("NoCampusText");
            }

            bool includeInactive = GetAttributeValue("IncludeInactiveCampuses").AsBoolean();
            var  campusList      = CampusCache.All(includeInactive)
                                   .Select(a => new CampusItem {
                Name = a.Name, Id = a.Id
            })
                                   .ToList();

            // run lava on each campus
            string dropdownItemTemplate = GetAttributeValue("DropdownItemTemplate");

            if (!string.IsNullOrWhiteSpace(dropdownItemTemplate))
            {
                foreach (var campus in campusList)
                {
                    var mergeObjects = new Dictionary <string, object>();
                    mergeObjects.Add("CampusName", campus.Name);
                    campus.Name = dropdownItemTemplate.ResolveMergeFields(mergeObjects);
                }
            }

            // check if the campus can be unselected
            if (!string.IsNullOrEmpty(GetAttributeValue("ClearSelectionText")))
            {
                var blankCampus = new CampusItem
                {
                    Name = GetAttributeValue("ClearSelectionText"),
                    Id   = Rock.Constants.All.Id
                };

                campusList.Insert(0, blankCampus);
            }

            rptCampuses.DataSource = campusList;
            rptCampuses.DataBind();
        }
示例#20
0
        public void Move(int src, int dst)
        {
            int off = Math.Abs(src - dst);

            if (GameBoard.GetGameBoard[dst].GetOwner != CurrentPerson && GameBoard.GetGameBoard[dst].GetOwner != null)
            {
                GameBoard.TransferPips(OtherPerson, dst, OtherPenIndx);
                OtherPerson.AddPoints(dst);
                OtherPerson.Penalize = true;
                GameWindow.UpdateStack(OtherPenIndx);
            }

            GameBoard.TransferPips(CurrentPerson, src, dst);
            GameWindow.UpdateStack(src);
            GameWindow.UpdateStack(dst);

            if (GameBoard.GetGameBoard[PenIndx].PipsCount == 0)
            {
                CurrentPerson.Penalize = false;
            }

            CurrentPerson.SubtractPoints(off);
            GameWindow.UpdatePlayerPoints();

            if (CheckWin(dst))
            {
                CurrentPerson.Game_Points += 1;
                EndGame();
                return;
            }

            if (off == dice[0] + dice[1])
            {
                mvs = 0;
            }
            else
            {
                mvs--;
                if (off == dice.GetResult[0])
                {
                    dice[0] = 0;
                }
                else
                {
                    dice[1] = 0;
                }
                GameWindow.UpdateGameDice();
            }

            if (ArtificialIntelligence.CountPossibleMoves(this) == 0)
            {
                mvs = 0;
            }

            if (mvs == 0)
            {
                NextPerson();
            }
            else
            {
                GameWindow.WaitingForMove();
            }
        }
        private ViewResult ViewUpdateDelineationGeometry(UpdateDelineationGeometryViewModel viewModel)
        {
            var newGisUploadUrl = SitkaRoute <DelineationUploadController> .BuildUrlFromExpression(c => c.UpdateDelineationGeometry());

            var approveGisUploadUrl = SitkaRoute <DelineationUploadController> .BuildUrlFromExpression(c => c.ApproveDelineationGisUpload());

            var viewData = new UpdateDelineationGeometryViewData(CurrentPerson, newGisUploadUrl, approveGisUploadUrl, CurrentPerson.GetStormwaterJurisdictionsPersonCanView());

            return(RazorView <UpdateDelineationGeometry, UpdateDelineationGeometryViewData, UpdateDelineationGeometryViewModel>(viewData, viewModel));
        }
示例#22
0
        public override MobileBlock GetMobile(string parameter)
        {
            var form = new List <FormElementItem>();

            var firstName = new FormElementItem
            {
                Type     = FormElementType.Entry,
                Key      = "firstName",
                Label    = "First Name",
                Required = true
            };

            if (CurrentPerson != null)
            {
                firstName.Value = CurrentPerson.NickName;
            }
            form.Add(firstName);

            var lastName = new FormElementItem
            {
                Type     = FormElementType.Entry,
                Key      = "lastName",
                Label    = "Last Name",
                Required = GetAttributeValue("RequireLastName").AsBoolean()
            };

            if (CurrentPerson != null)
            {
                lastName.Value = CurrentPerson.LastName;
            }
            form.Add(lastName);

            var email = new FormElementItem
            {
                Type     = FormElementType.Entry,
                Key      = "email",
                Label    = "Email",
                Required = false,
                Keyboard = Keyboard.Email
            };

            if (CurrentPerson != null)
            {
                email.Value = CurrentPerson.Email;
            }
            form.Add(email);

            if (GetAttributeValue("ShowCampus").AsBoolean())
            {
                var campus = new FormElementItem
                {
                    Type     = FormElementType.Picker,
                    Key      = "campus",
                    Label    = "Campus",
                    Options  = CampusCache.All().ToDictionary(c => c.Id.ToString(), c => c.Name),
                    Required = GetAttributeValue("RequireCampus").AsBoolean()
                };
                if (CurrentPerson != null)
                {
                    campus.Value = CurrentPerson.GetCampus().Id.ToString();
                }

                form.Add(campus);
            }

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("CategorySelection")))
            {
                var categoryGuid = GetAttributeValue("CategorySelection").AsGuid();
                var categoryList = CategoryCache.Read(categoryGuid).Categories.ToDictionary(c => c.Id.ToString(), c => c.Name);

                var category = new FormElementItem
                {
                    Type     = FormElementType.Picker,
                    Key      = "category",
                    Label    = "Category",
                    Options  = categoryList,
                    Required = true
                };
                form.Add(category);
            }

            var request = new FormElementItem
            {
                Type          = FormElementType.Editor,
                Label         = "Request",
                Key           = "request",
                HeightRequest = 100,
                Required      = true
            };

            form.Add(request);

            if (GetAttributeValue("EnableUrgentFlag").AsBoolean())
            {
                var urgent = new FormElementItem
                {
                    Type  = FormElementType.Switch,
                    Key   = "urgent",
                    Label = "Urgent?"
                };
                form.Add(urgent);
            }

            if (GetAttributeValue("DefaultAllowCommentsSetting").AsBoolean())
            {
                var allowComments = new FormElementItem
                {
                    Type  = FormElementType.Switch,
                    Key   = "allowComments",
                    Label = "Allow Encouraging Comments?"
                };
                form.Add(allowComments);
            }

            if (GetAttributeValue("EnablePublicDisplayFlag").AsBoolean())
            {
                var allowPublication = new FormElementItem
                {
                    Type  = FormElementType.Switch,
                    Key   = "allowPublication",
                    Label = "Allow Publication?"
                };
                form.Add(allowPublication);
            }

            var button = new FormElementItem
            {
                Type  = FormElementType.Button,
                Label = "Save Request",
                Key   = "save"
            };

            form.Add(button);

            CustomAttributes.Add("FormElementItems", JsonConvert.SerializeObject(form));
            return(new MobileBlock()
            {
                BlockType = "Avalanche.Blocks.FormBlock",
                Attributes = CustomAttributes
            });
        }
示例#23
0
        public ActionResult Invite(InviteViewModel viewModel)
        {
            var toolDisplayName = "Orange County Stormwater Tools";
            var homeUrl         = SitkaRoute <HomeController> .BuildAbsoluteUrlHttpsFromExpression(x => x.Index(), NeptuneWebConfiguration.CanonicalHostNameRoot);

            var loginUrl =
                SitkaRoute <AccountController> .BuildAbsoluteUrlHttpsFromExpression(x => x.LogOn(),
                                                                                    NeptuneWebConfiguration.CanonicalHostName);

            var supportUrl = SitkaRoute <HelpController> .BuildAbsoluteUrlHttpsFromExpression(x => x.Support(), NeptuneWebConfiguration.CanonicalHostNameRoot);

            var inviteModel = new KeystoneService.KeystoneInviteModel
            {
                FirstName        = viewModel.FirstName,
                LastName         = viewModel.LastName,
                Email            = viewModel.Email,
                SiteName         = toolDisplayName,
                Subject          = $"Invitation to the {toolDisplayName}",
                WelcomeText      = $"You have been invited by a colleague to create an account in the <a href=\"{homeUrl}\">{toolDisplayName}</a>. The {toolDisplayName} application is a collaborative effort of Orange County Public Works, MS4 Permittees, and other organizations.",
                RedirectURL      = loginUrl,
                SupportBlock     = $"If you have any questions, please visit our <a href=\"{supportUrl}\">support page</a>",
                OrganizationGuid = viewModel.OrganizationGuid,
                SignatureBlock   = $"The {toolDisplayName} team"
            };

            var keystoneService = new KeystoneService(HttpRequestStorage.GetHttpContextUserThroughOwin());
            var response        = keystoneService.Invite(inviteModel);

            if (response.StatusCode != HttpStatusCode.OK || response.Error != null)
            {
                ModelState.AddModelError("Email", $"There was a problem inviting the user to Keystone: {response.Error.Message}.");
                if (response.Error.ModelState != null)
                {
                    foreach (var modelStateKey in response.Error.ModelState.Keys)
                    {
                        foreach (var err in response.Error.ModelState[modelStateKey])
                        {
                            ModelState.AddModelError(modelStateKey, err);
                        }
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                return(ViewInvite(viewModel));
            }

            var keystoneUser = response.Payload.Claims;
            var existingUser = HttpRequestStorage.DatabaseEntities.People.GetPersonByPersonGuid(keystoneUser.UserGuid);

            if (existingUser != null)
            {
                SetMessageForDisplay($"{existingUser.GetFullNameFirstLastAndOrgAsUrl()} already has an account.</a>.");
                return(RedirectToAction(new SitkaRoute <UserController>(x => x.Detail(existingUser))));
            }

            var setJurisdictions = !CurrentPerson.IsAdministrator();
            var newUser          = CreateNewFirmaPerson(keystoneUser, keystoneUser.OrganizationGuid);

            HttpRequestStorage.DatabaseEntities.SaveChanges();

            if (setJurisdictions)
            {
                foreach (var stormwaterJurisdictionPerson in CurrentPerson.StormwaterJurisdictionPeople)
                {
                    newUser.StormwaterJurisdictionPeople.Add(new StormwaterJurisdictionPerson(stormwaterJurisdictionPerson.StormwaterJurisdictionID, newUser.PersonID));
                }
            }

            newUser.RoleID = Role.JurisdictionEditor.RoleID;

            HttpRequestStorage.DatabaseEntities.SaveChanges();

            SetMessageForDisplay(
                $"{newUser.GetFullNameFirstLastAndOrgAsUrl()} successfully added. You may want to assign them a role</a>.");
            return(RedirectToAction(new SitkaRoute <UserController>(x => x.Detail(newUser))));
        }
        /// <summary>
        /// Loads the campuses
        /// </summary>
        protected void LoadCampusDropdowns()
        {
            var campusEntityType = EntityTypeCache.Read(typeof(Campus));
            var currentCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

            var campusIdString = Request.QueryString["campusId"];

            if (campusIdString != null)
            {
                var campusId = campusIdString.AsInteger();

                if (currentCampus == null || currentCampus.Id != campusId)
                {
                    currentCampus = SetCampusContext(campusId, false);
                }
            }

            if (currentCampus == null && GetAttributeValue("DefaultToCurrentUser").AsBoolean() && CurrentPerson != null)
            {
                currentCampus = CurrentPerson.GetFamilies().First().Campus;
            }

            if (currentCampus != null)
            {
                var mergeObjects = new Dictionary <string, object>();
                mergeObjects.Add("CampusName", currentCampus.Name);
                lCurrentCampusSelection.Text = GetAttributeValue("CampusCurrentItemTemplate").ResolveMergeFields(mergeObjects);
                _currentCampusText           = GetAttributeValue("CampusCurrentItemTemplate").ResolveMergeFields(mergeObjects);
            }
            else
            {
                lCurrentCampusSelection.Text = GetAttributeValue("NoCampusText");
                _currentCampusText           = GetAttributeValue("NoCampusText");
            }

            var campusList = CampusCache.All()
                             .Select(a => new CampusItem {
                Name = a.Name, Id = a.Id
            })
                             .ToList();

            // run lava on each campus
            string dropdownItemTemplate = GetAttributeValue("CampusDropdownItemTemplate");

            if (!string.IsNullOrWhiteSpace(dropdownItemTemplate))
            {
                foreach (var campus in campusList)
                {
                    var mergeObjects = new Dictionary <string, object>();
                    mergeObjects.Add("CampusName", campus.Name);
                    campus.Name = dropdownItemTemplate.ResolveMergeFields(mergeObjects);
                }
            }

            // check if the campus can be unselected
            if (!string.IsNullOrEmpty(GetAttributeValue("CampusClearSelectionText")))
            {
                var blankCampus = new CampusItem
                {
                    Name = GetAttributeValue("CampusClearSelectionText"),
                    Id   = Rock.Constants.All.Id
                };

                campusList.Insert(0, blankCampus);
            }

            rptCampuses.DataSource = campusList;
            rptCampuses.DataBind();
        }
        /// <summary>
        /// Shows the read-only attribute values.
        /// </summary>
        protected void ShowDetails()
        {
            var loadAttributeValue = GetAttributeValue("LoadAttributeValue").AsBoolean(false);

            ltTitle.Text = GetAttributeValue("PanelHeading");
            btnSave.Text = GetAttributeValue("SaveButtonText");

            IHasAttributes entity = ContextEntity() as IHasAttributes;

            if (entity != null && CurrentPerson != null)
            {
                var rockContext = new RockContext();

                if (entity.Attributes == null)
                {
                    entity.LoadAttributes();
                }

                if (CurrentPerson.Attributes == null)
                {
                    CurrentPerson.LoadAttributes();
                }

                var sourceAttributeKey   = GetAttributeValue("SourceEntityAttributeKey");
                var sourceAttributeValue = entity.GetAttributeValue(sourceAttributeKey);
                var attributeService     = new AttributeService(rockContext);
                var targetAttribute      = attributeService.GetByGuids(new List <Guid>()
                {
                    sourceAttributeValue.AsGuid()
                }).ToList().FirstOrDefault();

                fsAttributes.Controls.Clear();

                string validationGroup = string.Format("vgAttributeValues_{0}", this.BlockId);
                btnSave.ValidationGroup = validationGroup;

                var    attribute      = AttributeCache.Get(targetAttribute);
                string attributeValue = CurrentPerson.GetAttributeValue(attribute.Key);
                string formattedValue = string.Empty;

                if (GetAttributeValue("CheckboxMode").AsBoolean(false))
                {
                    var      checkboxText = GetAttributeValue("CheckboxText");
                    CheckBox checkbox     = new CheckBox();
                    checkbox.ID   = "SimpleCheckBox";
                    checkbox.Text = String.IsNullOrWhiteSpace(checkboxText) ? attribute.Name : checkboxText;

                    if (GetAttributeValue("InstantSave").AsBoolean(false))
                    {
                        checkbox.AutoPostBack = true;

                        checkbox.CheckedChanged += new EventHandler(this.Check_Change);
                        btnSave.Visible          = false;
                    }

                    if (loadAttributeValue && !string.IsNullOrWhiteSpace(attributeValue) && attributeValue.AsBoolean(true))
                    {
                        checkbox.Checked = true;
                    }

                    fsAttributes.Controls.Add(checkbox);
                }
                else
                {
                    attribute.AddControl(fsAttributes.Controls, attributeValue, validationGroup, loadAttributeValue, true);
                }

                pnlDetails.Visible = true;
            }
        }
        public ActionResult UpdateDelineationGeometry(UpdateDelineationGeometryViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                var viewData = new UpdateDelineationGeometryViewData(CurrentPerson, null, null, CurrentPerson.GetStormwaterJurisdictionsPersonCanView());
                return(RazorPartialView <UpdateDelineationGeometryErrors, UpdateDelineationGeometryViewData, UpdateDelineationGeometryViewModel>(viewData, viewModel));
            }

            viewModel.UpdateModel(CurrentPerson);

            var stormwaterJurisdictionID = viewModel.StormwaterJurisdictionID.GetValueOrDefault();
            var treatmentBMPAKs          = HttpRequestStorage.DatabaseEntities.DelineationStagings.Select(x => new { x.TreatmentBMPName, StormwaterJurisdictionID = stormwaterJurisdictionID });

            var treatmentBMPsWithUpstreamBMPAlreadySet = HttpRequestStorage.DatabaseEntities.TreatmentBMPs.Where(x =>
                                                                                                                 treatmentBMPAKs.Contains(new { x.TreatmentBMPName, x.StormwaterJurisdictionID })).Where(x => x.UpstreamBMPID != null);

            if (treatmentBMPsWithUpstreamBMPAlreadySet.Any())
            {
                var namesOfInvalidBMPs = treatmentBMPsWithUpstreamBMPAlreadySet.Select(x => x.TreatmentBMPName);

                namesOfInvalidBMPs.ToList().ForEach(x =>
                {
                    ModelState.AddModelError("Upstream BMP", $"Treatment BMP:{x} has an Upstream BMP and cannot accept delineations. Please either remove this Treatment BMP from your file or remove the Upstream BMP from the Treatment BMP and try again.");
                });
                var viewData = new UpdateDelineationGeometryViewData(CurrentPerson, null, null, CurrentPerson.GetStormwaterJurisdictionsPersonCanView());
                return(RazorPartialView <UpdateDelineationGeometryErrors, UpdateDelineationGeometryViewData,
                                         UpdateDelineationGeometryViewModel>(viewData, viewModel));
            }

            return(RedirectToAction(new SitkaRoute <DelineationUploadController>(c => c.ApproveDelineationGisUpload())));
        }
        protected void SaveDetails()
        {
            var      checkValue = false;
            CheckBox check      = ( CheckBox )fsAttributes.FindControl("SimpleCheckBox");

            if (check != null && check.Checked)
            {
                checkValue = true;
            }

            IHasAttributes entity = ContextEntity() as IHasAttributes;

            var rockContext          = new RockContext();
            var sourceAttributeKey   = GetAttributeValue("SourceEntityAttributeKey");
            var sourceAttributeValue = entity.GetAttributeValue(sourceAttributeKey);
            var attributeService     = new AttributeService(rockContext);
            var targetAttribute      = attributeService.GetByGuids(new List <Guid>()
            {
                sourceAttributeValue.AsGuid()
            }).ToList().FirstOrDefault();

            int personEntityTypeId = EntityTypeCache.Get(typeof(Person)).Id;

            var changes = new History.HistoryChangeList();

            var attribute = AttributeCache.Get(targetAttribute);

            if (CurrentPerson != null)
            {
                Control attributeControl = fsAttributes.FindControl(string.Format("attribute_field_{0}", attribute.Id));
                if (GetAttributeValue("CheckboxMode").AsBoolean(false) || attributeControl != null)
                {
                    string originalValue = CurrentPerson.GetAttributeValue(attribute.Key);
                    string newValue      = string.Empty;

                    if (GetAttributeValue("CheckboxMode").AsBoolean(false))
                    {
                        var valueMode = GetAttributeValue("CheckboxAttributeValueMode");
                        if (valueMode == "Date")
                        {
                            if (checkValue)
                            {
                                newValue = RockDateTime.Now.ToString();
                            }
                            else
                            {
                                newValue = string.Empty;
                            }
                        }
                        else if (valueMode == "Boolean")
                        {
                            if (checkValue)
                            {
                                newValue = "True";
                            }
                            else
                            {
                                newValue = "False";
                            }
                        }
                    }
                    else
                    {
                        newValue = attribute.FieldType.Field.GetEditValue(attributeControl, attribute.QualifierValues);
                    }

                    Rock.Attribute.Helper.SaveAttributeValue(CurrentPerson, attribute, newValue, rockContext);

                    // Check for changes to write to history
                    if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim())
                    {
                        string formattedOriginalValue = string.Empty;
                        if (!string.IsNullOrWhiteSpace(originalValue))
                        {
                            formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false);
                        }

                        string formattedNewValue = string.Empty;
                        if (!string.IsNullOrWhiteSpace(newValue))
                        {
                            formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false);
                        }

                        History.EvaluateChange(changes, attribute.Name, formattedOriginalValue, formattedNewValue, attribute.FieldType.Field.IsSensitive());
                    }
                }
            }

            if (changes.Any())
            {
                HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                           CurrentPerson.Id, changes);
            }

            string linkedPage = GetAttributeValue("RedirectPage");

            if (string.IsNullOrWhiteSpace(linkedPage))
            {
                ShowDetails();
            }
            else
            {
                var pageParams = new Dictionary <string, string>();
                pageParams.Add("av", "updated");
                var pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                Response.Redirect(pageReference.BuildUrl(), false);
            }
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            RockPage.AddCSSLink(ResolveRockUrl("~/Styles/fluidbox.css"));
            RockPage.AddScriptLink(ResolveRockUrl("~/Scripts/imagesloaded.min.js"));
            RockPage.AddScriptLink(ResolveRockUrl("~/Scripts/jquery.fluidbox.min.js"));

            if (CurrentPerson != null)
            {
                lName.Text = CurrentPerson.FullName;

                // Setup Image
                var imgTag = new LiteralControl(Rock.Model.Person.GetPersonPhotoImageTag(CurrentPerson, 188, 188));
                if (CurrentPerson.PhotoId.HasValue)
                {
                    var imgLink = new HyperLink();
                    imgLink.Attributes.Add("href", CurrentPerson.PhotoUrl);
                    phImage.Controls.Add(imgLink);
                    imgLink.Controls.Add(imgTag);
                }
                else
                {
                    phImage.Controls.Add(imgTag);
                }

                if (CurrentPerson.BirthDate.HasValue)
                {
                    var    dtf = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
                    string mdp = dtf.ShortDatePattern;
                    mdp = mdp.Replace(dtf.DateSeparator + "yyyy", "").Replace("yyyy" + dtf.DateSeparator, "");

                    string ageText = (CurrentPerson.BirthYear.HasValue && CurrentPerson.BirthYear != DateTime.MinValue.Year) ?
                                     string.Format("{0} yrs old ", CurrentPerson.BirthDate.Value.Age()) : string.Empty;
                    lAge.Text = string.Format("{0}<small>({1})</small><br/>", ageText, CurrentPerson.BirthDate.Value.ToMonthDayString());
                }

                lGender.Text = CurrentPerson.Gender != Gender.Unknown ? CurrentPerson.Gender.ToString() : string.Empty;

                if (CurrentPerson.PhoneNumbers != null)
                {
                    rptPhones.DataSource = CurrentPerson.PhoneNumbers.ToList();
                    rptPhones.DataBind();
                }

                lEmail.Text = CurrentPerson.Email;

                Guid?locationTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull();
                if (locationTypeGuid.HasValue)
                {
                    var addressTypeDv = DefinedValueCache.Read(locationTypeGuid.Value);

                    var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();

                    if (familyGroupTypeGuid.HasValue)
                    {
                        var familyGroupType = GroupTypeCache.Read(familyGroupTypeGuid.Value);

                        RockContext rockContext = new RockContext();
                        var         address     = new GroupLocationService(rockContext).Queryable()
                                                  .Where(l => l.Group.GroupTypeId == familyGroupType.Id &&
                                                         l.GroupLocationTypeValueId == addressTypeDv.Id &&
                                                         l.Group.Members.Any(m => m.PersonId == CurrentPerson.Id))
                                                  .Select(l => l.Location)
                                                  .FirstOrDefault();
                        if (address != null)
                        {
                            lAddress.Text = string.Format("<div class='margin-b-md'><small>{0} Address</small><br />{1}</div>", addressTypeDv.Value, address.FormattedHtmlAddress);
                        }
                    }
                }

                if (GetAttributeValue("ShowHomeAddress").AsBoolean())
                {
                    var homeAddress = CurrentPerson.GetHomeLocation();
                    if (homeAddress != null)
                    {
                    }
                }
            }
            else
            {
                pnlView.Visible         = false;
                nbNotAuthorized.Visible = true;
            }
        }
示例#29
0
 void DeleteExecute(object obj)
 {
     CurrentPerson.DeletePerson();
     PersonList.Remove(CurrentPerson);
 }