/// <summary> /// Registers the java script. /// </summary> protected virtual void RegisterJavaScript() { string mapStyle = "null"; string markerColor = ""; try { DefinedValueCache dvcMapStyle = DefinedValueCache.Get(this.MapStyleValueGuid); if (dvcMapStyle != null) { mapStyle = dvcMapStyle.GetAttributeValue("DynamicMapStyle"); var colors = dvcMapStyle.GetAttributeValue("Colors").Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (colors.Any()) { markerColor = colors.First().Replace("#", ""); } } } catch { } // oh well... string options = string.Format("controlId: '{0}', drawingMode: '{1}', strokeColor: '{2}', fillColor: '{2}', mapStyle: {3}", this.ClientID, this.DrawingMode, markerColor, mapStyle); DbGeography centerPoint = CenterPoint; if (centerPoint != null && centerPoint.Latitude != null && centerPoint.Longitude != null) { options += string.Format(", centerLatitude: '{0}', centerLongitude: '{1}'", centerPoint.Latitude, centerPoint.Longitude); } else { // If no centerpoint was defined, try to get it from organization address var globalAttributes = GlobalAttributesCache.Get(); Guid guid = globalAttributes.GetValue("OrganizationAddress").AsGuid(); if (!guid.Equals(Guid.Empty)) { var location = new Rock.Model.LocationService(new Rock.Data.RockContext()).Get(guid); if (location != null && location.GeoPoint != null && location.GeoPoint.Latitude != null && location.GeoPoint.Longitude != null) { CenterPoint = location.GeoPoint; options += string.Format(", centerLatitude: '{0}', centerLongitude: '{1}'", location.GeoPoint.Latitude, location.GeoPoint.Longitude); } } } string script = string.Format(@" // if the geoPicker was rendered, initialize it if ($('#{1}').length > 0) {{ Rock.controls.geoPicker.initialize({{ {0} }}); }} ", options, this.ClientID); ScriptManager.RegisterStartupScript(this, this.GetType(), "geo_picker-" + this.ClientID, script, true); }
/// <summary> /// Creates a new communication. /// </summary> /// <param name="fromPerson">From person.</param> /// <param name="messageKey">The message key.</param> /// <param name="toPersonAliasId">To person alias identifier.</param> /// <param name="message">The message to send.</param> /// <param name="plainMessage">The plain message.</param> /// <param name="rockSmsFromPhoneDv">From phone.</param> /// <param name="responseCode">The reponseCode to use for tracking the conversation.</param> /// <param name="rockContext">A context to use for database calls.</param> /// <param name="errorMessage">The error message.</param> /// <param name="attachments">The attachments.</param> private void CreateCommunication(Person fromPerson, string messageKey, int?toPersonAliasId, string message, string plainMessage, DefinedValueCache rockSmsFromPhoneDv, string responseCode, Rock.Data.RockContext rockContext, out string errorMessage, List <BinaryFile> attachments = null) { errorMessage = string.Empty; try { LaunchWorkflow(fromPerson?.PrimaryAliasId, messageKey, message, toPersonAliasId, rockSmsFromPhoneDv); } catch (Exception ex) { errorMessage = ex.Message; // Log error and continue, don't stop because the workflow failed. ExceptionLogService.LogException(ex); } // See if this should go to a phone or to the DB. Default is to the phone so if for some reason we get a null here then just send it to the phone. var enableResponseRecipientForwarding = rockSmsFromPhoneDv.GetAttributeValue("EnableResponseRecipientForwarding").AsBooleanOrNull() ?? true; // NOTE: FromPerson should never be null if (enableResponseRecipientForwarding) { CreateCommunicationMobile(fromPerson, toPersonAliasId, message, rockSmsFromPhoneDv, responseCode, rockContext, attachments); } CreateCommunicationResponse(fromPerson, messageKey, toPersonAliasId, plainMessage, rockSmsFromPhoneDv, responseCode, rockContext, attachments); }
/// <summary> /// Launches the workflow. /// </summary> /// <param name="fromPersonAliasId">From person alias identifier.</param> /// <param name="fromPhone">From phone.</param> /// <param name="message">The message.</param> /// <param name="toPersonAliasId">To person alias identifier.</param> /// <param name="rockSmsFromPhoneDv">The rock SMS from phone DefinedValue.</param> private void LaunchWorkflow(int?fromPersonAliasId, string fromPhone, string message, int?toPersonAliasId, DefinedValueCache rockSmsFromPhoneDv) { var workflowTypeGuid = rockSmsFromPhoneDv.GetAttributeValue("LaunchWorkflowOnResponseReceived"); var workflowType = WorkflowTypeCache.Get(workflowTypeGuid); if (workflowType == null || (workflowType.IsActive != true)) { return; } var personAliasService = new PersonAliasService(new RockContext()); var workflowAttributeValues = new Dictionary <string, string>(); workflowAttributeValues.Add("FromPhone", fromPhone); workflowAttributeValues.Add("Message", message); workflowAttributeValues.Add("SMSFromDefinedValue", rockSmsFromPhoneDv.Guid.ToString()); if (fromPersonAliasId != null) { workflowAttributeValues.Add("FromPerson", personAliasService.Get(fromPersonAliasId.Value).Guid.ToString() ?? string.Empty); } if (toPersonAliasId != null) { workflowAttributeValues.Add("ToPerson", personAliasService.Get(toPersonAliasId.Value).Guid.ToString() ?? string.Empty); } var launchWorkflowTransaction = new Rock.Transactions.LaunchWorkflowTransaction(workflowType.Id); launchWorkflowTransaction.WorkflowAttributeValues = workflowAttributeValues; launchWorkflowTransaction.Enqueue(); }
/// <summary> /// Get the background check type that the request is for. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="workflow">The Workflow initiating the request.</param> /// <param name="requestTypeAttribute">The request type attribute.</param> /// <param name="packageName"></param> /// <param name="errorMessages">The error messages.</param> /// <returns>True/False value of whether the request was successfully sent or not.</returns> private bool GetPackageName(RockContext rockContext, Model.Workflow workflow, AttributeCache requestTypeAttribute, out string packageName, List <string> errorMessages) { packageName = null; if (requestTypeAttribute == null) { errorMessages.Add("The 'Checkr' background check provider requires a background check type."); return(false); } DefinedValueCache pkgTypeDefinedValue = DefinedValueCache.Get(workflow.GetAttributeValue(requestTypeAttribute.Key).AsGuid()); if (pkgTypeDefinedValue == null) { errorMessages.Add("The 'Checkr' background check provider couldn't load background check type."); return(false); } if (pkgTypeDefinedValue.Attributes == null) { // shouldn't happen since pkgTypeDefinedValue is a ModelCache<,> type return(false); } packageName = pkgTypeDefinedValue.GetAttributeValue("PMMPackageName"); return(true); }
/// <summary> /// Shows the view. /// </summary> private void ShowView() { int?outputCacheDuration = GetAttributeValue("OutputCacheDuration").AsIntegerOrNull(); int?itemCacheDuration = GetAttributeValue("ItemCacheDuration").AsIntegerOrNull(); string outputContents = null; string outputCacheKey = OUTPUT_CACHE_KEY; if (outputCacheDuration.HasValue && outputCacheDuration.Value > 0) { outputContents = GetCacheItem(outputCacheKey) as string; } if (outputContents == null) { var contentChannelItems = GetContentChannelItems(ITEM_CACHE_KEY, itemCacheDuration); var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new Rock.Lava.CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false }); mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber()); mergeFields.Add("Items", contentChannelItems); mergeFields.Add("ContentChannel", this.GetContentChannel()); mergeFields.Add("CurrentPage", this.PageCache); DefinedValueCache contentComponentTemplate = null; var contentComponentTemplateValueGuid = this.GetAttributeValue("ContentComponentTemplate").AsGuidOrNull(); if (contentComponentTemplateValueGuid.HasValue) { contentComponentTemplate = DefinedValueCache.Get(contentComponentTemplateValueGuid.Value); } if (contentComponentTemplate == null) { return; } string lavaTemplate = contentComponentTemplate.GetAttributeValue("DisplayLava"); // run LavaMerge on lavaTemplate outputContents = lavaTemplate.ResolveMergeFields(mergeFields); // run LavaMerge again in case there is lava in the MergeFields if (outputContents.HasMergeFields()) { outputContents = outputContents.ResolveMergeFields(mergeFields); } if (outputCacheDuration.HasValue && outputCacheDuration.Value > 0) { string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty; AddCacheItem(outputCacheKey, outputContents, outputCacheDuration.Value, cacheTags); } } lContentOutput.Text = outputContents; }
/// <summary> /// Gets the first FinancialBatch matching the specified filter parameters, or creates a new FinancialBatch if one isn't found. /// </summary> /// <param name="namePrefix">The name prefix.</param> /// <param name="nameSuffix">The name suffix.</param> /// <param name="currencyType">Type of the currency.</param> /// <param name="creditCardType">Type of the credit card.</param> /// <param name="transactionDate">The transaction date.</param> /// <param name="batchTimeOffset">The batch time offset.</param> /// <param name="batches">The batches.</param> /// <param name="batchWeeklyDayOfWeek">If batching weekly, the day of the week the batch should begin</param> /// <returns></returns> public FinancialBatch Get(string namePrefix, string nameSuffix, DefinedValueCache currencyType, DefinedValueCache creditCardType, DateTime transactionDate, TimeSpan batchTimeOffset, DayOfWeek?batchWeeklyDayOfWeek, List <FinancialBatch> batches = null) { // Use the credit card type's batch name suffix, or if that doesn't exist, use the currency type value string ccSuffix = string.Empty; if (creditCardType != null) { ccSuffix = creditCardType.GetAttributeValue("BatchNameSuffix"); if (string.IsNullOrWhiteSpace(ccSuffix)) { ccSuffix = creditCardType.Value; } } if (string.IsNullOrWhiteSpace(ccSuffix) && currencyType != null) { ccSuffix = currencyType.Value; } string batchName = namePrefix.Trim() + (string.IsNullOrWhiteSpace(ccSuffix) ? "" : " " + ccSuffix) + nameSuffix; return(GetByNameAndDate(batchName, transactionDate, batchTimeOffset, batchWeeklyDayOfWeek, batches)); }
/// <summary> /// Gets the specified name prefix. /// </summary> /// <param name="namePrefix">The name prefix.</param> /// <param name="nameSuffix">The name suffix.</param> /// <param name="currencyType">Type of the currency.</param> /// <param name="creditCardType">Type of the credit card.</param> /// <param name="transactionDate">The transaction date.</param> /// <param name="batchTimeOffset">The batch time offset.</param> /// <param name="batches">The batches.</param> /// <returns></returns> public FinancialBatch Get( string namePrefix, string nameSuffix, DefinedValueCache currencyType, DefinedValueCache creditCardType, DateTime transactionDate, TimeSpan batchTimeOffset, List<FinancialBatch> batches = null ) { // Use the credit card type's batch name suffix, or if that doesn't exist, use the currency type value string ccSuffix = string.Empty; if (creditCardType != null ) { ccSuffix = creditCardType.GetAttributeValue( "BatchNameSuffix" ); if ( string.IsNullOrWhiteSpace( ccSuffix ) ) { ccSuffix = creditCardType.Value; } } if ( string.IsNullOrWhiteSpace( ccSuffix ) && currencyType != null ) { ccSuffix = currencyType.Value; } string batchName = namePrefix.Trim() + ( string.IsNullOrWhiteSpace( ccSuffix ) ? "" : " " + ccSuffix ) + nameSuffix; return GetByNameAndDate( batchName, transactionDate, batchTimeOffset, batches ); }
/// <summary> /// Sends a background request to Protect My Ministry /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="workflow">The Workflow initiating the request.</param> /// <param name="personAttribute">The person attribute.</param> /// <param name="ssnAttribute">The SSN attribute.</param> /// <param name="requestTypeAttribute">The request type attribute.</param> /// <param name="billingCodeAttribute">The billing code attribute.</param> /// <param name="errorMessages">The error messages.</param> /// <returns> /// True/False value of whether the request was successfully sent or not /// </returns> /// <exception cref="System.NotImplementedException"></exception> /// <remarks> /// Note: If the associated workflow type does not have attributes with the following keys, they /// will automatically be added to the workflow type configuration in order to store the results /// of the PMM background check request /// RequestStatus: The request status returned by PMM request /// RequestMessage: Any error messages returned by PMM request /// ReportStatus: The report status returned by PMM /// ReportLink: The location of the background report on PMM server /// ReportRecommendation: PMM's recomendataion /// Report (BinaryFile): The downloaded background report /// </remarks> public override bool SendRequest(RockContext rockContext, Model.Workflow workflow, AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute, AttributeCache billingCodeAttribute, out List <string> errorMessages) { errorMessages = new List <string>(); try { // Check to make sure workflow is not null if (workflow == null) { errorMessages.Add("The 'Protect My Ministry' background check provider requires a valid workflow."); return(false); } // Get the person that the request is for Person person = null; if (personAttribute != null) { Guid?personAliasGuid = workflow.GetAttributeValue(personAttribute.Key).AsGuidOrNull(); if (personAliasGuid.HasValue) { person = new PersonAliasService(rockContext).Queryable() .Where(p => p.Guid.Equals(personAliasGuid.Value)) .Select(p => p.Person) .FirstOrDefault(); person.LoadAttributes(rockContext); } } if (person == null) { errorMessages.Add("The 'Protect My Ministry' background check provider requires the workflow to have a 'Person' attribute that contains the person who the background check is for."); return(false); } string password = Encryption.DecryptString(GetAttributeValue("Password")); XElement rootElement = new XElement("OrderXML", new XElement("Method", "SEND ORDER"), new XElement("Authentication", new XElement("Username", GetAttributeValue("UserName")), new XElement("Password", password) ) ); if (GetAttributeValue("TestMode").AsBoolean()) { rootElement.Add(new XElement("TestMode", "YES")); } rootElement.Add(new XElement("ReturnResultURL", GetAttributeValue("ReturnURL"))); XElement orderElement = new XElement("Order"); rootElement.Add(orderElement); if (billingCodeAttribute != null) { string billingCode = workflow.GetAttributeValue(billingCodeAttribute.Key); Guid? campusGuid = billingCode.AsGuidOrNull(); if (campusGuid.HasValue) { var campus = CampusCache.Read(campusGuid.Value); if (campus != null) { billingCode = campus.Name; } } orderElement.Add(new XElement("BillingReferenceCode", billingCode)); } XElement subjectElement = new XElement("Subject", new XElement("FirstName", person.FirstName), new XElement("MiddleName", person.MiddleName), new XElement("LastName", person.LastName) ); orderElement.Add(subjectElement); if (person.SuffixValue != null) { subjectElement.Add(new XElement("Generation", person.SuffixValue.Value)); } if (person.BirthDate.HasValue) { subjectElement.Add(new XElement("DOB", person.BirthDate.Value.ToString("MM/dd/yyyy"))); } if (ssnAttribute != null) { string ssn = Encryption.DecryptString(workflow.GetAttributeValue(ssnAttribute.Key)).AsNumeric(); if (!string.IsNullOrWhiteSpace(ssn) && ssn.Length == 9) { subjectElement.Add(new XElement("SSN", ssn.Insert(5, "-").Insert(3, "-"))); } } if (person.Gender == Gender.Male) { subjectElement.Add(new XElement("Gender", "Male")); } if (person.Gender == Gender.Female) { subjectElement.Add(new XElement("Gender", "Female")); } string dlNumber = person.GetAttributeValue("com.sparkdevnetwork.DLNumber"); if (!string.IsNullOrWhiteSpace(dlNumber)) { subjectElement.Add(new XElement("DLNumber", dlNumber)); } if (!string.IsNullOrWhiteSpace(person.Email)) { subjectElement.Add(new XElement("EmailAddress", person.Email)); } var homelocation = person.GetHomeLocation(); if (homelocation != null) { subjectElement.Add(new XElement("CurrentAddress", new XElement("StreetAddress", homelocation.Street1), new XElement("City", homelocation.City), new XElement("State", homelocation.State), new XElement("Zipcode", homelocation.PostalCode) )); } XElement aliasesElement = new XElement("Aliases"); if (person.NickName != person.FirstName) { aliasesElement.Add(new XElement("Alias", new XElement("FirstName", person.NickName))); } foreach (var previousName in person.GetPreviousNames()) { aliasesElement.Add(new XElement("Alias", new XElement("LastName", previousName.LastName))); } if (aliasesElement.HasElements) { subjectElement.Add(aliasesElement); } DefinedValueCache pkgTypeDefinedValue = null; string packageName = "BASIC"; string county = string.Empty; string state = string.Empty; string mvrJurisdiction = string.Empty; string mvrState = string.Empty; if (requestTypeAttribute != null) { pkgTypeDefinedValue = DefinedValueCache.Read(workflow.GetAttributeValue(requestTypeAttribute.Key).AsGuid()); if (pkgTypeDefinedValue != null) { if (pkgTypeDefinedValue.Attributes == null) { pkgTypeDefinedValue.LoadAttributes(rockContext); } packageName = pkgTypeDefinedValue.GetAttributeValue("PMMPackageName"); county = pkgTypeDefinedValue.GetAttributeValue("DefaultCounty"); state = pkgTypeDefinedValue.GetAttributeValue("DefaultState"); Guid?mvrJurisdictionGuid = pkgTypeDefinedValue.GetAttributeValue("MVRJurisdiction").AsGuidOrNull(); if (mvrJurisdictionGuid.HasValue) { var mvrJurisdictionDv = DefinedValueCache.Read(mvrJurisdictionGuid.Value); if (mvrJurisdictionDv != null) { mvrJurisdiction = mvrJurisdictionDv.Value; if (mvrJurisdiction.Length >= 2) { mvrState = mvrJurisdiction.Left(2); } } } if (homelocation != null) { if (!string.IsNullOrWhiteSpace(homelocation.County) && pkgTypeDefinedValue.GetAttributeValue("SendHomeCounty").AsBoolean()) { county = homelocation.County; } if (!string.IsNullOrWhiteSpace(homelocation.State)) { if (pkgTypeDefinedValue.GetAttributeValue("SendHomeState").AsBoolean()) { state = homelocation.State; } if (pkgTypeDefinedValue.GetAttributeValue("SendHomeStateMVR").AsBoolean()) { mvrState = homelocation.State; } } } } } if (!string.IsNullOrWhiteSpace(packageName)) { orderElement.Add(new XElement("PackageServiceCode", packageName, new XAttribute("OrderId", workflow.Id.ToString()))); if (packageName.Trim().Equals("BASIC", StringComparison.OrdinalIgnoreCase) || packageName.Trim().Equals("PLUS", StringComparison.OrdinalIgnoreCase)) { orderElement.Add(new XElement("OrderDetail", new XAttribute("OrderId", workflow.Id.ToString()), new XAttribute("ServiceCode", "combo"))); } } if (!string.IsNullOrWhiteSpace(county) || !string.IsNullOrWhiteSpace(state)) { orderElement.Add(new XElement("OrderDetail", new XAttribute("OrderId", workflow.Id.ToString()), new XAttribute("ServiceCode", string.IsNullOrWhiteSpace(county) ? "StateCriminal" : "CountyCrim"), new XElement("County", county), new XElement("State", state), new XElement("YearsToSearch", 7), new XElement("CourtDocsRequested", "NO"), new XElement("RushRequested", "NO"), new XElement("SpecialInstructions", "")) ); } if (!string.IsNullOrWhiteSpace(mvrJurisdiction) && !string.IsNullOrWhiteSpace(mvrState)) { orderElement.Add(new XElement("OrderDetail", new XAttribute("OrderId", workflow.Id.ToString()), new XAttribute("ServiceCode", "MVR"), new XElement("JurisdictionCode", mvrJurisdiction), new XElement("State", mvrState)) ); } XDocument xdoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), rootElement); var requestDateTime = RockDateTime.Now; XDocument xResult = PostToWebService(xdoc, GetAttributeValue("RequestURL")); var responseDateTime = RockDateTime.Now; int?personAliasId = person.PrimaryAliasId; if (personAliasId.HasValue) { // Create a background check file using (var newRockContext = new RockContext()) { var backgroundCheckService = new BackgroundCheckService(newRockContext); var backgroundCheck = backgroundCheckService.Queryable() .Where(c => c.WorkflowId.HasValue && c.WorkflowId.Value == workflow.Id) .FirstOrDefault(); if (backgroundCheck == null) { backgroundCheck = new Rock.Model.BackgroundCheck(); backgroundCheck.PersonAliasId = personAliasId.Value; backgroundCheck.WorkflowId = workflow.Id; backgroundCheckService.Add(backgroundCheck); } backgroundCheck.RequestDate = RockDateTime.Now; // Clear any SSN nodes before saving XML to record foreach (var xSSNElement in xdoc.Descendants("SSN")) { xSSNElement.Value = "XXX-XX-XXXX"; } foreach (var xSSNElement in xResult.Descendants("SSN")) { xSSNElement.Value = "XXX-XX-XXXX"; } backgroundCheck.ResponseXml = string.Format(@" Request XML ({0}): ------------------------ {1} Response XML ({2}): ------------------------ {3} ", requestDateTime, xdoc.ToString(), responseDateTime, xResult.ToString()); newRockContext.SaveChanges(); } } using (var newRockContext = new RockContext()) { var handledErrorMessages = new List <string>(); bool createdNewAttribute = false; if (_HTTPStatusCode == HttpStatusCode.OK) { var xOrderXML = xResult.Elements("OrderXML").FirstOrDefault(); if (xOrderXML != null) { var xStatus = xOrderXML.Elements("Status").FirstOrDefault(); if (xStatus != null) { if (SaveAttributeValue(workflow, "RequestStatus", xStatus.Value, FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), newRockContext, null)) { createdNewAttribute = true; } } handledErrorMessages.AddRange(xOrderXML.Elements("Message").Select(x => x.Value).ToList()); var xErrors = xOrderXML.Elements("Errors").FirstOrDefault(); if (xErrors != null) { handledErrorMessages.AddRange(xOrderXML.Elements("Message").Select(x => x.Value).ToList()); } if (xResult.Root.Descendants().Count() > 0) { SaveResults(xResult, workflow, rockContext, false); } } } else { handledErrorMessages.Add("Invalid HttpStatusCode: " + _HTTPStatusCode.ToString()); } if (handledErrorMessages.Any()) { if (SaveAttributeValue(workflow, "RequestMessage", handledErrorMessages.AsDelimited(Environment.NewLine), FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), newRockContext, null)) { createdNewAttribute = true; } } newRockContext.SaveChanges(); if (createdNewAttribute) { AttributeCache.FlushEntityAttributes(); } return(true); } } catch (Exception ex) { ExceptionLogService.LogException(ex, null); errorMessages.Add(ex.Message); return(false); } }
/// <summary> /// Gets the specified name prefix. /// </summary> /// <param name="namePrefix">The name prefix.</param> /// <param name="currencyType">Type of the currency.</param> /// <param name="creditCardType">Type of the credit card.</param> /// <param name="transactionDate">The transaction date.</param> /// <param name="batchTimeOffset">The batch time offset.</param> /// <param name="batches">The batches.</param> /// <returns></returns> public FinancialBatch Get( string namePrefix, DefinedValueCache currencyType, DefinedValueCache creditCardType, DateTime transactionDate, TimeSpan batchTimeOffset, List<FinancialBatch> batches = null ) { // Use the credit card type's batch name suffix, or if that doesn't exist, use the currency type value string ccSuffix = string.Empty; if (creditCardType != null ) { ccSuffix = creditCardType.GetAttributeValue( "BatchNameSuffix" ); if ( string.IsNullOrWhiteSpace( ccSuffix ) ) { ccSuffix = creditCardType.Value; } } if ( string.IsNullOrWhiteSpace( ccSuffix ) && currencyType != null ) { ccSuffix = currencyType.Value; } string batchName = namePrefix.Trim() + ( string.IsNullOrWhiteSpace( ccSuffix ) ? "" : " " + ccSuffix ); FinancialBatch batch = null; // If a list of batches was passed, search those first if ( batches != null ) { batch = batches .Where( b => b.Status == BatchStatus.Open && b.BatchStartDateTime <= transactionDate && b.BatchEndDateTime > transactionDate && b.Name == batchName ) .OrderByDescending( b => b.BatchStartDateTime ) .FirstOrDefault(); if ( batch != null ) { return batch; } } // If batch was not found in existing list, search database batch = Queryable() .Where( b => b.Status == BatchStatus.Open && b.BatchStartDateTime <= transactionDate && b.BatchEndDateTime > transactionDate && b.Name == batchName ) .OrderByDescending( b => b.BatchStartDateTime ) .FirstOrDefault(); // If still no batch, create a new one if ( batch == null ) { batch = new FinancialBatch(); batch.Guid = Guid.NewGuid(); batch.Name = batchName; batch.Status = BatchStatus.Open; batch.BatchStartDateTime = transactionDate.Date.Add( batchTimeOffset ); if ( batch.BatchStartDateTime > transactionDate ) { batch.BatchStartDateTime.Value.AddDays( -1 ); } batch.BatchEndDateTime = batch.BatchStartDateTime.Value.AddDays( 1 ); batch.ControlAmount = 0; Add( batch ); } // Add the batch to the list if ( batches != null ) { batches.Add( batch ); } return batch; }
/// <summary> /// Shows the report. /// </summary> private void ShowMap() { string mapStylingFormat = @" <style> #map_wrapper {{ height: {0}px; }} #map_canvas {{ width: 100%; height: 100%; border-radius: var(--border-radius-base); }} </style>"; lMapStyling.Text = string.Format(mapStylingFormat, GetAttributeValue("MapHeight")); // add styling to map string styleCode = "null"; DefinedValueCache dvcMapStyle = DefinedValueCache.Get(GetAttributeValue("MapStyle").AsGuid()); if (dvcMapStyle != null) { styleCode = dvcMapStyle.GetAttributeValue("DynamicMapStyle"); } var polygonColorList = GetAttributeValue("PolygonColors").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); string polygonColors = polygonColorList.AsDelimited(","); string latitude = "39.8282"; string longitude = "-98.5795"; string zoom = "4"; var orgLocation = GlobalAttributesCache.Get().OrganizationLocation; if (orgLocation != null && orgLocation.GeoPoint != null) { latitude = orgLocation.GeoPoint.Latitude.Value.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US")); longitude = orgLocation.GeoPoint.Longitude.Value.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US")); zoom = "12"; } var rockContext = new RockContext(); var campuses = CampusCache.All(); var locationService = new LocationService(rockContext); CampusMarkersData = string.Empty; if (cbShowCampusLocations.Checked) { foreach (var campus in campuses) { if (campus.LocationId.HasValue) { var location = locationService.Get(campus.LocationId.Value); if (location != null && location.GeoPoint != null) { CampusMarkersData += string.Format("{{ location: new google.maps.LatLng({0},{1}), campusName:'{2}' }},", location.GeoPoint.Latitude, location.GeoPoint.Longitude, campus.Name); } } } CampusMarkersData.TrimEnd(new char[] { ',' }); } // show geofences if a group was specified this.GroupId = this.PageParameter("GroupId").AsIntegerOrNull(); if (!this.GroupId.HasValue && gpGroupToMap.Visible) { // if a page parameter wasn't specified, use the selected group from the filter this.GroupId = gpGroupToMap.SelectedValue.AsIntegerOrNull(); } var groupMemberService = new GroupMemberService(rockContext); var groupLocationTypeHome = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()); int groupLocationTypeHomeId = groupLocationTypeHome != null ? groupLocationTypeHome.Id : 0; var groupTypeFamily = GroupTypeCache.GetFamilyGroupType(); int groupTypeFamilyId = groupTypeFamily != null ? groupTypeFamily.Id : 0; // if there is a DataViewId page parameter, use that instead of the Block or Filter dataview setting (the filter control won't be visible if there is a DataViewId page parameter) int? dataViewId = this.PageParameter("DataViewId").AsIntegerOrNull(); Guid?dataViewGuid = null; if (!dataViewId.HasValue) { dataViewGuid = this.GetAttributeValue("DataView").AsGuidOrNull(); } if (ddlUserDataView.Visible) { dataViewGuid = ddlUserDataView.SelectedValue.AsGuidOrNull(); } IQueryable <int> qryPersonIds = null; if (dataViewId.HasValue || dataViewGuid.HasValue) { DataView dataView = null; // if a DataViewId page parameter was specified, use that, otherwise use the blocksetting or filter selection if (dataViewId.HasValue) { dataView = new DataViewService(rockContext).Get(dataViewId.Value); } else { dataView = new DataViewService(rockContext).Get(dataViewGuid.Value); } if (dataView != null) { List <string> errorMessages; qryPersonIds = dataView.GetQuery(null, rockContext, null, out errorMessages).OfType <Person>().Select(a => a.Id); } } if (qryPersonIds == null) { // if no dataview was specified, show nothing qryPersonIds = new PersonService(rockContext).Queryable().Where(a => false).Select(a => a.Id); } var qryGroupMembers = groupMemberService.Queryable(); var campusIds = cpCampuses.SelectedCampusIds; if (campusIds.Any()) { qryGroupMembers = qryGroupMembers.Where(a => a.Group.CampusId.HasValue && campusIds.Contains(a.Group.CampusId.Value)); } var qryLocationGroupMembers = qryGroupMembers .Where(a => a.Group.GroupTypeId == groupTypeFamilyId) .Where(a => a.Group.IsActive) .Select(a => new { GroupGeoPoint = a.Group.GroupLocations.Where(gl => gl.IsMappedLocation && gl.GroupLocationTypeValueId == groupLocationTypeHomeId && gl.Location.IsActive && gl.Location.GeoPoint != null).Select(x => x.Location.GeoPoint).FirstOrDefault(), a.Group.CampusId, a.PersonId }) .Where(a => (a.GroupGeoPoint != null) && qryPersonIds.Contains(a.PersonId)) .GroupBy(a => new { a.GroupGeoPoint.Latitude, a.GroupGeoPoint.Longitude }) .Select(s => new { s.Key.Longitude, s.Key.Latitude, MemberCount = s.Count() }); var locationList = qryLocationGroupMembers.ToList() .Select(a => new LatLongWeighted(a.Latitude.Value, a.Longitude.Value, a.MemberCount)) .ToList(); List <LatLongWeighted> points = locationList; // cluster points that are close together double?milesPerGrouping = this.GetAttributeValue("PointGrouping").AsDoubleOrNull(); if (!milesPerGrouping.HasValue) { // default to a 1/10th of a mile milesPerGrouping = 0.10; } if (milesPerGrouping.HasValue && milesPerGrouping > 0) { var metersPerLatitudePHX = 110886.79; var metersPerLongitudePHX = 94493.11; double metersPerMile = 1609.34; var squareLengthHeightMeters = metersPerMile * milesPerGrouping.Value; var longitudeRoundFactor = metersPerLongitudePHX / squareLengthHeightMeters; var latitudeRoundFactor = metersPerLatitudePHX / squareLengthHeightMeters; points = points.GroupBy(a => new { rLat = Math.Round(a.Lat * latitudeRoundFactor), rLong = Math.Round(a.Lat * longitudeRoundFactor), }).Select(a => new LatLongWeighted(a.Average(x => x.Lat), a.Average(x => x.Long), a.Sum(x => x.Weight))).ToList(); } this.HeatMapData = points.Select(a => a.Weight > 1 ? string.Format("{{location: new google.maps.LatLng({0}, {1}), weight: {2}}}", a.Lat, a.Long, a.Weight) : string.Format("new google.maps.LatLng({0}, {1})", a.Lat, a.Long)).ToList().AsDelimited(",\n"); StyleCode = styleCode; hfPolygonColors.Value = polygonColors; hfCenterLatitude.Value = latitude.ToString(); hfCenterLongitude.Value = longitude.ToString(); hfZoom.Value = zoom.ToString(); }
public override bool SendRequest(RockContext rockContext, Workflow workflow, AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute, AttributeCache billingCodeAttribute, out List <string> errorMessages) { errorMessages = new List <string>(); rockContext.SaveChanges(); // Check to make sure workflow is not null if (workflow == null || workflow.Id == 0) { errorMessages.Add("The 'Protect My Ministry' background check provider requires a valid persisted workflow."); return(false); } workflow.LoadAttributes(); // Get the person that the request is for Person person = null; if (personAttribute != null) { Guid?personAliasGuid = workflow.GetAttributeValue(personAttribute.Key).AsGuidOrNull(); if (personAliasGuid.HasValue) { person = new PersonAliasService(rockContext).Queryable() .Where(p => p.Guid.Equals(personAliasGuid.Value)) .Select(p => p.Person) .FirstOrDefault(); person.LoadAttributes(rockContext); } } if (person == null) { errorMessages.Add("The 'Protect My Ministry' background check provider requires the workflow to have a 'Person' attribute that contains the person who the background check is for."); return(false); } string billingCode = workflow.GetAttributeValue(billingCodeAttribute.Key); Guid? campusGuid = billingCode.AsGuidOrNull(); if (campusGuid.HasValue) { var campus = CampusCache.Read(campusGuid.Value); if (campus != null) { billingCode = campus.Name; } } string ssn = Encryption.DecryptString(workflow.GetAttributeValue(ssnAttribute.Key)); DefinedValueCache requestType = DefinedValueCache.Read(workflow.GetAttributeValue(requestTypeAttribute.Key).AsGuid()); if (requestType == null) { errorMessages.Add("Unknown request type."); return(false); } int orderId = workflow.Id; string requestTypePackageName = requestType.GetAttributeValue("PMMPackageName").Trim(); BackgroundCheck bgCheck = getBgCheck(rockContext, workflow, person.PrimaryAliasId.Value); List <string[]> SSNTraceCounties = null; if (requestTypePackageName.Equals("PLUS", StringComparison.OrdinalIgnoreCase) && !String.IsNullOrWhiteSpace(bgCheck.ResponseXml)) { IEnumerable <XElement> transactions = XDocument.Parse(bgCheck.ResponseXml).Root.Elements("Transaction"); IEnumerable <XElement> OrderXMLs = transactions.SelectMany(x => x.Elements("OrderXML")); IEnumerable <XElement> Orders = OrderXMLs.Select(x => x.Element("Order")).Where(x => x != null); IEnumerable <XElement> OrderDetails = Orders.SelectMany(x => x.Elements("OrderDetail")); IEnumerable <XElement> SSNTraces = OrderDetails.Where(x => x.Attribute("ServiceCode")?.Value == "SSNTrace" && x.Element("Status") != null); IEnumerable <XElement> SSNTraceResults = SSNTraces.Select(x => x.Element("Result")); IEnumerable <XElement> SSNTraceIndividuals = SSNTraceResults.SelectMany(x => x.Elements("Individual")); IEnumerable <XElement> SSNTraceIndividualsToSearch = SSNTraceIndividuals.Where(x => x.Element("EndDate") == null || x.Element("EndDate").Element("Year") == null || (x.Element("EndDate").Element("Year").Value.AsInteger() > (DateTime.Now.Year - 8))); SSNTraceCounties = SSNTraceIndividualsToSearch.Where(x => x.Element("County") != null && x.Element("State") != null).Select(x => new string[] { x.Element("County").Value, x.Element("State").Value }).ToList(); } XElement xTransaction = makeBGRequest(bgCheck, ssn, requestType, billingCode, SSNTraceCounties); saveTransaction(rockContext, bgCheck, xTransaction); handleTransaction(rockContext, bgCheck, xTransaction); return(true); //catch (Exception ex) //{ // ExceptionLogService.LogException(ex, null); // errorMessages.Add(ex.Message); // return false; //} }
public void ProcessRequest(HttpContext context) { request = context.Request; response = context.Response; RockContext rockContext = new RockContext(); if (request.HttpMethod != "GET" && request.HttpMethod != "HEAD") { response.TrySkipIisCustomErrors = true; response.StatusCode = 405; response.Headers.Add("Allow", "GET"); response.Write("Invalid request method."); return; } if (request.QueryString["ChannelId"] == null) { response.TrySkipIisCustomErrors = true; response.StatusCode = 400; response.Write("A ChannelId is required."); return; } int?channelId = request.QueryString["ChannelId"].AsIntegerOrNull(); if (channelId == null) { response.TrySkipIisCustomErrors = true; response.StatusCode = 400; response.Write("Invalid channel id."); return; } ContentChannel channel = new ContentChannelService(rockContext).Queryable("ContentChannelType").FirstOrDefault(c => c.Id == channelId.Value); if (channel == null) { response.TrySkipIisCustomErrors = true; response.StatusCode = 404; response.Write("Channel does not exist."); return; } if (!channel.EnableRss) { response.TrySkipIisCustomErrors = true; response.StatusCode = 403; response.Write("RSS is not enabled for this channel."); return; } DefinedValueCache dvRssTemplate = null; if (request.QueryString["TemplateId"] != null) { int?templateDefinedValueId = request.QueryString["TemplateId"].AsIntegerOrNull(); if (templateDefinedValueId == null) { response.TrySkipIisCustomErrors = true; response.StatusCode = 400; response.Write("Invalid template id."); return; } dvRssTemplate = DefinedValueCache.Get(templateDefinedValueId.Value); } if (dvRssTemplate == null) { dvRssTemplate = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.DEFAULT_RSS_CHANNEL); } if (dvRssTemplate.DefinedType.Guid != new Guid(Rock.SystemGuid.DefinedType.LAVA_TEMPLATES)) { response.TrySkipIisCustomErrors = true; response.StatusCode = 400; response.Write("Invalid template id."); return; } string rssTemplate = dvRssTemplate.GetAttributeValue("Template"); if (string.IsNullOrWhiteSpace(dvRssTemplate.GetAttributeValue("MimeType"))) { response.ContentType = "application/rss+xml"; } else { response.ContentType = dvRssTemplate.GetAttributeValue("MimeType"); } if (request.HttpMethod == "HEAD") { response.StatusCode = 200; return; } // load merge fields var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("Channel", channel); Dictionary <string, object> requestObjects = new Dictionary <string, object>(); requestObjects.Add("Scheme", request.Url.Scheme); requestObjects.Add("Host", WebRequestHelper.GetHostNameFromRequest(context)); requestObjects.Add("Authority", request.Url.Authority); requestObjects.Add("LocalPath", request.Url.LocalPath); requestObjects.Add("AbsoluteUri", request.Url.AbsoluteUri); requestObjects.Add("AbsolutePath", request.Url.AbsolutePath); requestObjects.Add("Port", request.Url.Port); requestObjects.Add("Query", request.Url.Query); requestObjects.Add("OriginalString", request.Url.OriginalString); mergeFields.Add("Request", requestObjects); // check for new rss item limit if (request.QueryString["Count"] != null) { int.TryParse(request.QueryString["Count"], out rssItemLimit); } // get channel items ContentChannelItemService contentService = new ContentChannelItemService(rockContext); var content = contentService.Queryable("ContentChannelType") .Where(c => c.ContentChannelId == channel.Id && (c.Status == ContentChannelItemStatus.Approved || c.ContentChannel.ContentChannelType.DisableStatus || c.ContentChannel.RequiresApproval == false) && c.StartDateTime <= RockDateTime.Now); if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange) { if (channel.ContentChannelType.IncludeTime) { content = content.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime >= RockDateTime.Now); } else { content = content.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime > RockDateTime.Today); } } if (channel.ItemsManuallyOrdered) { content = content.OrderBy(c => c.Order); } else { content = content.OrderByDescending(c => c.StartDateTime); } content = content.Take(rssItemLimit); content.LoadAttributes(); foreach (var item in content) { item.Content = item.Content.ResolveMergeFields(mergeFields); // resolve any relative links var globalAttributes = GlobalAttributesCache.Get(); string publicAppRoot = globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash(); item.Content = item.Content.Replace(@" src=""/", @" src=""" + publicAppRoot); item.Content = item.Content.Replace(@" href=""/", @" href=""" + publicAppRoot); // get item attributes and add them as elements to the feed foreach (var attributeValue in item.AttributeValues) { attributeValue.Value.Value = attributeValue.Value.Value.ResolveMergeFields(mergeFields); } } mergeFields.Add("Items", content); mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber()); response.Write(rssTemplate.ResolveMergeFields(mergeFields)); }
private void Map() { string mapStylingFormat = @" <style> #map_wrapper {{ height: {0}px; }} #map_canvas {{ width: 100%; height: 100%; border-radius: var(--border-radius-base); }} </style>"; lMapStyling.Text = string.Format(mapStylingFormat, GetAttributeValue("MapHeight")); string settingGroupTypeId = GetAttributeValue("GroupType"); string queryStringGroupTypeId = PageParameter("GroupTypeId"); if ((string.IsNullOrWhiteSpace(settingGroupTypeId) && string.IsNullOrWhiteSpace(queryStringGroupTypeId))) { pnlMap.Visible = false; lMessages.Text = "<div class='alert alert-warning'><strong>Group Mapper</strong> Please configure a group type to display as a block setting or pass a GroupTypeId as a query parameter.</div>"; } else { var rockContext = new RockContext(); pnlMap.Visible = true; int groupsMapped = 0; int groupsWithNoGeo = 0; StringBuilder sbGroupJson = new StringBuilder(); StringBuilder sbGroupsWithNoGeo = new StringBuilder(); Guid?groupType = null; int groupTypeId = -1; if (!string.IsNullOrWhiteSpace(settingGroupTypeId)) { groupType = new Guid(settingGroupTypeId); } else { if (!string.IsNullOrWhiteSpace(queryStringGroupTypeId) && Int32.TryParse(queryStringGroupTypeId, out groupTypeId)) { groupType = new GroupTypeService(rockContext).Get(groupTypeId).Guid; } } if (groupType != null) { Template template = null; ILavaTemplate lavaTemplate = null; if (LavaService.RockLiquidIsEnabled) { if (GetAttributeValue("ShowMapInfoWindow").AsBoolean()) { template = Template.Parse(GetAttributeValue("InfoWindowContents").Trim()); LavaHelper.VerifyParseTemplateForCurrentEngine(GetAttributeValue("InfoWindowContents").Trim()); } else { template = Template.Parse(string.Empty); } } else { string templateContent; if (GetAttributeValue("ShowMapInfoWindow").AsBoolean()) { templateContent = GetAttributeValue("InfoWindowContents").Trim(); } else { templateContent = string.Empty; } var parseResult = LavaService.ParseTemplate(templateContent); lavaTemplate = parseResult.Template; } var groupPageRef = new PageReference(GetAttributeValue("GroupDetailPage")); // create group detail link for use in map's info window var personPageParams = new Dictionary <string, string>(); personPageParams.Add("PersonId", string.Empty); var personProfilePage = LinkedPageUrl("PersonProfilePage", personPageParams); var groupEntityType = EntityTypeCache.Get(typeof(Group)); var dynamicGroups = new List <dynamic>(); // Create query to get attribute values for selected attribute keys. var attributeKeys = GetAttributeValue("Attributes").SplitDelimitedValues().ToList(); var attributeValues = new AttributeValueService(rockContext).Queryable("Attribute") .Where(v => v.Attribute.EntityTypeId == groupEntityType.Id && attributeKeys.Contains(v.Attribute.Key)); GroupService groupService = new GroupService(rockContext); var groups = groupService.Queryable() .Where(g => g.GroupType.Guid == groupType) .Select(g => new { Group = g, GroupId = g.Id, GroupName = g.Name, GroupGuid = g.Guid, GroupMemberTerm = g.GroupType.GroupMemberTerm, GroupCampus = g.Campus.Name, IsActive = g.IsActive, GroupLocation = g.GroupLocations .Where(l => l.Location.GeoPoint != null) .Select(l => new { l.Location.Street1, l.Location.Street2, l.Location.City, l.Location.State, PostalCode = l.Location.PostalCode, Latitude = l.Location.GeoPoint.Latitude, Longitude = l.Location.GeoPoint.Longitude, Name = l.GroupLocationTypeValue.Value }).FirstOrDefault(), GroupMembers = g.Members, AttributeValues = attributeValues .Where(v => v.EntityId == g.Id) }); if (GetAttributeValue("IncludeInactiveGroups").AsBoolean() == false) { groups = groups.Where(g => g.IsActive == true); } // Create dynamic object to include attribute values foreach (var group in groups) { dynamic dynGroup = new ExpandoObject(); dynGroup.GroupId = group.GroupId; dynGroup.GroupName = group.GroupName; // create group detail link for use in map's info window if (groupPageRef.PageId > 0) { var groupPageParams = new Dictionary <string, string>(); groupPageParams.Add("GroupId", group.GroupId.ToString()); groupPageRef.Parameters = groupPageParams; dynGroup.GroupDetailPage = groupPageRef.BuildUrl(); } else { dynGroup.GroupDetailPage = string.Empty; } dynGroup.PersonProfilePage = personProfilePage; dynGroup.GroupMemberTerm = group.GroupMemberTerm; dynGroup.GroupCampus = group.GroupCampus; dynGroup.GroupLocation = group.GroupLocation; var groupAttributes = new List <dynamic>(); foreach (AttributeValue value in group.AttributeValues) { var attrCache = AttributeCache.Get(value.AttributeId); var dictAttribute = new Dictionary <string, object>(); dictAttribute.Add("Key", attrCache.Key); dictAttribute.Add("Name", attrCache.Name); if (attrCache != null) { dictAttribute.Add("Value", attrCache.FieldType.Field.FormatValueAsHtml(null, attrCache.EntityTypeId, group.GroupId, value.Value, attrCache.QualifierValues, false)); } else { dictAttribute.Add("Value", value.Value); } groupAttributes.Add(dictAttribute); } dynGroup.Attributes = groupAttributes; var groupMembers = new List <dynamic>(); foreach (GroupMember member in group.GroupMembers) { var dictMember = new Dictionary <string, object>(); dictMember.Add("Id", member.Person.Id); dictMember.Add("GuidP", member.Person.Guid); dictMember.Add("NickName", member.Person.NickName); dictMember.Add("LastName", member.Person.LastName); dictMember.Add("RoleName", member.GroupRole.Name); dictMember.Add("Email", member.Person.Email); dictMember.Add("PhotoGuid", member.Person.Photo != null ? member.Person.Photo.Guid : Guid.Empty); var phoneTypes = new List <dynamic>(); foreach (PhoneNumber p in member.Person.PhoneNumbers) { var dictPhoneNumber = new Dictionary <string, object>(); dictPhoneNumber.Add("Name", p.NumberTypeValue.Value); dictPhoneNumber.Add("Number", p.ToString()); phoneTypes.Add(dictPhoneNumber); } dictMember.Add("PhoneTypes", phoneTypes); groupMembers.Add(dictMember); } dynGroup.GroupMembers = groupMembers; dynamicGroups.Add(dynGroup); } foreach (var group in dynamicGroups) { if (group.GroupLocation != null && group.GroupLocation.Latitude != null) { groupsMapped++; var groupDict = group as IDictionary <string, object>; string infoWindow; if (LavaService.RockLiquidIsEnabled) { infoWindow = template.Render(Hash.FromDictionary(groupDict)).Replace("\n", string.Empty); } else { var result = LavaService.RenderTemplate(lavaTemplate, groupDict); infoWindow = result.Text; if (!result.HasErrors) { infoWindow = infoWindow.Replace("\n", string.Empty); } } sbGroupJson.Append(string.Format( @"{{ ""name"":""{0}"" , ""latitude"":""{1}"", ""longitude"":""{2}"", ""infowindow"":""{3}"" }},", HttpUtility.HtmlEncode(group.GroupName), group.GroupLocation.Latitude, group.GroupLocation.Longitude, HttpUtility.HtmlEncode(infoWindow))); } else { groupsWithNoGeo++; if (!string.IsNullOrWhiteSpace(group.GroupDetailPage)) { sbGroupsWithNoGeo.Append(string.Format(@"<li><a href='{0}'>{1}</a></li>", group.GroupDetailPage, group.GroupName)); } else { sbGroupsWithNoGeo.Append(string.Format(@"<li>{0}</li>", group.GroupName)); } } } string groupJson = sbGroupJson.ToString(); // remove last comma if (groupJson.Length > 0) { groupJson = groupJson.Substring(0, groupJson.Length - 1); } // add styling to map string styleCode = "null"; string markerColor = "FE7569"; DefinedValueCache dvcMapStyle = DefinedValueCache.Get(GetAttributeValue("MapStyle").AsGuid()); if (dvcMapStyle != null) { styleCode = dvcMapStyle.GetAttributeValue("DynamicMapStyle"); var colors = dvcMapStyle.GetAttributeValue("Colors").Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (colors.Any()) { markerColor = colors.First().Replace("#", ""); } } // write script to page string mapScriptFormat = @" <script> Sys.Application.add_load(function () {{ var groupData = JSON.parse('{{ ""groups"" : [ {0} ]}}'); var showInfoWindow = {1}; var mapStyle = {2}; var pinColor = '{3}'; var pinImage = {{ path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z', fillColor: '#' + pinColor, fillOpacity: 1, strokeColor: '#000', strokeWeight: 1, scale: 1, labelOrigin: new google.maps.Point(0,-28) }}; initializeMap(); function initializeMap() {{ console.log(mapStyle); var map; var bounds = new google.maps.LatLngBounds(); var mapOptions = {{ mapTypeId: 'roadmap', styles: mapStyle }}; // Display a map on the page map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); map.setTilt(45); // Display multiple markers on a map if (showInfoWindow) {{ var infoWindow = new google.maps.InfoWindow(), marker, i; }} // Loop through our array of markers & place each one on the map $.each(groupData.groups, function (i, group) {{ var position = new google.maps.LatLng(group.latitude, group.longitude); bounds.extend(position); marker = new google.maps.Marker({{ position: position, map: map, title: htmlDecode(group.name), icon: pinImage, label: String.fromCharCode(9679) }}); // Allow each marker to have an info window if (showInfoWindow) {{ google.maps.event.addListener(marker, 'click', (function (marker, i) {{ return function () {{ infoWindow.setContent(htmlDecode(groupData.groups[i].infowindow)); infoWindow.open(map, marker); }} }})(marker, i)); }} map.fitBounds(bounds); }}); // Override our map zoom level once our fitBounds function runs (Make sure it only runs once) var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {{ google.maps.event.removeListener(boundsListener); }}); }} function htmlDecode(input) {{ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? """" : e.childNodes[0].nodeValue; }} }}); </script>"; string mapScript = string.Format( mapScriptFormat, groupJson, GetAttributeValue("ShowMapInfoWindow").AsBoolean().ToString().ToLower(), styleCode, markerColor); ScriptManager.RegisterStartupScript(pnlMap, pnlMap.GetType(), "group-mapper-script", mapScript, false); if (groupsMapped == 0) { pnlMap.Visible = false; lMessages.Text = @" <p> <div class='alert alert-warning fade in'>No groups were able to be mapped. You may want to check your configuration.</div> </p>"; } else { // output any warnings if (groupsWithNoGeo > 0) { string messagesFormat = @" <p> <div class='alert alert-warning fade in'>Some groups could not be mapped. <button type='button' class='close' data-dismiss='alert' aria-hidden='true'><i class='fa fa-times'></i></button> <small><a data-toggle='collapse' data-parent='#accordion' href='#map-error-details'>Show Details</a></small> <div id='map-error-details' class='collapse'> <p class='margin-t-sm'> <strong>Groups That Could Not Be Mapped</strong> <ul> {0} </ul> </p> </div> </div> </p>"; lMessages.Text = string.Format(messagesFormat, sbGroupsWithNoGeo.ToString()); } } } else { pnlMap.Visible = false; lMessages.Text = "<div class='alert alert-warning'><strong>Group Mapper</strong> Please configure a group type to display and a location type to use.</div>"; } } }
public XDocument BuildRequest(string orderId, Person person, string ssn, DefinedValueCache requestType, string billingCode, List <String[]> counties = null) { XElement rootElement = new XElement("OrderXML", new XElement("Method", "SEND ORDER"), new XElement("Authentication", new XElement("Username", GetAttributeValue("UserName")), new XElement("Password", Encryption.DecryptString(GetAttributeValue("Password"))) ) ); if (GetAttributeValue("TestMode").AsBoolean()) { rootElement.Add(new XElement("TestMode", "YES")); } rootElement.Add(new XElement("ReturnResultURL", GetAttributeValue("ReturnURL"))); XElement orderElement = new XElement("Order"); rootElement.Add(orderElement); if (!String.IsNullOrWhiteSpace(billingCode)) { orderElement.Add(new XElement("BillingReferenceCode", billingCode)); } XElement subjectElement = new XElement("Subject", new XElement("FirstName", person.FirstName), new XElement("MiddleName", person.MiddleName), new XElement("LastName", person.LastName) ); orderElement.Add(subjectElement); if (person.SuffixValue != null) { subjectElement.Add(new XElement("Generation", person.SuffixValue.Value)); } if (person.BirthDate.HasValue) { subjectElement.Add(new XElement("DOB", person.BirthDate.Value.ToString("MM/dd/yyyy"))); } ssn = ssn.AsNumeric(); if (!String.IsNullOrWhiteSpace(ssn) && ssn.Length == 9) { subjectElement.Add(new XElement("SSN", ssn.Insert(5, "-").Insert(3, "-"))); } if (person.Gender == Gender.Male) { subjectElement.Add(new XElement("Gender", "Male")); } if (person.Gender == Gender.Female) { subjectElement.Add(new XElement("Gender", "Female")); } string dlNumber = person.GetAttributeValue("com.sparkdevnetwork.DLNumber"); if (!string.IsNullOrWhiteSpace(dlNumber)) { subjectElement.Add(new XElement("DLNumber", dlNumber)); } var homelocation = person.GetHomeLocation(); if (homelocation != null) { var addressStatesDefinedValues = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.LOCATION_ADDRESS_STATE.AsGuid()).DefinedValues; var mappedStateId = addressStatesDefinedValues.Where(x => x.Description.ToLower() == homelocation.State.ToLower()).Select(x => x.Value).FirstOrDefault(); if (mappedStateId != null) { homelocation.State = mappedStateId; } subjectElement.Add(new XElement("CurrentAddress", new XElement("StreetAddress", homelocation.Street1), new XElement("City", homelocation.City), new XElement("State", homelocation.State), new XElement("Zipcode", homelocation.PostalCode) )); } XElement aliasesElement = new XElement("Aliases"); if (person.NickName != person.FirstName) { aliasesElement.Add(new XElement("Alias", new XElement("FirstName", person.NickName))); } foreach (var previousName in person.GetPreviousNames()) { aliasesElement.Add(new XElement("Alias", new XElement("LastName", previousName.LastName))); } if (aliasesElement.HasElements) { subjectElement.Add(aliasesElement); } string packageName = requestType.GetAttributeValue("PMMPackageName"); string county = requestType.GetAttributeValue("DefaultCounty"); string state = requestType.GetAttributeValue("DefaultState"); string mvrJurisdiction = GetMVRJurisdiction(requestType.GetAttributeValue("MVRJurisdiction")); string mvrState = mvrJurisdiction.Left(2); if (homelocation != null) { if (String.IsNullOrWhiteSpace(homelocation.County) && requestType.GetAttributeValue("SendHomeCounty").AsBoolean()) { county = homelocation.County; } if (!String.IsNullOrWhiteSpace(homelocation.State)) { if (requestType.GetAttributeValue("SendHomeState").AsBoolean()) { state = homelocation.State; } if (requestType.GetAttributeValue("SendHomeStateMVR").AsBoolean()) { mvrState = homelocation.State; } } } if (!string.IsNullOrWhiteSpace(packageName) && !packageName.Trim().Equals("SSNTRACE", StringComparison.OrdinalIgnoreCase)) { orderElement.Add(new XElement("PackageServiceCode", requestType, new XAttribute("OrderId", orderId))); } if (packageName.Trim().Equals("BASIC", StringComparison.OrdinalIgnoreCase) || packageName.Trim().Equals("PLUS", StringComparison.OrdinalIgnoreCase)) { orderElement.Add(new XElement("OrderDetail", new XAttribute("OrderId", orderId), new XAttribute("ServiceCode", "combo"))); } if (packageName.Trim().Equals("SSNTRACE", StringComparison.OrdinalIgnoreCase)) { orderElement.Add(new XElement("OrderDetail", new XAttribute("OrderId", orderId), new XAttribute("ServiceCode", "SSNTrace"))); } if (counties == null) { counties = new List <String[]>(); } // Create a list of locations to check var locations = new List <BGLocation>(); // Add any passed in counties if (counties != null) { locations.AddRange(counties.Select(c => new BGLocation { County = c[0], State = c[1] })); } // Add their current or default location locations.Add(new BGLocation { County = county, State = state }); // Normalize locations and filter nulls and duplicates locations = locations.Select(l => normalizeLocation(l)).Where(l => l != null).Distinct(new BGLocationEquals()).ToList(); foreach (var location in locations) { orderElement.Add(new XElement("OrderDetail", new XAttribute("OrderId", orderId), new XAttribute("ServiceCode", "CountyCrim"), new XElement("County", location.County), new XElement("State", location.State), new XElement("YearsToSearch", 7), new XElement("CourtDocsRequested", "NO"), new XElement("RushRequested", "NO"), new XElement("SpecialInstructions", "")) ); } if (!string.IsNullOrWhiteSpace(mvrJurisdiction) && !string.IsNullOrWhiteSpace(mvrState)) { orderElement.Add(new XElement("OrderDetail", new XAttribute("OrderId", orderId), new XAttribute("ServiceCode", "MVR"), new XElement("JurisdictionCode", mvrJurisdiction), new XElement("State", mvrState)) ); } return(new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), rootElement)); }
private void Map() { int?groupId = PageParameter("GroupId").AsIntegerOrNull(); if (!groupId.HasValue) { pnlMap.Visible = false; lMessages.Text = "<div class='alert alert-warning'><strong>Group Map</strong> A Group ID is required to display the map.</div>"; return; } pnlMap.Visible = true; string mapStylingFormat = MAP_STYLING_FORMAT; lMapStyling.Text = string.Format(mapStylingFormat, GetAttributeValue("MapHeight")); // add styling to map string styleCode = "null"; var markerColors = new List <string>(); DefinedValueCache dvcMapStyle = DefinedValueCache.Get(GetAttributeValue("MapStyle").AsGuid()); if (dvcMapStyle != null) { styleCode = dvcMapStyle.GetAttributeValue("DynamicMapStyle"); markerColors = dvcMapStyle.GetAttributeValue("Colors") .Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries) .ToList(); markerColors.ForEach(c => c = c.Replace("#", string.Empty)); } if (!markerColors.Any()) { markerColors.Add("FE7569"); } _groupColor = markerColors[0].Replace("#", string.Empty); _childGroupColor = (markerColors.Count > 1 ? markerColors[1] : markerColors[0]).Replace("#", string.Empty); _memberColor = (markerColors.Count > 2 ? markerColors[2] : markerColors[0]).Replace("#", string.Empty); var polygonColorList = GetAttributeValue("PolygonColors").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); string polygonColors = "\"" + polygonColorList.AsDelimited("\", \"") + "\""; string template = HttpUtility.HtmlEncode(GetAttributeValue("InfoWindowContents").Replace(Environment.NewLine, string.Empty).Replace("\n", string.Empty)); string groupPage = GetAttributeValue("GroupPage"); string personProfilePage = GetAttributeValue("PersonProfilePage"); string mapPage = GetAttributeValue("MapPage"); string infoWindowJson = string.Format(@"{{ ""GroupPage"":""{0}"", ""PersonProfilePage"":""{1}"", ""MapPage"":""{2}"", ""Template"":""{3}"" }}", groupPage, personProfilePage, mapPage, template); string latitude = "39.8282"; string longitude = "-98.5795"; string zoom = "4"; var orgLocation = GlobalAttributesCache.Get().OrganizationLocation; if (orgLocation != null && orgLocation.GeoPoint != null) { latitude = orgLocation.GeoPoint.Latitude.ToString(); longitude = orgLocation.GeoPoint.Longitude.ToString(); zoom = "12"; } // write script to page string mapScriptFormat = MAP_SCRIPT_FORMAT_NAME; string mapScript = string.Format(mapScriptFormat, groupId.Value, // {0} styleCode, // {1} polygonColors, // {2} _groupColor, // {3} _childGroupColor, // {4} _memberColor, // {5} infoWindowJson, // {6} latitude, // {7} longitude, // {8} zoom, // {9} cbShowAllGroups.Checked.ToTrueFalse(), // {10} gtpGroupType.SelectedGroupTypeIds.AsDelimited(","), // {11} GroupMemberStatus.Active // {12} ); ScriptManager.RegisterStartupScript(pnlMap, pnlMap.GetType(), "group-map-script", mapScript, false); }
/// <summary> /// Gets the specified name prefix. /// </summary> /// <param name="namePrefix">The name prefix.</param> /// <param name="currencyType">Type of the currency.</param> /// <param name="creditCardType">Type of the credit card.</param> /// <param name="transactionDate">The transaction date.</param> /// <param name="batchTimeOffset">The batch time offset.</param> /// <param name="batches">The batches.</param> /// <returns></returns> public FinancialBatch Get(string namePrefix, DefinedValueCache currencyType, DefinedValueCache creditCardType, DateTime transactionDate, TimeSpan batchTimeOffset, List <FinancialBatch> batches = null) { // Use the credit card type's batch name suffix, or if that doesn't exist, use the currency type value string ccSuffix = string.Empty; if (creditCardType != null) { ccSuffix = creditCardType.GetAttributeValue("BatchNameSuffix"); if (string.IsNullOrWhiteSpace(ccSuffix)) { ccSuffix = creditCardType.Value; } } if (string.IsNullOrWhiteSpace(ccSuffix) && currencyType != null) { ccSuffix = currencyType.Value; } string batchName = namePrefix.Trim() + (string.IsNullOrWhiteSpace(ccSuffix) ? "" : " " + ccSuffix); FinancialBatch batch = null; // If a list of batches was passed, search those first if (batches != null) { batch = batches .Where(b => b.Status == BatchStatus.Open && b.BatchStartDateTime <= transactionDate && b.BatchEndDateTime > transactionDate && b.Name == batchName) .OrderByDescending(b => b.BatchStartDateTime) .FirstOrDefault(); if (batch != null) { return(batch); } } // If batch was not found in existing list, search database batch = Queryable() .Where(b => b.Status == BatchStatus.Open && b.BatchStartDateTime <= transactionDate && b.BatchEndDateTime > transactionDate && b.Name == batchName) .OrderByDescending(b => b.BatchStartDateTime) .FirstOrDefault(); // If still no batch, create a new one if (batch == null) { batch = new FinancialBatch(); batch.Guid = Guid.NewGuid(); batch.Name = batchName; batch.Status = BatchStatus.Open; var batchStartDateTime = transactionDate.Date.Add(batchTimeOffset); if (batchStartDateTime > transactionDate) { batchStartDateTime = batchStartDateTime.AddDays(-1); } batch.BatchStartDateTime = batchStartDateTime; batch.BatchEndDateTime = batchStartDateTime.AddDays(1); batch.ControlAmount = 0; Add(batch); } // Add the batch to the list if (batches != null) { batches.Add(batch); } return(batch); }
private void Map() { int?groupId = PageParameter("GroupId").AsIntegerOrNull(); if (!groupId.HasValue) { pnlMap.Visible = false; lMessages.Text = "<div class='alert alert-warning'><strong>Group Map</strong> A Group ID is required to display the map.</div>"; return; } pnlMap.Visible = true; string mapStylingFormat = @" <style> #map_wrapper {{ height: {0}px; }} #map_canvas {{ width: 100%; height: 100%; border-radius: 8px; }} </style>"; lMapStyling.Text = string.Format(mapStylingFormat, GetAttributeValue("MapHeight")); // add styling to map string styleCode = "null"; var markerColors = new List <string>(); DefinedValueCache dvcMapStyle = DefinedValueCache.Read(GetAttributeValue("MapStyle").AsGuid()); if (dvcMapStyle != null) { styleCode = dvcMapStyle.GetAttributeValue("DynamicMapStyle"); markerColors = dvcMapStyle.GetAttributeValue("Colors") .Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries) .ToList(); markerColors.ForEach(c => c = c.Replace("#", string.Empty)); } if (!markerColors.Any()) { markerColors.Add("FE7569"); } _groupColor = markerColors[0].Replace("#", string.Empty); _childGroupColor = (markerColors.Count > 1 ? markerColors[1] : markerColors[0]).Replace("#", string.Empty); _memberColor = (markerColors.Count > 2 ? markerColors[2] : markerColors[0]).Replace("#", string.Empty); var polygonColorList = GetAttributeValue("PolygonColors").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); string polygonColors = "\"" + polygonColorList.AsDelimited("\", \"") + "\""; string template = HttpUtility.HtmlEncode(GetAttributeValue("InfoWindowContents").Replace(Environment.NewLine, string.Empty).Replace("\n", string.Empty)); string groupPage = GetAttributeValue("GroupPage"); string personProfilePage = GetAttributeValue("PersonProfilePage"); string mapPage = GetAttributeValue("MapPage"); string infoWindowJson = string.Format(@"{{ ""GroupPage"":""{0}"", ""PersonProfilePage"":""{1}"", ""MapPage"":""{2}"", ""Template"":""{3}"" }}", groupPage, personProfilePage, mapPage, template); string latitude = "39.8282"; string longitude = "-98.5795"; string zoom = "4"; var orgLocation = GlobalAttributesCache.Read().OrganizationLocation; if (orgLocation != null && orgLocation.GeoPoint != null) { latitude = orgLocation.GeoPoint.Latitude.ToString(); longitude = orgLocation.GeoPoint.Longitude.ToString(); zoom = "12"; } // write script to page string mapScriptFormat = @" <script> Sys.Application.add_load(function () {{ var groupId = {0}; var allMarkers = []; var groupItems = []; var childGroupItems = []; var groupMemberItems = []; var familyItems = {{}}; var map; var bounds = new google.maps.LatLngBounds(); var infoWindow = new google.maps.InfoWindow(); var mapStyle = {1}; var pinShadow = new google.maps.MarkerImage('//chart.googleapis.com/chart?chst=d_map_pin_shadow', new google.maps.Size(40, 37), new google.maps.Point(0, 0), new google.maps.Point(12, 35)); var polygonColorIndex = 0; var polygonColors = [{2}]; var infoWindowRequest = {6}; var min = .999999; var max = 1.000001; initializeMap(); function initializeMap() {{ // Set default map options var mapOptions = {{ mapTypeId: 'roadmap' ,styles: mapStyle ,center: new google.maps.LatLng({7}, {8}) ,zoom: {9} }}; // Display a map on the page map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); map.setTilt(45); var getChildMapInfoUrl = Rock.settings.get('baseUrl') + 'api/Groups/GetMapInfo/{0}/Children'; if ('{10}' != '') {{ getChildMapInfoUrl += '?includeDescendants={10}'; if ('{11}' != '') {{ getChildMapInfoUrl += '&groupTypeIds={11}'; }} }} // Query for group, child group, and group member locations asyncronously $.when ( // Get group $.get( Rock.settings.get('baseUrl') + 'api/Groups/GetMapInfo/{0}', function( mapItems ) {{ $.each(mapItems, function (i, mapItem) {{ $('#lGroupName').text(mapItem.Name); var items = addMapItem(i, mapItem, '{3}'); for (var i = 0; i < items.length; i++) {{ groupItems.push(items[i]); }} }}); if (groupItems.length == 0) {{ $('.js-show-group').hide(); }} else {{ setAllMap(groupItems, null); }} }}), // Get Child Groups $.get(getChildMapInfoUrl, function( mapItems ) {{ $.each(mapItems, function (i, mapItem) {{ var items = addMapItem(i, mapItem, '{4}'); for (var i = 0; i < items.length; i++) {{ childGroupItems.push(items[i]); }} }}); if (childGroupItems.length == 0) {{ $('.js-show-child-groups').hide(); }} else {{ setAllMap(childGroupItems, null); }} }}), // Get Group Members $.get( Rock.settings.get('baseUrl') + 'api/Groups/GetMapInfo/{0}/Members', function( mapItems ) {{ $.each(mapItems, function (i, mapItem) {{ var items = addMapItem(i, mapItem, '{5}'); for (var i = 0; i < items.length; i++) {{ groupMemberItems.push(items[i]); }} }}); if (groupMemberItems.length == 0) {{ $('.js-show-group-members').hide(); }} else {{ setAllMap(groupMemberItems, null); }} }}) ).done( function() {{ // adjust any markers that may overlap adjustOverlappedMarkers(); // When all three requests are done, set the map bounds if (!bounds.isEmpty()) {{ map.fitBounds(bounds); }} // If a group map marker exists, check the group option and show marker if ( groupItems.length > 0) {{ $('#cbShowGroup').prop('checked', true); setAllMap(groupItems, map); // Else check for group member locations, if they exists, select the members option and show member markers }} else if ( groupMemberItems.length > 0) {{ $('#cbShowGroupMembers').prop('checked', true); setAllMap(groupMemberItems, map); // otherwise look for child groups and display their markers }} else if ( childGroupItems.length > 0) {{ $('#cbShowChildGroups').prop('checked', true); setAllMap(childGroupItems, map); }} }}); }} function addMapItem( i, mapItem, color ) {{ var items = []; if (mapItem.Point) {{ var position = new google.maps.LatLng(mapItem.Point.Latitude, mapItem.Point.Longitude); bounds.extend(position); if (!color) {{ color = 'FE7569' }} var pinImage = new google.maps.MarkerImage('//chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|' + color, new google.maps.Size(21, 34), new google.maps.Point(0,0), new google.maps.Point(10, 34)); marker = new google.maps.Marker({{ position: position, map: map, title: htmlDecode(mapItem.Name), icon: pinImage, shadow: pinShadow }}); items.push(marker); allMarkers.push(marker); google.maps.event.addListener(marker, 'click', (function (marker, i) {{ return function () {{ $.post( Rock.settings.get('baseUrl') + 'api/Groups/GetMapInfoWindow/' + mapItem.EntityId + '/' + mapItem.LocationId, infoWindowRequest, function( data ) {{ infoWindow.setContent( data.Result ); infoWindow.open(map, marker); }}); }} }})(marker, i)); }} if (typeof mapItem.PolygonPoints !== 'undefined' && mapItem.PolygonPoints.length > 0) {{ var polygon; var polygonPoints = []; $.each(mapItem.PolygonPoints, function(j, point) {{ var position = new google.maps.LatLng(point.Latitude, point.Longitude); bounds.extend(position); polygonPoints.push(position); }}); var polygonColor = getNextPolygonColor(); polygon = new google.maps.Polygon({{ paths: polygonPoints, map: map, strokeColor: polygonColor, fillColor: polygonColor }}); items.push(polygon); // Get Center var polyBounds = new google.maps.LatLngBounds(); for ( j = 0; j < polygonPoints.length; j++) {{ polyBounds.extend(polygonPoints[j]); }} google.maps.event.addListener(polygon, 'click', (function (polygon, i) {{ return function () {{ $.post( Rock.settings.get('baseUrl') + 'api/Groups/GetMapInfoWindow/' + mapItem.EntityId + '/' + mapItem.LocationId, infoWindowRequest, function( data ) {{ infoWindow.setContent( data.Result ); infoWindow.setPosition(polyBounds.getCenter()); infoWindow.open(map); }}); }} }})(polygon, i)); if ( mapItem.EntityId == {0} ) {{ $('.js-connection-status').show(); }} }} return items; }} // Show/Hide group $('#cbShowGroup').click( function() {{ if ($(this).prop('checked')) {{ setAllMap(groupItems, map); }} else {{ setAllMap(groupItems, null); }} }}); // Show/Hide child groups $('#cbShowChildGroups').click( function() {{ if ($(this).prop('checked')) {{ setAllMap(childGroupItems, map); }} else {{ setAllMap(childGroupItems, null); }} }}); // Show/Hide group members $('#cbShowGroupMembers').click( function() {{ if ($(this).prop('checked')) {{ setAllMap(groupMemberItems, map); }} else {{ setAllMap(groupMemberItems, null); }} }}); // Show/Hide families $('.js-connection-status-cb').click( function() {{ var statusId = $(this).attr('data-item'); if ($(this).prop('checked')) {{ if (typeof familyItems[statusId] !== 'undefined') {{ setAllMap(familyItems[statusId], map); }} else {{ familyItems[statusId] = []; var color = $(this).attr('data-color'); $.get( Rock.settings.get('baseUrl') + 'api/Groups/GetMapInfo/{0}/Families/' + statusId, function( mapItems ) {{ $.each(mapItems, function (i, mapItem) {{ var items = addMapItem(i, mapItem, color); for (var i = 0; i < items.length; i++) {{ familyItems[statusId].push(items[i]); }} }}); }}); }} }} else {{ if (typeof familyItems[statusId] !== 'undefined') {{ setAllMap(familyItems[statusId], null); }} }} }}); function setAllMap(markers, map) {{ for (var i = 0; i < markers.length; i++) {{ markers[i].setMap(map); }} }} function htmlDecode(input) {{ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? """" : e.childNodes[0].nodeValue; }} function getNextPolygonColor() {{ var color = 'FE7569'; if ( polygonColors.length > polygonColorIndex ) {{ color = polygonColors[polygonColorIndex]; polygonColorIndex++; }} else {{ color = polygonColors[0]; polygonColorIndex = 1; }} return color; }} function adjustOverlappedMarkers() {{ if (allMarkers.length > 1) {{ for(i=0; i < allMarkers.length-1; i++) {{ var marker1 = allMarkers[i]; var pos1 = marker1.getPosition(); for(j=i+1; j < allMarkers.length; j++) {{ var marker2 = allMarkers[j]; var pos2 = marker2.getPosition(); if (pos1.equals(pos2)) {{ var newLat = pos1.lat() * (Math.random() * (max - min) + min); var newLng = pos1.lng() * (Math.random() * (max - min) + min); marker1.setPosition( new google.maps.LatLng(newLat,newLng) ); }} }} }} }} }} }}); </script>"; string mapScript = string.Format(mapScriptFormat, groupId.Value, // {0} styleCode, // {1} polygonColors, // {2} _groupColor, // {3} _childGroupColor, // {4} _memberColor, // {5} infoWindowJson, // {6} latitude, // {7} longitude, // {8} zoom, // {9} cbShowAllGroups.Checked.ToTrueFalse(), // {10} gtpGroupType.SelectedGroupTypeIds.AsDelimited(",") // {11} ); ScriptManager.RegisterStartupScript(pnlMap, pnlMap.GetType(), "group-map-script", mapScript, false); }