/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { string formattedValue = string.Empty; if ( !string.IsNullOrWhiteSpace( value ) ) { var names = new List<string>(); foreach ( string guidValue in value.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ) ) { Guid guid = Guid.Empty; if ( Guid.TryParse( guidValue, out guid ) ) { var definedValue = Rock.Web.Cache.DefinedValueCache.Read( guid ); if ( definedValue != null ) { names.Add( definedValue.Name ); } } } formattedValue = names.AsDelimited( ", " ); } return base.FormatValue( parentControl, formattedValue, null, condensed ); }
/// <summary> /// Sets the value. /// </summary> /// <param name="metricCategory">The metric category.</param> public void SetValue( MetricCategory metricCategory ) { if ( metricCategory != null ) { ItemId = metricCategory.Id.ToString(); var parentCategoryIds = new List<string>(); var parentCategory = metricCategory.Category; while ( parentCategory != null ) { if ( !parentCategoryIds.Contains( parentCategory.Id.ToString() ) ) { parentCategoryIds.Insert( 0, parentCategory.Id.ToString() ); } else { // infinite recursion break; } parentCategory = parentCategory.ParentCategory; } InitialItemParentIds = parentCategoryIds.AsDelimited( "," ); ItemName = metricCategory.Name; } else { ItemId = Constants.None.IdValue; ItemName = Constants.None.TextHtml; } }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { string formattedValue = string.Empty; var names = new List<string>(); if ( !string.IsNullOrWhiteSpace( value ) ) { var selectedGuids = new List<Guid>(); value.SplitDelimitedValues().ToList().ForEach( v => selectedGuids.Add( Guid.Parse( v ) ) ); foreach( Guid guid in selectedGuids) { var entityType = EntityTypeCache.Read( guid ); if ( entityType != null ) { names.Add( entityType.FriendlyName ); } } } formattedValue = names.AsDelimited( ", " ); return base.FormatValue( parentControl, formattedValue, null, condensed ); }
/// <summary> /// Sets the value. /// </summary> /// <param name="location">The location.</param> public void SetValue( Rock.Model.Location location ) { if ( location != null ) { ItemId = location.Id.ToString(); List<int> parentLocationIds = new List<int>(); var parentLocation = location.ParentLocation; while ( parentLocation != null ) { if ( parentLocationIds.Contains( parentLocation.Id ) ) { // infinite recursion break; } parentLocationIds.Insert( 0, parentLocation.Id ); ; parentLocation = parentLocation.ParentLocation; } InitialItemParentIds = parentLocationIds.AsDelimited( "," ); ItemName = location.ToString(); } else { ItemId = Constants.None.IdValue; ItemName = Constants.None.TextHtml; } }
/// <summary> /// Reads new values entered by the user for the field /// </summary> /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public override string GetEditValue( System.Web.UI.Control control, Dictionary<string, ConfigurationValue> configurationValues ) { List<string> values = new List<string>(); if ( control != null && control is RockCheckBoxList ) { RockCheckBoxList cbl = (RockCheckBoxList)control; foreach ( ListItem li in cbl.Items ) if ( li.Selected ) values.Add( li.Value ); return values.AsDelimited<string>( "," ); } return null; }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); Guid? workflowGuid = GetAttributeValue( action, "Workflow", true ).AsGuidOrNull(); if ( workflowGuid.HasValue ) { using ( var newRockContext = new RockContext() ) { var workflowService = new WorkflowService( newRockContext ); var workflow = workflowService.Get( workflowGuid.Value ); if ( workflow != null ) { string status = GetAttributeValue( action, "Status" ).ResolveMergeFields( GetMergeFields( action ) ); workflow.Status = status; workflow.AddLogEntry( string.Format( "Status set to '{0}' by another workflow: {1}", status, action.Activity.Workflow ) ); newRockContext.SaveChanges(); action.AddLogEntry( string.Format( "Set Status to '{0}' on another workflow: {1}", status, workflow ) ); bool processNow = GetAttributeValue( action, "ProcessNow" ).AsBoolean(); if ( processNow ) { var processErrors = new List<string>(); if ( !workflowService.Process( workflow, out processErrors ) ) { action.AddLogEntry( "Error(s) occurred processing target workflow: " + processErrors.AsDelimited( ", " ) ); } } return true; } } action.AddLogEntry( "Could not find selected workflow." ); } else { action.AddLogEntry( "Workflow attribute was not set." ); return true; // Continue processing in this case } return false; }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { string formattedValue = string.Empty; var names = new List<string>(); if ( !string.IsNullOrWhiteSpace( value ) ) { int entityTypeId = int.MinValue; if ( int.TryParse( value, out entityTypeId ) ) { var entityType = EntityTypeCache.Read( entityTypeId ); if ( entityType != null ) { names.Add( entityType.FriendlyName ); } } } formattedValue = names.AsDelimited( ", " ); return base.FormatValue( parentControl, formattedValue, null, condensed ); }
/// <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 ) { ParseControls( true ); var rockContext = new RockContext(); var service = new WorkflowTypeService( rockContext ); WorkflowType workflowType = null; int? workflowTypeId = hfWorkflowTypeId.Value.AsIntegerOrNull(); if ( workflowTypeId.HasValue ) { workflowType = service.Get( workflowTypeId.Value ); } if ( workflowType == null ) { workflowType = new WorkflowType(); } var validationErrors = new List<string>(); // check for unique prefix string prefix = tbNumberPrefix.UntrimmedText; if ( !string.IsNullOrWhiteSpace( prefix ) && prefix.ToUpper() != ( workflowType.WorkflowIdPrefix ?? string.Empty ).ToUpper() ) { if ( service.Queryable().AsNoTracking() .Any( w => w.Id != workflowType.Id && w.WorkflowIdPrefix == prefix ) ) { validationErrors.Add( "Workflow Number Prefix is already being used by another workflow type. Please use a unique prefix." ); } else { workflowType.WorkflowIdPrefix = prefix; } } else { workflowType.WorkflowIdPrefix = prefix; } workflowType.IsActive = cbIsActive.Checked; workflowType.Name = tbName.Text; workflowType.Description = tbDescription.Text; workflowType.CategoryId = cpCategory.SelectedValueAsInt(); workflowType.WorkTerm = tbWorkTerm.Text; workflowType.ModifiedByPersonAliasId = CurrentPersonAliasId; workflowType.ModifiedDateTime = RockDateTime.Now; int? mins = tbProcessingInterval.Text.AsIntegerOrNull(); if ( mins.HasValue ) { workflowType.ProcessingIntervalSeconds = mins.Value * 60; } else { workflowType.ProcessingIntervalSeconds = null; } workflowType.IsPersisted = cbIsPersisted.Checked; workflowType.LoggingLevel = ddlLoggingLevel.SelectedValueAsEnum<WorkflowLoggingLevel>(); workflowType.IconCssClass = tbIconCssClass.Text; workflowType.SummaryViewText = ceSummaryViewText.Text; workflowType.NoActionMessage = ceNoActionMessage.Text; if ( validationErrors.Any() ) { nbValidationError.Text = string.Format( "Please Correct the Following<ul><li>{0}</li></ul>", validationErrors.AsDelimited( "</li><li>" ) ); nbValidationError.Visible = true; return; } if ( !Page.IsValid || !workflowType.IsValid ) { return; } foreach(var activityType in ActivityTypesState) { if (!activityType.IsValid) { return; } foreach(var actionType in activityType.ActionTypes) { if ( !actionType.IsValid ) { return; } } } rockContext.WrapTransaction( () => { // Save the entity field changes to workflow type if ( workflowType.Id.Equals( 0 ) ) { service.Add( workflowType ); } rockContext.SaveChanges(); // Save the workflow type attributes SaveAttributes( new Workflow().TypeId, "WorkflowTypeId", workflowType.Id.ToString(), AttributesState, rockContext ); WorkflowActivityTypeService workflowActivityTypeService = new WorkflowActivityTypeService( rockContext ); WorkflowActivityService workflowActivityService = new WorkflowActivityService( rockContext ); WorkflowActionService workflowActionService = new WorkflowActionService( rockContext ); WorkflowActionTypeService workflowActionTypeService = new WorkflowActionTypeService( rockContext ); WorkflowActionFormService workflowFormService = new WorkflowActionFormService( rockContext ); WorkflowActionFormAttributeService workflowFormAttributeService = new WorkflowActionFormAttributeService( rockContext ); // delete WorkflowActionTypes that aren't assigned in the UI anymore List<WorkflowActionType> actionTypesInDB = workflowActionTypeService.Queryable().Where( a => a.ActivityType.WorkflowTypeId.Equals( workflowType.Id ) ).ToList(); List<WorkflowActionType> actionTypesInUI = new List<WorkflowActionType>(); foreach ( var workflowActivity in ActivityTypesState ) { foreach ( var workflowAction in workflowActivity.ActionTypes ) { actionTypesInUI.Add( workflowAction ); } } var deletedActionTypes = from actionType in actionTypesInDB where !actionTypesInUI.Select( u => u.Guid ).Contains( actionType.Guid ) select actionType; foreach ( var actionType in deletedActionTypes.ToList() ) { if ( actionType.WorkflowForm != null ) { workflowFormService.Delete( actionType.WorkflowForm ); } // Delete any workflow actions of this type int loopCounter = 0; foreach ( var action in workflowActionService.Queryable().Where( a => a.ActionTypeId == actionType.Id ) ) { workflowActionService.Delete( action ); loopCounter++; if ( loopCounter > 100 ) { rockContext.SaveChanges(); loopCounter = 0; } } rockContext.SaveChanges(); workflowActionTypeService.Delete( actionType ); } rockContext.SaveChanges(); // delete WorkflowActivityTypes that aren't assigned in the UI anymore List<WorkflowActivityType> activityTypesInDB = workflowActivityTypeService.Queryable().Where( a => a.WorkflowTypeId.Equals( workflowType.Id ) ).ToList(); var deletedActivityTypes = from activityType in activityTypesInDB where !ActivityTypesState.Select( u => u.Guid ).Contains( activityType.Guid ) select activityType; foreach ( var activityType in deletedActivityTypes.ToList() ) { // Delete any workflow activities of this type int loopCounter = 0; foreach ( var activity in workflowActivityService.Queryable().Where( a => a.ActivityTypeId == activityType.Id ) ) { workflowActivityService.Delete( activity ); loopCounter++; if ( loopCounter > 100 ) { rockContext.SaveChanges(); loopCounter = 0; } } rockContext.SaveChanges(); workflowActivityTypeService.Delete( activityType ); } rockContext.SaveChanges(); // add or update WorkflowActivityTypes(and Actions) that are assigned in the UI int workflowActivityTypeOrder = 0; foreach ( var editorWorkflowActivityType in ActivityTypesState ) { // Add or Update the activity type WorkflowActivityType workflowActivityType = workflowType.ActivityTypes.FirstOrDefault( a => a.Guid.Equals( editorWorkflowActivityType.Guid ) ); if ( workflowActivityType == null ) { workflowActivityType = new WorkflowActivityType(); workflowActivityType.Guid = editorWorkflowActivityType.Guid; workflowType.ActivityTypes.Add( workflowActivityType ); } workflowActivityType.IsActive = editorWorkflowActivityType.IsActive; workflowActivityType.Name = editorWorkflowActivityType.Name; workflowActivityType.Description = editorWorkflowActivityType.Description; workflowActivityType.IsActivatedWithWorkflow = editorWorkflowActivityType.IsActivatedWithWorkflow; workflowActivityType.Order = workflowActivityTypeOrder++; // Save Activity Type rockContext.SaveChanges(); // Save ActivityType Attributes if ( ActivityAttributesState.ContainsKey( workflowActivityType.Guid ) ) { SaveAttributes( new WorkflowActivity().TypeId, "ActivityTypeId", workflowActivityType.Id.ToString(), ActivityAttributesState[workflowActivityType.Guid], rockContext ); } // Because the SaveAttributes above may have flushed the cached entity attribute cache, and it would get loaded again with // a different context, manually reload the cache now with our context to prevent a database lock conflict (when database is // configured without snapshot isolation turned on) AttributeCache.LoadEntityAttributes( rockContext ); int workflowActionTypeOrder = 0; foreach ( var editorWorkflowActionType in editorWorkflowActivityType.ActionTypes ) { WorkflowActionType workflowActionType = workflowActivityType.ActionTypes.FirstOrDefault( a => a.Guid.Equals( editorWorkflowActionType.Guid ) ); if ( workflowActionType == null ) { // New action workflowActionType = new WorkflowActionType(); workflowActionType.Guid = editorWorkflowActionType.Guid; workflowActivityType.ActionTypes.Add( workflowActionType ); } workflowActionType.CriteriaAttributeGuid = editorWorkflowActionType.CriteriaAttributeGuid; workflowActionType.CriteriaComparisonType = editorWorkflowActionType.CriteriaComparisonType; workflowActionType.CriteriaValue = editorWorkflowActionType.CriteriaValue; workflowActionType.Name = editorWorkflowActionType.Name; workflowActionType.EntityTypeId = editorWorkflowActionType.EntityTypeId; workflowActionType.IsActionCompletedOnSuccess = editorWorkflowActionType.IsActionCompletedOnSuccess; workflowActionType.IsActivityCompletedOnSuccess = editorWorkflowActionType.IsActivityCompletedOnSuccess; workflowActionType.Attributes = editorWorkflowActionType.Attributes; workflowActionType.AttributeValues = editorWorkflowActionType.AttributeValues; workflowActionType.Order = workflowActionTypeOrder++; if ( workflowActionType.WorkflowForm != null && editorWorkflowActionType.WorkflowForm == null ) { // Form removed workflowFormService.Delete( workflowActionType.WorkflowForm ); workflowActionType.WorkflowForm = null; } if ( editorWorkflowActionType.WorkflowForm != null ) { if ( workflowActionType.WorkflowForm == null ) { workflowActionType.WorkflowForm = new WorkflowActionForm(); } workflowActionType.WorkflowForm.NotificationSystemEmailId = editorWorkflowActionType.WorkflowForm.NotificationSystemEmailId; workflowActionType.WorkflowForm.IncludeActionsInNotification = editorWorkflowActionType.WorkflowForm.IncludeActionsInNotification; workflowActionType.WorkflowForm.AllowNotes = editorWorkflowActionType.WorkflowForm.AllowNotes; workflowActionType.WorkflowForm.Header = editorWorkflowActionType.WorkflowForm.Header; workflowActionType.WorkflowForm.Footer = editorWorkflowActionType.WorkflowForm.Footer; workflowActionType.WorkflowForm.Actions = editorWorkflowActionType.WorkflowForm.Actions; workflowActionType.WorkflowForm.ActionAttributeGuid = editorWorkflowActionType.WorkflowForm.ActionAttributeGuid; var editorGuids = editorWorkflowActionType.WorkflowForm.FormAttributes .Select( a => a.Attribute.Guid ) .ToList(); foreach ( var formAttribute in workflowActionType.WorkflowForm.FormAttributes .Where( a => !editorGuids.Contains( a.Attribute.Guid ) ).ToList() ) { workflowFormAttributeService.Delete( formAttribute ); } int attributeOrder = 0; foreach ( var editorAttribute in editorWorkflowActionType.WorkflowForm.FormAttributes.OrderBy( a => a.Order ) ) { int attributeId = AttributeCache.Read( editorAttribute.Attribute.Guid, rockContext ).Id; var formAttribute = workflowActionType.WorkflowForm.FormAttributes .Where( a => a.AttributeId == attributeId ) .FirstOrDefault(); if ( formAttribute == null ) { formAttribute = new WorkflowActionFormAttribute(); formAttribute.Guid = editorAttribute.Guid; formAttribute.AttributeId = attributeId; workflowActionType.WorkflowForm.FormAttributes.Add( formAttribute ); } formAttribute.Order = attributeOrder++; formAttribute.IsVisible = editorAttribute.IsVisible; formAttribute.IsReadOnly = editorAttribute.IsReadOnly; formAttribute.IsRequired = editorAttribute.IsRequired; formAttribute.HideLabel = editorAttribute.HideLabel; formAttribute.PreHtml = editorAttribute.PreHtml; formAttribute.PostHtml = editorAttribute.PostHtml; } } } } rockContext.SaveChanges(); foreach ( var activityType in workflowType.ActivityTypes ) { foreach ( var workflowActionType in activityType.ActionTypes ) { workflowActionType.SaveAttributeValues( rockContext ); } } } ); var qryParams = new Dictionary<string, string>(); qryParams["workflowTypeId"] = workflowType.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Handles the Click event of the btnCopy 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 btnCopy_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); var workflowType = new WorkflowTypeService( rockContext ).Get( hfWorkflowTypeId.Value.AsInteger() ); if ( workflowType != null ) { // Load the state objects for the source workflow type LoadStateDetails( workflowType, rockContext ); // clone the workflow type var newWorkflowType = workflowType.Clone( false ); newWorkflowType.CreatedByPersonAlias = null; newWorkflowType.CreatedByPersonAliasId = null; newWorkflowType.CreatedDateTime = RockDateTime.Now; newWorkflowType.ModifiedByPersonAlias = null; newWorkflowType.ModifiedByPersonAliasId = null; newWorkflowType.ModifiedDateTime = RockDateTime.Now; newWorkflowType.Id = 0; newWorkflowType.Guid = Guid.NewGuid(); newWorkflowType.IsSystem = false; newWorkflowType.Name = workflowType.Name + " - Copy"; // Create temporary state objects for the new workflow type var newAttributesState = new List<Attribute>(); var newActivityTypesState = new List<WorkflowActivityType>(); var newActivityAttributesState = new Dictionary<Guid, List<Attribute>>(); // Dictionary to keep the attributes and activity types linked between the source and the target based on their guids var guidXref = new Dictionary<Guid, Guid>(); // Clone the workflow attributes foreach ( var attribute in AttributesState ) { var newAttribute = attribute.Clone( false ); newAttribute.Id = 0; newAttribute.Guid = Guid.NewGuid(); newAttribute.IsSystem = false; newAttributesState.Add( newAttribute ); guidXref.Add( attribute.Guid, newAttribute.Guid ); foreach ( var qualifier in attribute.AttributeQualifiers ) { var newQualifier = qualifier.Clone( false ); newQualifier.Id = 0; newQualifier.Guid = Guid.NewGuid(); newQualifier.IsSystem = false; newAttribute.AttributeQualifiers.Add( qualifier ); guidXref.Add( qualifier.Guid, newQualifier.Guid ); } } // Create new guids for all the existing activity types foreach (var activityType in ActivityTypesState) { guidXref.Add( activityType.Guid, Guid.NewGuid() ); } foreach ( var activityType in ActivityTypesState ) { var newActivityType = activityType.Clone( false ); newActivityType.WorkflowTypeId = 0; newActivityType.Id = 0; newActivityType.Guid = guidXref[activityType.Guid]; newActivityTypesState.Add( newActivityType ); var newActivityAttributes = new List<Attribute>(); foreach ( var attribute in ActivityAttributesState[activityType.Guid] ) { var newAttribute = attribute.Clone( false ); newAttribute.Id = 0; newAttribute.Guid = Guid.NewGuid(); newAttribute.IsSystem = false; newActivityAttributes.Add( newAttribute ); guidXref.Add( attribute.Guid, newAttribute.Guid ); foreach ( var qualifier in attribute.AttributeQualifiers ) { var newQualifier = qualifier.Clone( false ); newQualifier.Id = 0; newQualifier.Guid = Guid.NewGuid(); newQualifier.IsSystem = false; newAttribute.AttributeQualifiers.Add( qualifier ); guidXref.Add( qualifier.Guid, newQualifier.Guid ); } } newActivityAttributesState.Add( newActivityType.Guid, newActivityAttributes ); foreach ( var actionType in activityType.ActionTypes ) { var newActionType = actionType.Clone( false ); newActionType.ActivityTypeId = 0; newActionType.WorkflowFormId = 0; newActionType.Id = 0; newActionType.Guid = Guid.NewGuid(); newActivityType.ActionTypes.Add( newActionType ); if ( actionType.CriteriaAttributeGuid.HasValue && guidXref.ContainsKey( actionType.CriteriaAttributeGuid.Value ) ) { newActionType.CriteriaAttributeGuid = guidXref[actionType.CriteriaAttributeGuid.Value]; } Guid criteriaAttributeGuid = actionType.CriteriaValue.AsGuid(); if ( !criteriaAttributeGuid.IsEmpty() && guidXref.ContainsKey( criteriaAttributeGuid ) ) { newActionType.CriteriaValue = guidXref[criteriaAttributeGuid].ToString(); } if ( actionType.WorkflowForm != null ) { var newWorkflowForm = actionType.WorkflowForm.Clone( false ); newWorkflowForm.Id = 0; newWorkflowForm.Guid = Guid.NewGuid(); var newActionButtons = new List<string>(); foreach ( var actionButton in actionType.WorkflowForm.Actions.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ) ) { var details = actionButton.Split( new char[] { '^' } ); if ( details.Length > 2 ) { Guid oldGuid = details[2].AsGuid(); if (!oldGuid.IsEmpty() && guidXref.ContainsKey(oldGuid)) { details[2] = guidXref[oldGuid].ToString(); } } newActionButtons.Add( details.ToList().AsDelimited("^") ); } newWorkflowForm.Actions = newActionButtons.AsDelimited( "|" ); if ( actionType.WorkflowForm.ActionAttributeGuid.HasValue && guidXref.ContainsKey( actionType.WorkflowForm.ActionAttributeGuid.Value ) ) { newWorkflowForm.ActionAttributeGuid = guidXref[actionType.WorkflowForm.ActionAttributeGuid.Value]; } newActionType.WorkflowForm = newWorkflowForm; foreach ( var formAttribute in actionType.WorkflowForm.FormAttributes ) { if ( guidXref.ContainsKey( formAttribute.Attribute.Guid ) ) { var newFormAttribute = formAttribute.Clone( false ); newFormAttribute.WorkflowActionFormId = 0; newFormAttribute.Id = 0; newFormAttribute.Guid = Guid.NewGuid(); newFormAttribute.AttributeId = 0; newFormAttribute.Attribute = new Rock.Model.Attribute { Guid = guidXref[formAttribute.Attribute.Guid], Name = formAttribute.Attribute.Name }; newWorkflowForm.FormAttributes.Add( newFormAttribute ); } } } newActionType.LoadAttributes( rockContext ); if ( actionType.Attributes != null && actionType.Attributes.Any() ) { foreach ( var attributeKey in actionType.Attributes.Select( a => a.Key ) ) { string value = actionType.GetAttributeValue( attributeKey ); Guid guidValue = value.AsGuid(); if ( !guidValue.IsEmpty() && guidXref.ContainsKey( guidValue ) ) { newActionType.SetAttributeValue( attributeKey, guidXref[guidValue].ToString() ); } else { newActionType.SetAttributeValue( attributeKey, value ); } } } } } workflowType = newWorkflowType; AttributesState = newAttributesState; ActivityTypesState = newActivityTypesState; ActivityAttributesState = newActivityAttributesState; hfWorkflowTypeId.Value = workflowType.Id.ToString(); ShowEditDetails( workflowType, rockContext ); } }
/// <summary> /// Resolves the values. /// </summary> /// <param name="values">The values.</param> /// <param name="listControl">The list control.</param> /// <returns></returns> private string ResolveValues( string values, System.Web.UI.WebControls.CheckBoxList checkBoxList ) { var resolvedValues = new List<string>(); foreach ( string value in values.Split( ';' ) ) { var item = checkBoxList.Items.FindByValue( value ); if ( item != null ) { resolvedValues.Add( item.Text ); } } return resolvedValues.AsDelimited( ", " ); }
/// <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 OnLoad( EventArgs e ) { base.OnLoad( e ); bool canEditBlock = IsUserAuthorized( Authorization.EDIT ); if ( !Page.IsPostBack ) { if ( string.IsNullOrWhiteSpace( _groupId ) ) { // If no group was selected, try to find the first group and redirect // back to current page with that group selected var group = FindFirstGroup(); { if ( group != null ) { _groupId = group.Id.ToString(); string redirectUrl = string.Empty; // redirect so that the group treeview has the first node selected right away and group detail shows the group if ( hfPageRouteTemplate.Value.IndexOf( "{groupId}", StringComparison.OrdinalIgnoreCase ) >= 0 ) { redirectUrl = "~/" + hfPageRouteTemplate.Value.ReplaceCaseInsensitive( "{groupId}", _groupId.ToString() ); } else { redirectUrl = this.Request.Url + "?GroupId=" + _groupId.ToString(); } this.Response.Redirect( redirectUrl, false ); Context.ApplicationInstance.CompleteRequest(); } } } } if ( !string.IsNullOrWhiteSpace( _groupId ) ) { hfInitialGroupId.Value = _groupId; hfSelectedGroupId.Value = _groupId; string key = string.Format( "Group:{0}", _groupId ); Group group = RockPage.GetSharedItem( key ) as Group; if ( group == null ) { int id = _groupId.AsInteger(); group = new GroupService( new RockContext() ).Queryable( "GroupType" ) .Where( g => g.Id == id ) .FirstOrDefault(); RockPage.SaveSharedItem( key, group ); } if ( group != null ) { // show the Add button if the selected Group's GroupType can have children lbAddGroupChild.Enabled = canEditBlock && group.GroupType.ChildGroupTypes.Count > 0; } else { // hide the Add Button when adding a new Group lbAddGroupChild.Enabled = false; } // get the parents of the selected item so we can tell the treeview to expand those int? rootGroupId = GetAttributeValue( "RootGroup" ).AsIntegerOrNull(); List<string> parentIdList = new List<string>(); while ( group != null ) { if ( group.Id == rootGroupId ) { // stop if we are at the root group group = null; } else { group = group.ParentGroup; } if ( group != null ) { parentIdList.Insert( 0, group.Id.ToString() ); } } // also get any additional expanded nodes that were sent in the Post string postedExpandedIds = this.Request.Params["ExpandedIds"]; if ( !string.IsNullOrWhiteSpace( postedExpandedIds ) ) { var postedExpandedIdList = postedExpandedIds.Split( ',' ).ToList(); foreach ( var id in postedExpandedIdList ) { if ( !parentIdList.Contains( id ) ) { parentIdList.Add( id ); } } } hfInitialGroupParentIds.Value = parentIdList.AsDelimited( "," ); } else { // let the Add button be visible if there is nothing selected (if authorized) lbAddGroupChild.Enabled = canEditBlock; } // disable add child group if no group is selected int selectedGroupId = hfSelectedGroupId.ValueAsInt(); if ( selectedGroupId == 0 ) { lbAddGroupChild.Enabled = false; } }
/// <summary> /// Formats the fee cost. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> protected string FormatFeeCost( string value ) { var values = new List<string>(); string[] nameValues = value.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ); foreach ( string nameValue in nameValues ) { string[] nameAndValue = nameValue.Split( new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries ); if ( nameAndValue.Length == 2 ) { values.Add( string.Format( "{0}-{1}", nameAndValue[0], nameAndValue[1].AsDecimal().FormatAsCurrency() ) ); } else { values.Add( string.Format( "{0}", nameValue.AsDecimal().FormatAsCurrency() ) ); } } return values.AsDelimited( ", " ); }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { string formattedValue = string.Empty; if ( !string.IsNullOrWhiteSpace( value ) ) { var names = new List<string>(); foreach ( Guid guid in value.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).AsGuidList() ) { var attribute = AttributeCache.Read( guid ); if ( attribute != null ) { names.Add( attribute.Name ); } } formattedValue = names.AsDelimited( ", " ); } return base.FormatValue( parentControl, formattedValue, null, condensed ); }
/// <summary> /// Processes the payment information. /// </summary> /// <param name="errorMessage">The error message.</param> /// <returns></returns> private bool ProcessPaymentInfo( out string errorMessage ) { errorMessage = string.Empty; var errorMessages = new List<string>(); // Validate that an amount was entered if ( SelectedAccounts.Sum( a => a.Amount ) <= 0 ) { errorMessages.Add( "Make sure you've entered an amount for at least one account" ); } // Validate that no negative amounts were entered if ( SelectedAccounts.Any( a => a.Amount < 0 ) ) { errorMessages.Add( "Make sure the amount you've entered for each account is a positive amount" ); } string howOften = DefinedValueCache.Read( btnFrequency.SelectedValueAsId().Value ).Name; DateTime when = DateTime.MinValue; // Make sure a repeating payment starts in the future if ( dtpStartDate.SelectedDate.HasValue && dtpStartDate.SelectedDate > DateTime.Today ) { when = dtpStartDate.SelectedDate.Value; } else { errorMessages.Add( "Make sure the Next Gift date is in the future (after today)" ); } if ( hfPaymentTab.Value == "ACH" ) { // Validate ach options if ( rblSavedAch.Items.Count > 0 && ( rblSavedAch.SelectedValueAsInt() ?? 0 ) > 0 ) { // TODO: Find saved account } else { if ( string.IsNullOrWhiteSpace( txtBankName.Text ) ) { errorMessages.Add( "Make sure to enter a bank name" ); } if ( string.IsNullOrWhiteSpace( txtRoutingNumber.Text ) ) { errorMessages.Add( "Make sure to enter a valid routing number" ); } if ( string.IsNullOrWhiteSpace( txtAccountNumber.Text ) ) { errorMessages.Add( "Make sure to enter a valid account number" ); } } } else if ( hfPaymentTab.Value == "CreditCard" ) { // validate cc options if ( rblSavedCC.Items.Count > 0 && ( rblSavedCC.SelectedValueAsInt() ?? 0 ) > 0 ) { // TODO: Find saved card } else { if ( Gateway.SplitNameOnCard ) { if ( string.IsNullOrWhiteSpace( txtCardFirstName.Text ) || string.IsNullOrWhiteSpace( txtCardLastName.Text ) ) { errorMessages.Add( "Make sure to enter a valid first and last name as it appears on your credit card" ); } } else { if ( string.IsNullOrWhiteSpace( txtCardName.Text ) ) { errorMessages.Add( "Make sure to enter a valid name as it appears on your credit card" ); } } if ( string.IsNullOrWhiteSpace( txtCreditCard.Text ) ) { errorMessages.Add( "Make sure to enter a valid credit card number" ); } var currentMonth = DateTime.Today; currentMonth = new DateTime( currentMonth.Year, currentMonth.Month, 1 ); if ( !mypExpiration.SelectedDate.HasValue || mypExpiration.SelectedDate.Value.CompareTo( currentMonth ) < 0 ) { errorMessages.Add( "Make sure to enter a valid credit card expiration date" ); } if ( string.IsNullOrWhiteSpace( txtCVV.Text ) ) { errorMessages.Add( "Make sure to enter a valid credit card security code" ); } } } if ( errorMessages.Any() ) { errorMessage = errorMessages.AsDelimited( "<br/>" ); return false; } using ( new UnitOfWorkScope() ) { FinancialScheduledTransaction scheduledTransaction = null; if ( ScheduledTransactionId.HasValue ) { scheduledTransaction = new FinancialScheduledTransactionService().Get( ScheduledTransactionId.Value ); } if ( scheduledTransaction == null ) { errorMessage = "There was a problem getting the transaction information"; return false; } if ( scheduledTransaction.AuthorizedPerson == null ) { errorMessage = "There was a problem determining the person associated with the transaction"; return false; } PaymentInfo paymentInfo = GetPaymentInfo( new PersonService(), scheduledTransaction ); if ( paymentInfo != null ) { tdName.Description = paymentInfo.FullName; tdTotal.Description = paymentInfo.Amount.ToString( "C" ); if (paymentInfo.CurrencyTypeValue != null) { tdPaymentMethod.Description = paymentInfo.CurrencyTypeValue.Description; tdPaymentMethod.Visible = true; } else { tdPaymentMethod.Visible = false; } if (string.IsNullOrWhiteSpace(paymentInfo.MaskedNumber)) { tdAccountNumber.Visible = false; } else { tdAccountNumber.Visible = true; tdAccountNumber.Description = paymentInfo.MaskedNumber; } tdWhen.Description = string.Format( "{0} starting on {1}", howOften, when.ToShortDateString()); } } rptAccountListConfirmation.DataSource = SelectedAccounts.Where( a => a.Amount != 0 ); rptAccountListConfirmation.DataBind(); string nextDate = dtpStartDate.SelectedDate.HasValue ? dtpStartDate.SelectedDate.Value.ToShortDateString() : "?"; string frequency = DefinedValueCache.Read( btnFrequency.SelectedValueAsInt() ?? 0 ).Description; tdWhen.Description = frequency + " starting on " + nextDate; return true; }
/// <summary> /// Shows the preview. /// </summary> /// <param name="entityTypeId">The entity type id.</param> /// <param name="filter">The filter.</param> private void BindGrid( Report report ) { if ( report != null ) { var errors = new List<string>(); if ( !report.EntityTypeId.HasValue ) { return; } string authorizationMessage; if ( !this.IsAuthorizedForAllReportComponents( Authorization.VIEW, report, out authorizationMessage ) ) { nbEditModeMessage.Text = authorizationMessage; return; } Type entityType = EntityTypeCache.Read( report.EntityTypeId.Value ).GetEntityType(); bool isPersonDataSet = report.EntityTypeId == EntityTypeCache.Read( typeof( Rock.Model.Person ) ).Id; if ( isPersonDataSet ) { gReport.PersonIdField = "Id"; gReport.DataKeyNames = new string[] { "id" }; } else { gReport.PersonIdField = null; } if ( report.EntityTypeId.HasValue ) { gReport.RowItemText = EntityTypeCache.Read( report.EntityTypeId.Value ).FriendlyName; } List<EntityField> entityFields = Rock.Reporting.EntityHelper.GetEntityFields( entityType ); var selectedEntityFields = new Dictionary<int, EntityField>(); var selectedAttributes = new Dictionary<int, AttributeCache>(); var selectedComponents = new Dictionary<int, ReportField>(); gReport.Columns.Clear(); int columnIndex = 0; if ( !string.IsNullOrWhiteSpace( gReport.PersonIdField ) ) { gReport.Columns.Add( new SelectField() ); columnIndex++; } foreach ( var reportField in report.ReportFields.OrderBy( a => a.Order ) ) { columnIndex++; if ( reportField.ReportFieldType == ReportFieldType.Property ) { var entityField = entityFields.FirstOrDefault( a => a.Name == reportField.Selection ); if ( entityField != null ) { selectedEntityFields.Add( columnIndex, entityField ); BoundField boundField; if ( entityField.DefinedTypeGuid.HasValue ) { boundField = new DefinedValueField(); } else { boundField = Grid.GetGridField( entityField.PropertyType ); } boundField.DataField = string.Format( "Entity_{0}_{1}", entityField.Name, columnIndex ); boundField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? entityField.Title : reportField.ColumnHeaderText; boundField.SortExpression = entityField.Name; boundField.Visible = reportField.ShowInGrid; gReport.Columns.Add( boundField ); } } else if ( reportField.ReportFieldType == ReportFieldType.Attribute ) { Guid? attributeGuid = reportField.Selection.AsGuidOrNull(); if ( attributeGuid.HasValue ) { var attribute = AttributeCache.Read( attributeGuid.Value ); selectedAttributes.Add( columnIndex, attribute ); BoundField boundField; if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.BOOLEAN.AsGuid() ) ) { boundField = new BoolField(); } else { boundField = new BoundField(); } boundField.DataField = string.Format( "Attribute_{0}_{1}", attribute.Id, columnIndex ); boundField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? attribute.Name : reportField.ColumnHeaderText; boundField.SortExpression = null; if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.INTEGER.AsGuid() ) || attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE.AsGuid() ) ) { boundField.HeaderStyle.HorizontalAlign = HorizontalAlign.Right; boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Right; } boundField.Visible = reportField.ShowInGrid; // NOTE: Additional formatting for attributes is done in the gReport_RowDataBound event gReport.Columns.Add( boundField ); } } else if ( reportField.ReportFieldType == ReportFieldType.DataSelectComponent ) { selectedComponents.Add( columnIndex, reportField ); DataSelectComponent selectComponent = DataSelectContainer.GetComponent( reportField.DataSelectComponentEntityType.Name ); if ( selectComponent != null ) { DataControlField columnField = selectComponent.GetGridField( entityType, reportField.Selection ); if ( columnField is BoundField ) { ( columnField as BoundField ).DataField = string.Format( "Data_{0}_{1}", selectComponent.ColumnPropertyName, columnIndex ); } columnField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? selectComponent.ColumnHeaderText : reportField.ColumnHeaderText; columnField.SortExpression = null; columnField.Visible = reportField.ShowInGrid; gReport.Columns.Add( columnField ); } } } // if no fields are specified, show the default fields (Previewable/All) for the EntityType var dataColumns = gReport.Columns.OfType<object>().Where(a => a.GetType() != typeof(SelectField)); if (dataColumns.Count() == 0) { // show either the Previewable Columns or all (if there are no previewable columns) bool showAllColumns = !entityFields.Any( a => a.FieldKind == FieldKind.Property && a.IsPreviewable ); foreach ( var entityField in entityFields.Where(a => a.FieldKind == FieldKind.Property) ) { columnIndex++; selectedEntityFields.Add( columnIndex, entityField ); BoundField boundField; if ( entityField.DefinedTypeGuid.HasValue ) { boundField = new DefinedValueField(); } else { boundField = Grid.GetGridField( entityField.PropertyType ); } boundField.DataField = string.Format( "Entity_{0}_{1}", entityField.Name, columnIndex ); boundField.HeaderText = entityField.Name; boundField.SortExpression = entityField.Name; boundField.Visible = showAllColumns || entityField.IsPreviewable; gReport.Columns.Add( boundField ); } } try { gReport.ExportFilename = report.Name; gReport.DataSource = report.GetDataSource( new RockContext(), entityType, selectedEntityFields, selectedAttributes, selectedComponents, gReport.SortProperty, out errors ); gReport.DataBind(); } catch ( Exception ex ) { errors.Add( ex.Message ); } if ( errors.Any() ) { nbEditModeMessage.Text = "INFO: There was a problem with one or more of the report's data components...<br/><br/> " + errors.AsDelimited( "<br/>" ); } } }
/// <summary> /// Sets the allowed group types. /// </summary> private void SetAllowedGroupTypes() { // limit GroupType selection to what Block Attributes allow hfGroupTypesInclude.Value = string.Empty; List<Guid> groupTypeIncludeGuids = GetAttributeValue( "GroupTypes" ).SplitDelimitedValues().AsGuidList(); if ( groupTypeIncludeGuids.Any() ) { var groupTypeIdIncludeList = new List<int>(); foreach ( Guid guid in groupTypeIncludeGuids ) { var groupType = GroupTypeCache.Read( guid ); if ( groupType != null ) { groupTypeIdIncludeList.Add( groupType.Id ); } } hfGroupTypesInclude.Value = groupTypeIdIncludeList.AsDelimited( "," ); } hfGroupTypesExclude.Value = string.Empty; List<Guid> groupTypeExcludeGuids = GetAttributeValue( "GroupTypesExclude" ).SplitDelimitedValues().AsGuidList(); if ( groupTypeExcludeGuids.Any() ) { var groupTypeIdExcludeList = new List<int>(); foreach ( Guid guid in groupTypeExcludeGuids ) { var groupType = GroupTypeCache.Read( guid ); if ( groupType != null ) { groupTypeIdExcludeList.Add( groupType.Id ); } } hfGroupTypesExclude.Value = groupTypeIdExcludeList.AsDelimited( "," ); } }
void gPeople_RowDataBound( object sender, GridViewRowEventArgs e ) { if ( e.Row.RowType == DataControlRowType.DataRow ) { var person = e.Row.DataItem as PersonSearchResult; if ( person != null ) { if (_inactiveStatus != null && person.RecordStatusValueId.HasValue && person.RecordStatusValueId.Value == _inactiveStatus.Id) { e.Row.AddCssClass( "inactive" ); } if ( person.IsDeceased ) { e.Row.AddCssClass( "deceased" ); } string delimitedCampuses = string.Empty; if ( person.CampusIds.Any() ) { var campuses = new List<string>(); foreach ( var campusId in person.CampusIds ) { var campus = CampusCache.Read( campusId ); if ( campus != null ) { campuses.Add( campus.Name ); } } if ( campuses.Any() ) { delimitedCampuses = campuses.AsDelimited( ", " ); var lCampus = e.Row.FindControl( "lCampus" ) as Literal; if ( lCampus != null ) { lCampus.Text = delimitedCampuses; } } } var lPerson = e.Row.FindControl( "lPerson" ) as Literal; if ( !person.IsBusiness ) { StringBuilder sbPersonDetails = new StringBuilder(); sbPersonDetails.Append( string.Format( "<div class=\"photo-round photo-round-sm pull-left\" data-original=\"{0}&w=100\" style=\"background-image: url('{1}');\"></div>", person.PhotoUrl, ResolveUrl("~/Assets/Images/person-no-photo-male.svg") ) ); sbPersonDetails.Append("<div class=\"pull-left margin-l-sm\">"); sbPersonDetails.Append(string.Format("<strong>{0}</strong> ", person.FullNameReversed)); sbPersonDetails.Append( string.Format( "<small class=\"hidden-sm hidden-md hidden-lg\"><br>{0}</br></small>", delimitedCampuses ) ); sbPersonDetails.Append( string.Format( "<small class=\"hidden-sm hidden-md hidden-lg\">{0}</small>", DefinedValueCache.GetName( person.ConnectionStatusValueId ) ) ); sbPersonDetails.Append(string.Format(" <small class=\"hidden-md hidden-lg\">{0}</small>", person.AgeFormatted)); if (!string.IsNullOrWhiteSpace(person.Email)){ sbPersonDetails.Append(string.Format("<br/><small>{0}</small>", person.Email)); } // add home addresses foreach(var location in person.HomeAddresses ) { if ( string.IsNullOrWhiteSpace( location.Street1 ) && string.IsNullOrWhiteSpace( location.Street2 ) && string.IsNullOrWhiteSpace( location.City ) ) { continue; } string format = string.Empty; var countryValue = Rock.Web.Cache.DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.LOCATION_COUNTRIES.AsGuid() ) .DefinedValues .Where( v => v.Value.Equals( location.Country, StringComparison.OrdinalIgnoreCase ) ) .FirstOrDefault(); if ( countryValue != null ) { format = countryValue.GetAttributeValue( "AddressFormat" ); } if ( !string.IsNullOrWhiteSpace( format ) ) { var dict = location.ToDictionary(); dict["Country"] = countryValue.Description; sbPersonDetails.Append( string.Format( "<small><br>{0}</small>", format.ResolveMergeFields( dict ).ConvertCrLfToHtmlBr().Replace( "<br/><br/>", "<br/>" ) ) ); } else { sbPersonDetails.Append( string.Format( string.Format( "<small><br>{0}<br>{1} {2}, {3} {4}</small>", location.Street1, location.Street2, location.City, location.State, location.PostalCode ) ) ); } } sbPersonDetails.Append("</div>"); lPerson.Text = sbPersonDetails.ToString(); } else { lPerson.Text = string.Format( "{0}", person.LastName ); } } } }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues"></param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { bool isDefinedType = configurationValues != null && configurationValues.ContainsKey( "definedtype" ) && configurationValues["definedtype"].Value.AsIntegerOrNull().HasValue; var values = new List<string>(); string[] nameValues = value.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ); foreach ( string nameValue in nameValues ) { string[] nameAndValue = nameValue.Split( new char[] { '^' } ); if ( nameAndValue.Length == 2 ) { if ( isDefinedType ) { var definedValue = DefinedValueCache.Read( nameAndValue[1].AsInteger() ); if ( definedValue != null ) { nameAndValue[1] = definedValue.Value; } } values.Add( string.Format( "{0}: {1}", nameAndValue[0], nameAndValue[1] ) ); } else { values.Add( nameValue ); } } return values.AsDelimited( ", " ); }
/// <summary> /// Handles the ServerValidate event of the cvPageRoute control. /// </summary> /// <param name="source">The source of the event.</param> /// <param name="args">The <see cref="ServerValidateEventArgs"/> instance containing the event data.</param> protected void cvPageRoute_ServerValidate( object source, ServerValidateEventArgs args ) { var errorMessages = new List<string>(); foreach ( string route in tbPageRoute.Text.SplitDelimitedValues() ) { var pageRoute = new PageRoute(); pageRoute.Route = route.TrimStart( new char[] { '/' } ); pageRoute.Guid = Guid.NewGuid(); if ( !pageRoute.IsValid ) { errorMessages.Add( string.Format( "The '{0}' route is invalid: {1}", route, pageRoute.ValidationResults.Select( r => r.ErrorMessage ).ToList().AsDelimited( "; " ) ) ); } } cvPageRoute.ErrorMessage = errorMessages.AsDelimited( "<br/>" ); args.IsValid = !errorMessages.Any(); }
/// <summary> /// Reads new values entered by the user for the field /// </summary> /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param> /// <param name="configurationValues"></param> /// <returns></returns> public override string GetEditValue( Control control, Dictionary<string, ConfigurationValue> configurationValues ) { var ids = new List<string>(); if ( control != null && control is ListControl ) { if ( control is Rock.Web.UI.Controls.RockDropDownList ) { ids.Add( ( (ListControl)control ).SelectedValue ); } else if ( control is Rock.Web.UI.Controls.RockCheckBoxList ) { var cblControl = control as Rock.Web.UI.Controls.RockCheckBoxList; ids.AddRange( cblControl.Items.Cast<ListItem>() .Where( i => i.Selected ) .Select( i => i.Value ) ); } } var guids = new List<string>(); foreach ( int attributeId in ids.AsIntegerList() ) { var attribute = Rock.Web.Cache.AttributeCache.Read( attributeId ); if ( attribute != null ) { guids.Add( attribute.Guid.ToString() ); } } return guids.AsDelimited( "," ); }
/// <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 ) { ParseControls( true ); var rockContext = new RockContext(); var service = new RegistrationTemplateService( rockContext ); RegistrationTemplate RegistrationTemplate = null; int? RegistrationTemplateId = hfRegistrationTemplateId.Value.AsIntegerOrNull(); if ( RegistrationTemplateId.HasValue ) { RegistrationTemplate = service.Get( RegistrationTemplateId.Value ); } bool newTemplate = false; if ( RegistrationTemplate == null ) { newTemplate = true; RegistrationTemplate = new RegistrationTemplate(); } RegistrationNotify notify = RegistrationNotify.None; foreach( ListItem li in cblNotify.Items ) { if ( li.Selected ) { notify = notify | (RegistrationNotify)li.Value.AsInteger(); } } RegistrationTemplate.IsActive = cbIsActive.Checked; RegistrationTemplate.Name = tbName.Text; RegistrationTemplate.CategoryId = cpCategory.SelectedValueAsInt(); RegistrationTemplate.GroupTypeId = gtpGroupType.SelectedGroupTypeId; RegistrationTemplate.GroupMemberRoleId = rpGroupTypeRole.GroupRoleId; RegistrationTemplate.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>(); RegistrationTemplate.RequiredSignatureDocumentTemplateId = ddlSignatureDocumentTemplate.SelectedValueAsInt(); RegistrationTemplate.SignatureDocumentAction = cbDisplayInLine.Checked ? SignatureDocumentAction.Embed : SignatureDocumentAction.Email; RegistrationTemplate.RegistrationWorkflowTypeId = wtpRegistrationWorkflow.SelectedValueAsInt(); RegistrationTemplate.Notify = notify; RegistrationTemplate.AddPersonNote = cbAddPersonNote.Checked; RegistrationTemplate.LoginRequired = cbLoginRequired.Checked; RegistrationTemplate.AllowExternalRegistrationUpdates = cbAllowExternalUpdates.Checked; RegistrationTemplate.AllowGroupPlacement = cbAllowGroupPlacement.Checked; RegistrationTemplate.AllowMultipleRegistrants = cbMultipleRegistrants.Checked; RegistrationTemplate.MaxRegistrants = nbMaxRegistrants.Text.AsInteger(); RegistrationTemplate.RegistrantsSameFamily = rblRegistrantsInSameFamily.SelectedValueAsEnum<RegistrantsSameFamily>(); RegistrationTemplate.ShowCurrentFamilyMembers = cbShowCurrentFamilyMembers.Checked; RegistrationTemplate.SetCostOnInstance = !tglSetCostOnTemplate.Checked; RegistrationTemplate.Cost = cbCost.Text.AsDecimal(); RegistrationTemplate.MinimumInitialPayment = cbMinimumInitialPayment.Text.AsDecimalOrNull(); RegistrationTemplate.FinancialGatewayId = fgpFinancialGateway.SelectedValueAsInt(); RegistrationTemplate.BatchNamePrefix = txtBatchNamePrefix.Text; RegistrationTemplate.ConfirmationFromName = tbConfirmationFromName.Text; RegistrationTemplate.ConfirmationFromEmail = tbConfirmationFromEmail.Text; RegistrationTemplate.ConfirmationSubject = tbConfirmationSubject.Text; RegistrationTemplate.ConfirmationEmailTemplate = ceConfirmationEmailTemplate.Text; RegistrationTemplate.ReminderFromName = tbReminderFromName.Text; RegistrationTemplate.ReminderFromEmail = tbReminderFromEmail.Text; RegistrationTemplate.ReminderSubject = tbReminderSubject.Text; RegistrationTemplate.ReminderEmailTemplate = ceReminderEmailTemplate.Text; RegistrationTemplate.PaymentReminderFromName = tbPaymentReminderFromName.Text; RegistrationTemplate.PaymentReminderFromEmail = tbPaymentReminderFromEmail.Text; RegistrationTemplate.PaymentReminderSubject = tbPaymentReminderSubject.Text; RegistrationTemplate.PaymentReminderEmailTemplate = cePaymentReminderEmailTemplate.Text; RegistrationTemplate.PaymentReminderTimeSpan = nbPaymentReminderTimeSpan.Text.AsInteger(); RegistrationTemplate.RegistrationTerm = string.IsNullOrWhiteSpace( tbRegistrationTerm.Text ) ? "Registration" : tbRegistrationTerm.Text; RegistrationTemplate.RegistrantTerm = string.IsNullOrWhiteSpace( tbRegistrantTerm.Text ) ? "Registrant" : tbRegistrantTerm.Text; RegistrationTemplate.FeeTerm = string.IsNullOrWhiteSpace( tbFeeTerm.Text ) ? "Additional Options" : tbFeeTerm.Text; RegistrationTemplate.DiscountCodeTerm = string.IsNullOrWhiteSpace( tbDiscountCodeTerm.Text ) ? "Discount Code" : tbDiscountCodeTerm.Text; RegistrationTemplate.SuccessTitle = tbSuccessTitle.Text; RegistrationTemplate.SuccessText = ceSuccessText.Text; if ( !Page.IsValid || !RegistrationTemplate.IsValid ) { return; } foreach ( var form in FormState ) { if ( !form.IsValid ) { return; } if ( FormFieldsState.ContainsKey( form.Guid ) ) { foreach( var formField in FormFieldsState[ form.Guid ]) { if ( !formField.IsValid ) { return; } } } } // Get the valid group member attributes var group = new Group(); group.GroupTypeId = gtpGroupType.SelectedGroupTypeId ?? 0; var groupMember = new GroupMember(); groupMember.Group = group; groupMember.LoadAttributes(); var validGroupMemberAttributeIds = groupMember.Attributes.Select( a => a.Value.Id ).ToList(); // Remove any group member attributes that are not valid based on selected group type foreach( var fieldList in FormFieldsState.Select( s => s.Value ) ) { foreach( var formField in fieldList .Where( a => a.FieldSource == RegistrationFieldSource.GroupMemberAttribute && a.AttributeId.HasValue && !validGroupMemberAttributeIds.Contains( a.AttributeId.Value ) ) .ToList() ) { fieldList.Remove( formField ); } } // Perform Validation var validationErrors = new List<string>(); if ( ( ( RegistrationTemplate.SetCostOnInstance ?? false ) || RegistrationTemplate.Cost > 0 || FeeState.Any() ) && !RegistrationTemplate.FinancialGatewayId.HasValue ) { validationErrors.Add( "A Financial Gateway is required when the registration has a cost or additional fees or is configured to allow instances to set a cost." ); } if ( validationErrors.Any() ) { nbValidationError.Visible = true; nbValidationError.Text = "<ul class='list-unstyled'><li>" + validationErrors.AsDelimited( "</li><li>" ) + "</li></ul>"; } else { // Save the entity field changes to registration template if ( RegistrationTemplate.Id.Equals( 0 ) ) { service.Add( RegistrationTemplate ); } rockContext.SaveChanges(); var attributeService = new AttributeService( rockContext ); var registrationTemplateFormService = new RegistrationTemplateFormService( rockContext ); var registrationTemplateFormFieldService = new RegistrationTemplateFormFieldService( rockContext ); var registrationTemplateDiscountService = new RegistrationTemplateDiscountService( rockContext ); var registrationTemplateFeeService = new RegistrationTemplateFeeService( rockContext ); var registrationRegistrantFeeService = new RegistrationRegistrantFeeService( rockContext ); var groupService = new GroupService( rockContext ); // delete forms that aren't assigned in the UI anymore var formUiGuids = FormState.Select( f => f.Guid ).ToList(); foreach ( var form in registrationTemplateFormService .Queryable() .Where( f => f.RegistrationTemplateId == RegistrationTemplate.Id && !formUiGuids.Contains( f.Guid ) ) ) { foreach( var formField in form.Fields.ToList() ) { form.Fields.Remove( formField ); registrationTemplateFormFieldService.Delete( formField ); } registrationTemplateFormService.Delete( form ); } // delete fields that aren't assigned in the UI anymore var fieldUiGuids = FormFieldsState.SelectMany( a => a.Value).Select( f => f.Guid ).ToList(); foreach ( var formField in registrationTemplateFormFieldService .Queryable() .Where( a => formUiGuids.Contains( a.RegistrationTemplateForm.Guid ) && !fieldUiGuids.Contains( a.Guid ) ) ) { registrationTemplateFormFieldService.Delete( formField ); } // delete discounts that aren't assigned in the UI anymore var discountUiGuids = DiscountState.Select( u => u.Guid ).ToList(); foreach ( var discount in registrationTemplateDiscountService .Queryable() .Where( d => d.RegistrationTemplateId == RegistrationTemplate.Id && !discountUiGuids.Contains( d.Guid ) ) ) { registrationTemplateDiscountService.Delete( discount ); } // delete fees that aren't assigned in the UI anymore var feeUiGuids = FeeState.Select( u => u.Guid ).ToList(); var deletedfees = registrationTemplateFeeService .Queryable() .Where( d => d.RegistrationTemplateId == RegistrationTemplate.Id && !feeUiGuids.Contains( d.Guid ) ) .ToList(); var deletedFeeIds = deletedfees.Select( f => f.Id ).ToList(); foreach ( var registrantFee in registrationRegistrantFeeService .Queryable() .Where( f => deletedFeeIds.Contains( f.RegistrationTemplateFeeId ) ) .ToList() ) { registrationRegistrantFeeService.Delete( registrantFee ); } foreach ( var fee in deletedfees ) { registrationTemplateFeeService.Delete( fee ); } int? entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.RegistrationRegistrant ) ).Id; var qualifierColumn = "RegistrationTemplateId"; var qualifierValue = RegistrationTemplate.Id.ToString(); // Get the registration attributes still in the UI var attributesUI = FormFieldsState .SelectMany( s => s.Value.Where( a => a.FieldSource == RegistrationFieldSource.RegistrationAttribute && a.Attribute != null ) ) .Select( f => f.Attribute ) .ToList(); var selectedAttributeGuids = attributesUI.Select( a => a.Guid ); // Delete the registration attributes that were removed from the UI var attributesDB = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue ); foreach ( var attr in attributesDB.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ).ToList() ) { attributeService.Delete( attr ); Rock.Web.Cache.AttributeCache.Flush( attr.Id ); } rockContext.SaveChanges(); // Save all of the registration attributes still in the UI foreach ( var attr in attributesUI ) { Helper.SaveAttributeEdits( attr, entityTypeId, qualifierColumn, qualifierValue, rockContext ); } // add/updated forms/fields foreach ( var formUI in FormState ) { var form = RegistrationTemplate.Forms.FirstOrDefault( f => f.Guid.Equals( formUI.Guid ) ); if ( form == null ) { form = new RegistrationTemplateForm(); form.Guid = formUI.Guid; RegistrationTemplate.Forms.Add( form ); } form.Name = formUI.Name; form.Order = formUI.Order; if ( FormFieldsState.ContainsKey( form.Guid ) ) { foreach ( var formFieldUI in FormFieldsState[form.Guid] ) { var formField = form.Fields.FirstOrDefault( a => a.Guid.Equals( formFieldUI.Guid ) ); if ( formField == null ) { formField = new RegistrationTemplateFormField(); formField.Guid = formFieldUI.Guid; form.Fields.Add( formField ); } formField.AttributeId = formFieldUI.AttributeId; if ( !formField.AttributeId.HasValue && formFieldUI.FieldSource == RegistrationFieldSource.RegistrationAttribute && formFieldUI.Attribute != null ) { var attr = AttributeCache.Read( formFieldUI.Attribute.Guid, rockContext ); if ( attr != null ) { formField.AttributeId = attr.Id; } } formField.FieldSource = formFieldUI.FieldSource; formField.PersonFieldType = formFieldUI.PersonFieldType; formField.IsInternal = formFieldUI.IsInternal; formField.IsSharedValue = formFieldUI.IsSharedValue; formField.ShowCurrentValue = formFieldUI.ShowCurrentValue; formField.PreText = formFieldUI.PreText; formField.PostText = formFieldUI.PostText; formField.IsGridField = formFieldUI.IsGridField; formField.IsRequired = formFieldUI.IsRequired; formField.Order = formFieldUI.Order; } } } // add/updated discounts foreach ( var discountUI in DiscountState ) { var discount = RegistrationTemplate.Discounts.FirstOrDefault( a => a.Guid.Equals( discountUI.Guid ) ); if ( discount == null ) { discount = new RegistrationTemplateDiscount(); discount.Guid = discountUI.Guid; RegistrationTemplate.Discounts.Add( discount ); } discount.Code = discountUI.Code; discount.DiscountPercentage = discountUI.DiscountPercentage; discount.DiscountAmount = discountUI.DiscountAmount; discount.Order = discountUI.Order; } // add/updated fees foreach ( var feeUI in FeeState ) { var fee = RegistrationTemplate.Fees.FirstOrDefault( a => a.Guid.Equals( feeUI.Guid ) ); if ( fee == null ) { fee = new RegistrationTemplateFee(); fee.Guid = feeUI.Guid; RegistrationTemplate.Fees.Add( fee ); } fee.Name = feeUI.Name; fee.FeeType = feeUI.FeeType; fee.CostValue = feeUI.CostValue; fee.DiscountApplies = feeUI.DiscountApplies; fee.AllowMultiple = feeUI.AllowMultiple; fee.Order = feeUI.Order; } rockContext.SaveChanges(); AttributeCache.FlushEntityAttributes(); // If this is a new template, give the current user and the Registration Administrators role administrative // rights to this template, and staff, and staff like roles edit rights if ( newTemplate ) { RegistrationTemplate.AllowPerson( Authorization.ADMINISTRATE, CurrentPerson, rockContext ); var registrationAdmins = groupService.Get( Rock.SystemGuid.Group.GROUP_EVENT_REGISTRATION_ADMINISTRATORS.AsGuid() ); RegistrationTemplate.AllowSecurityRole( Authorization.ADMINISTRATE, registrationAdmins, rockContext ); var staffLikeUsers = groupService.Get( Rock.SystemGuid.Group.GROUP_STAFF_LIKE_MEMBERS.AsGuid() ); RegistrationTemplate.AllowSecurityRole( Authorization.EDIT, staffLikeUsers, rockContext ); var staffUsers = groupService.Get( Rock.SystemGuid.Group.GROUP_STAFF_MEMBERS.AsGuid() ); RegistrationTemplate.AllowSecurityRole( Authorization.EDIT, staffUsers, rockContext ); } var qryParams = new Dictionary<string, string>(); qryParams["RegistrationTemplateId"] = RegistrationTemplate.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); } }
/// <summary> /// Reads new values entered by the user for the field /// </summary> /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param> /// <param name="configurationValues"></param> /// <returns></returns> public override string GetEditValue( Control control, Dictionary<string, ConfigurationValue> configurationValues ) { var ids = new List<string>(); if ( control != null && control is ListControl ) { if ( control is Rock.Web.UI.Controls.RockDropDownList ) { ids.Add( ( (ListControl)control ).SelectedValue ); } else if ( control is Rock.Web.UI.Controls.RockCheckBoxList ) { var cblControl = control as Rock.Web.UI.Controls.RockCheckBoxList; ids.AddRange( cblControl.Items.Cast<ListItem>() .Where( i => i.Selected ) .Select( i => i.Value ) ); } } var guids = new List<string>(); foreach ( string id in ids ) { int definedValueId = int.MinValue; if ( int.TryParse( id, out definedValueId ) ) { var definedValue = Rock.Web.Cache.DefinedValueCache.Read( definedValueId ); if ( definedValue != null ) { guids.Add( definedValue.Guid.ToString() ); } } } return guids.AsDelimited( "," ); }
/// <summary> /// Finds the first group. /// </summary> /// <returns></returns> private Group FindFirstGroup() { // limit GroupType selection to what Block Attributes allow List<Guid> groupTypeGuids = GetAttributeValue( "GroupTypes" ).SplitDelimitedValues().Select( Guid.Parse ).ToList(); string groupTypeIds = "0"; if ( groupTypeGuids.Any() ) { var groupTypeIdList = new List<int>(); foreach ( Guid guid in groupTypeGuids ) { var groupType = GroupTypeCache.Read( guid ); if ( groupType != null ) { groupTypeIdList.Add( groupType.Id ); } } groupTypeIds = groupTypeIdList.AsDelimited( "," ); groupTypeIds = string.IsNullOrWhiteSpace( groupTypeIds ) ? "0" : groupTypeIds; } var groupService = new GroupService( new RockContext() ); var qry = groupService.GetNavigationChildren( 0, hfRootGroupId.ValueAsInt(), hfLimitToSecurityRoleGroups.Value.AsBoolean(), groupTypeIds ); foreach ( var group in qry.OrderBy( g => g.Name ) ) { // return first group they are authorized to view if ( group.IsAuthorized( Authorization.VIEW, CurrentPerson ) ) { return group; } } return null; }
private bool BindGrid( Grid grid, DataView dataView ) { var errors = new List<string>(); grid.DataSource = dataView.BindGrid( grid, out errors, true ); if ( grid.DataSource != null ) { if ( errors.Any() ) { nbEditModeMessage.Text = "INFO: There was a problem with one or more of the filters for this data view...<br/><br/> " + errors.AsDelimited( "<br/>" ); } if ( dataView.EntityTypeId.HasValue ) { grid.RowItemText = EntityTypeCache.Read( dataView.EntityTypeId.Value ).FriendlyName; } grid.DataBind(); return true; } return false; }
/// <summary> /// Binds the grid. /// </summary> protected void BindGrid() { AddScheduleColumns(); var rockContext = new RockContext(); var groupLocationService = new GroupLocationService( rockContext ); var groupTypeService = new GroupTypeService( rockContext ); var groupService = new GroupService( rockContext ); IEnumerable<GroupTypePath> groupPaths = new List<GroupTypePath>(); var groupLocationQry = groupLocationService.Queryable(); List<int> currentAndDescendantGroupTypeIds = new List<int>(); var currentGroupTypeIds = this.CurrentGroupTypeIds.ToList(); currentAndDescendantGroupTypeIds.AddRange( currentGroupTypeIds ); foreach ( var templateGroupType in groupTypeService.Queryable().Where( a => currentGroupTypeIds.Contains( a.Id ) ) ) { foreach ( var childGroupType in groupTypeService.GetChildGroupTypes( templateGroupType.Id ) ) { currentAndDescendantGroupTypeIds.Add( childGroupType.Id ); currentAndDescendantGroupTypeIds.AddRange( groupTypeService.GetAllAssociatedDescendents( childGroupType.Id ).Select( a => a.Id ).ToList() ); } } groupLocationQry = groupLocationQry.Where( a => currentAndDescendantGroupTypeIds.Contains( a.Group.GroupTypeId ) ); groupLocationQry = groupLocationQry.OrderBy( a => a.Group.Name ).ThenBy( a => a.Location.Name ); List<int> currentDeviceLocationIdList = this.GetGroupTypesLocations( rockContext ).Select( a => a.Id ).Distinct().ToList(); var qryList = groupLocationQry .Where( a => currentDeviceLocationIdList.Contains( a.LocationId ) ) .Select( a => new { GroupLocationId = a.Id, a.Location, GroupId = a.GroupId, GroupName = a.Group.Name, ScheduleIdList = a.Schedules.Select( s => s.Id ), GroupTypeId = a.Group.GroupTypeId } ).ToList(); var locationService = new LocationService( rockContext ); // put stuff in a datatable so we can dynamically have columns for each Schedule DataTable dataTable = new DataTable(); dataTable.Columns.Add( "GroupLocationId" ); dataTable.Columns.Add( "GroupId" ); dataTable.Columns.Add( "GroupName" ); dataTable.Columns.Add( "GroupPath" ); dataTable.Columns.Add( "LocationName" ); dataTable.Columns.Add( "LocationPath" ); foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() ) { dataTable.Columns.Add( field.DataField, typeof( bool ) ); } var locationPaths = new Dictionary<int, string>(); foreach ( var row in qryList ) { DataRow dataRow = dataTable.NewRow(); dataRow["GroupLocationId"] = row.GroupLocationId; dataRow["GroupName"] = groupService.GroupAncestorPathName( row.GroupId ); dataRow["GroupPath"] = groupPaths.Where( gt => gt.GroupTypeId == row.GroupTypeId ).Select( gt => gt.Path ).FirstOrDefault(); dataRow["LocationName"] = row.Location.Name; if ( row.Location.ParentLocationId.HasValue ) { int locationId = row.Location.ParentLocationId.Value; if ( !locationPaths.ContainsKey( locationId ) ) { var locationNames = new List<string>(); var parentLocation = locationService.Get( locationId ); while ( parentLocation != null ) { locationNames.Add( parentLocation.Name ); parentLocation = parentLocation.ParentLocation; } if ( locationNames.Any() ) { locationNames.Reverse(); locationPaths.Add( locationId, locationNames.AsDelimited( " > " ) ); } else { locationPaths.Add( locationId, string.Empty ); } } dataRow["LocationPath"] = locationPaths[locationId]; } foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() ) { int scheduleId = int.Parse( field.DataField.Replace( "scheduleField_", string.Empty ) ); dataRow[field.DataField] = row.ScheduleIdList.Any( a => a == scheduleId ); } dataTable.Rows.Add( dataRow ); } gGroupLocationSchedule.EntityTypeId = EntityTypeCache.Read<GroupLocation>().Id; gGroupLocationSchedule.DataSource = dataTable; gGroupLocationSchedule.DataBind(); }
// TODO: Add support for scanner private void SomeScannerSearch( DefinedValueCache searchType, string searchValue ) { CurrentCheckInState.CheckIn.UserEnteredSearch = false; CurrentCheckInState.CheckIn.ConfirmSingleFamily = false; CurrentCheckInState.CheckIn.SearchType = searchType; CurrentCheckInState.CheckIn.SearchValue = searchValue; var errors = new List<string>(); if ( ProcessActivity( "Family Search", out errors ) ) { SaveState(); NavigateToLinkedPage( "FamilySelectPage" ); } else { string errorMsg = "<ul><li>" + errors.AsDelimited( "</li><li>" ) + "</li></ul>"; maWarning.Show( errorMsg, Rock.Web.UI.Controls.ModalAlertType.Warning ); } }
/// <summary> /// Processes the payment information. /// </summary> /// <param name="errorMessage">The error message.</param> /// <returns></returns> private bool ProcessPaymentInfo( out string errorMessage ) { errorMessage = string.Empty; var errorMessages = new List<string>(); // Validate that an amount was entered if ( SelectedAccounts.Sum( a => a.Amount ) <= 0 ) { errorMessages.Add( "Make sure you've entered an amount for at least one account" ); } // Validate that no negative amounts were entered if ( SelectedAccounts.Any( a => a.Amount < 0 ) ) { errorMessages.Add( "Make sure the amount you've entered for each account is a positive amount" ); } // Get the payment schedule PaymentSchedule schedule = GetSchedule(); if ( schedule != null ) { // Make sure a repeating payment starts in the future if ( schedule.StartDate <= RockDateTime.Today ) { errorMessages.Add( "When scheduling a repeating payment, make sure the First Gift date is in the future (after today)" ); } } else { if ( dtpStartDate.SelectedDate < RockDateTime.Today ) { errorMessages.Add( "Make sure the date is not in the past" ); } } if ( txtFirstName.Visible == true ) { if ( string.IsNullOrWhiteSpace( txtFirstName.Text ) || string.IsNullOrWhiteSpace( txtLastName.Text ) ) { errorMessages.Add( "Make sure to enter both a first and last name" ); } } bool displayPhone = GetAttributeValue( "DisplayPhone" ).AsBoolean(); if ( displayPhone && string.IsNullOrWhiteSpace( pnbPhone.Number ) ) { errorMessages.Add( "Make sure to enter a valid phone number. A phone number is required for us to process this transaction" ); } bool displayEmail = GetAttributeValue( "DisplayEmail" ).AsBoolean(); if ( displayEmail && string.IsNullOrWhiteSpace( txtEmail.Text ) ) { errorMessages.Add( "Make sure to enter a valid email address. An email address is required for us to send you a payment confirmation" ); } var location = new Location(); acAddress.GetValues( location ); if ( string.IsNullOrWhiteSpace( location.Street1 ) ) { errorMessages.Add( "Make sure to enter a valid address. An address is required for us to process this transaction" ); } if ( !_using3StepGateway ) { if ( rblSavedAccount.Items.Count <= 0 || ( rblSavedAccount.SelectedValueAsInt() ?? 0 ) <= 0 ) { bool isACHTxn = hfPaymentTab.Value == "ACH"; if ( isACHTxn ) { // validate ach options if ( string.IsNullOrWhiteSpace( txtRoutingNumber.Text ) ) { errorMessages.Add( "Make sure to enter a valid routing number" ); } if ( string.IsNullOrWhiteSpace( txtAccountNumber.Text ) ) { errorMessages.Add( "Make sure to enter a valid account number" ); } } else { // validate cc options if ( _ccGatewayComponent.PromptForNameOnCard( _ccGateway ) ) { if ( _ccGatewayComponent != null && _ccGatewayComponent.SplitNameOnCard ) { if ( string.IsNullOrWhiteSpace( txtCardFirstName.Text ) || string.IsNullOrWhiteSpace( txtCardLastName.Text ) ) { errorMessages.Add( "Make sure to enter a valid first and last name as it appears on your credit card" ); } } else { if ( string.IsNullOrWhiteSpace( txtCardName.Text ) ) { errorMessages.Add( "Make sure to enter a valid name as it appears on your credit card" ); } } } var rgx = new System.Text.RegularExpressions.Regex( @"[^\d]" ); string ccNum = rgx.Replace( txtCreditCard.Text, "" ); if ( string.IsNullOrWhiteSpace( ccNum ) ) { errorMessages.Add( "Make sure to enter a valid credit card number" ); } var currentMonth = RockDateTime.Today; currentMonth = new DateTime( currentMonth.Year, currentMonth.Month, 1 ); if ( !mypExpiration.SelectedDate.HasValue || mypExpiration.SelectedDate.Value.CompareTo( currentMonth ) < 0 ) { errorMessages.Add( "Make sure to enter a valid credit card expiration date" ); } if ( string.IsNullOrWhiteSpace( txtCVV.Text ) ) { errorMessages.Add( "Make sure to enter a valid credit card security code" ); } } } } if ( errorMessages.Any() ) { errorMessage = errorMessages.AsDelimited( "<br/>" ); return false; } PaymentInfo paymentInfo = GetPaymentInfo(); if ( !phGiveAsOption.Visible || tglGiveAsOption.Checked ) { if ( txtCurrentName.Visible ) { Person person = GetPerson( false ); if ( person != null ) { paymentInfo.FirstName = person.FirstName; paymentInfo.LastName = person.LastName; } } else { paymentInfo.FirstName = txtFirstName.Text; paymentInfo.LastName = txtLastName.Text; } } else { paymentInfo.LastName = txtBusinessName.Text; } tdNameConfirm.Description = paymentInfo.FullName.Trim(); tdPhoneConfirm.Description = paymentInfo.Phone; tdEmailConfirm.Description = paymentInfo.Email; tdAddressConfirm.Description = string.Format( "{0} {1}, {2} {3}", paymentInfo.Street1, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode ); rptAccountListConfirmation.DataSource = SelectedAccounts.Where( a => a.Amount != 0 ); rptAccountListConfirmation.DataBind(); tdTotalConfirm.Description = paymentInfo.Amount.ToString( "C" ); if ( !_using3StepGateway ) { tdPaymentMethodConfirm.Description = paymentInfo.CurrencyTypeValue.Description; tdAccountNumberConfirm.Description = paymentInfo.MaskedNumber; tdAccountNumberConfirm.Visible = !string.IsNullOrWhiteSpace( paymentInfo.MaskedNumber ); } tdWhenConfirm.Description = schedule != null ? schedule.ToString() : "Today"; btnConfirmationPrev.Visible = !_using3StepGateway; return true; }
/// <summary> /// Binds the grid. /// </summary> /// <param name="grid">The grid.</param> /// <param name="dataView">The data view.</param> /// <returns></returns> private bool BindGrid( Grid grid, DataView dataView, int? fetchRowCount = null ) { var errorMessages = new List<string>(); grid.DataSource = null; if ( dataView.EntityTypeId.HasValue ) { var cachedEntityType = EntityTypeCache.Read( dataView.EntityTypeId.Value ); if ( cachedEntityType != null && cachedEntityType.AssemblyName != null ) { Type entityType = cachedEntityType.GetEntityType(); if ( entityType != null ) { grid.CreatePreviewColumns( entityType ); var qry = dataView.GetQuery( grid.SortProperty, out errorMessages ); if ( fetchRowCount.HasValue ) { qry = qry.Take( fetchRowCount.Value ); } grid.DataSource = qry.AsNoTracking().ToList(); } } } if ( grid.DataSource != null ) { grid.ExportFilename = dataView.Name; if ( errorMessages.Any() ) { nbEditModeMessage.Text = "INFO: There was a problem with one or more of the filters for this data view...<br/><br/> " + errorMessages.AsDelimited( "<br/>" ); } if ( dataView.EntityTypeId.HasValue ) { grid.RowItemText = EntityTypeCache.Read( dataView.EntityTypeId.Value ).FriendlyName; } grid.DataBind(); return true; } return false; }
/// <summary> /// Registers the java script. /// </summary> protected virtual void RegisterJavaScript() { var metric = new Rock.Model.MetricService( new Rock.Data.RockContext() ).Get( this.MetricId ?? 0 ); if ( string.IsNullOrWhiteSpace( this.XAxisLabel ) && metric != null ) { // if XAxisLabel hasn't been set, and this is a metric, automatically set it to the metric.XAxisLabel this.XAxisLabel = metric.XAxisLabel; } if ( string.IsNullOrWhiteSpace( this.YAxisLabel ) && metric != null ) { // if YAxisLabel hasn't been set, and this is a metric, automatically set it to the metric.YAxisLabel this.YAxisLabel = metric.YAxisLabel; } // setup Rest URL parameters if ( this.MetricId.HasValue ) { _hfRestUrlParams.Value = string.Format( "{0}", this.MetricId ); List<string> filterParams = new List<string>(); List<string> qryParams = new List<string>(); if ( this.StartDate.HasValue ) { filterParams.Add( string.Format( "MetricValueDateTime ge DateTime'{0}'", this.StartDate.Value.ToString( "o" ) ) ); } if ( this.EndDate.HasValue ) { filterParams.Add( string.Format( "MetricValueDateTime lt DateTime'{0}'", this.EndDate.Value.ToString( "o" ) ) ); } if ( this.MetricValueType.HasValue ) { // MetricValueType is an enum, which isn't quite supported for $filters as of Web Api 2.1, so pass it as a regular rest param instead of as part of the odata $filter qryParams.Add( string.Format( "metricValueType={0}", this.MetricValueType ) ); } if ( this.EntityId.HasValue ) { filterParams.Add( string.Format( "(EntityId eq {0} or EntityId eq null)", this.EntityId ) ); } if ( filterParams.Count > 0 ) { qryParams.Add( "$filter=" + filterParams.AsDelimited( " and " ) ); } _hfRestUrlParams.Value += "?" + qryParams.AsDelimited( "&" ); } else { _hfRestUrlParams.Value = string.Empty; } string scriptFormat = @" var restUrl_{0} = $('#{0} .js-rest-url').val() + $('#{0} .js-rest-url-params').val(); $.ajax({{ url: restUrl_{0}, dataType: 'json', contentType: 'application/json' }}) .done( function (chartData) {{ var chartOptions = {1}; var plotSelector = '#{0} .js-chart-placeholder'; var yaxisLabelText = $('#{0} .js-yaxis-value').val(); var getSeriesUrl = $('#{0} .js-seriesname-url').val(); var combineValues = {4}; "; if ( this.GetType() == typeof( PieChart ) ) { scriptFormat += @" Rock.controls.charts.plotPieChartData(chartData, chartOptions, plotSelector); "; } else { scriptFormat += @" Rock.controls.charts.plotChartData(chartData, chartOptions, plotSelector, yaxisLabelText, getSeriesUrl, combineValues); "; } scriptFormat += @" // plothover script (tooltip script) {2} // plotclick script {3} }}) .fail(function (jqXHR, textStatus, errorThrown) {{ //debugger }}); "; string chartOptionsJson = JsonConvert.SerializeObject( this.Options, Formatting.Indented, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore } ); _hbChartOptions.Text = "<div style='white-space: pre; max-height: 120px; overflow-y:scroll' Font-Names='Consolas' Font-Size='8'><br />" + chartOptionsJson + "</div>"; string restUrl = this.ResolveUrl( this.DataSourceUrl ); _hfRestUrl.Value = restUrl; var seriesNameUrl = this.SeriesNameUrl; if ( this.MetricId.HasValue ) { seriesNameUrl = seriesNameUrl ?? "~/api/MetricValues/GetSeriesName/"; } if ( !string.IsNullOrWhiteSpace( seriesNameUrl ) ) { _hfSeriesNameUrl.Value = this.ResolveUrl( seriesNameUrl.EnsureTrailingForwardslash() + this.MetricId + "/" ); } else { _hfSeriesNameUrl.Value = null; } string tooltipScript = ShowTooltip ? string.Format( "Rock.controls.charts.bindTooltip('{0}', {1})", this.ClientID, this.TooltipFormatter ?? "null" ) : null; string chartClickScript = GetChartClickScript(); string script = string.Format( scriptFormat, this.ClientID, // {0} chartOptionsJson, // {1} tooltipScript, // {2} chartClickScript, // {3} this.CombineValues.ToTrueFalse().ToLower() ); // {4} ScriptManager.RegisterStartupScript( this, this.GetType(), "flot-chart-script_" + this.ClientID, script, true ); }
/// <summary> /// Shows the readonly details. /// </summary> /// <param name="connectionRequest">The connection request.</param> private void ShowReadonlyDetails( ConnectionRequest connectionRequest ) { pdAuditDetails.SetEntity( connectionRequest, ResolveRockUrl( "~" ) ); if ( connectionRequest.AssignedGroupId != null ) { pnlRequirements.Visible = true; ShowConnectionOpportunityRequirementsStatuses(); } else { pnlRequirements.Visible = false; lbConnect.Enabled = !connectionRequest.ConnectionOpportunity.ConnectionType.RequiresPlacementGroupToConnect; } if ( connectionRequest.ConnectionState == ConnectionState.Inactive || connectionRequest.ConnectionState == ConnectionState.Connected ) { lbConnect.Visible = false; lbTransfer.Visible = false; } lContactInfo.Text = string.Empty; Person person = null; if ( connectionRequest != null && connectionRequest.PersonAlias != null ) { person = connectionRequest.PersonAlias.Person; } if ( person != null && ( person.PhoneNumbers.Any() || !String.IsNullOrWhiteSpace( person.Email ) ) ) { List<String> contactList = new List<string>(); foreach ( PhoneNumber phoneNumber in person.PhoneNumbers ) { contactList.Add( String.Format( "{0} <font color='#808080'>{1}</font>", phoneNumber.NumberFormatted, phoneNumber.NumberTypeValue ) ); } string emailTag = person.GetEmailTag( ResolveRockUrl( "/" ) ); if ( !string.IsNullOrWhiteSpace( emailTag ) ) { contactList.Add( emailTag ); } lContactInfo.Text = contactList.AsDelimited( "</br>" ); } else { lContactInfo.Text = "No contact Info"; } if ( person != null && !string.IsNullOrWhiteSpace( GetAttributeValue( "PersonProfilePage" ) ) ) { lbProfilePage.Visible = true; Dictionary<string, string> queryParms = new Dictionary<string, string>(); queryParms.Add( "PersonId", person.Id.ToString() ); lbProfilePage.PostBackUrl = LinkedPageUrl( "PersonProfilePage", queryParms ); } else { lbProfilePage.Visible = false; } if ( person != null ) { string imgTag = Rock.Model.Person.GetPersonPhotoImageTag( person, 200, 200, className: "img-thumbnail" ); if ( person.PhotoId.HasValue ) { lPortrait.Text = string.Format( "<a href='{0}'>{1}</a>", person.PhotoUrl, imgTag ); } else { lPortrait.Text = imgTag; } } else { lPortrait.Text = string.Empty; ; } lComments.Text = connectionRequest != null && connectionRequest.Comments != null ? connectionRequest.Comments.ScrubHtmlAndConvertCrLfToBr() : string.Empty; lRequestDate.Text = connectionRequest != null && connectionRequest.CreatedDateTime.HasValue ? connectionRequest.CreatedDateTime.Value.ToShortDateString() : string.Empty; if ( connectionRequest != null && connectionRequest.AssignedGroup != null ) { var qryParams = new Dictionary<string, string>(); qryParams.Add( "GroupId", connectionRequest.AssignedGroup.Id.ToString() ); string url = LinkedPageUrl( "GroupDetailPage", qryParams ); string roleStatus = string.Empty; string roleName = string.Empty; if ( connectionRequest.AssignedGroupMemberRoleId.HasValue ) { var role = new GroupTypeRoleService( new RockContext() ).Get( connectionRequest.AssignedGroupMemberRoleId.Value ); roleName = role != null ? role.Name : string.Empty; } string statusName = connectionRequest.AssignedGroupMemberStatus != null ? connectionRequest.AssignedGroupMemberStatus.ConvertToString() : string.Empty; if ( !string.IsNullOrWhiteSpace( roleName ) || !string.IsNullOrWhiteSpace( statusName ) ) { roleStatus = string.Format( " ({0}{1}{2})", statusName, !string.IsNullOrWhiteSpace( roleName ) && !string.IsNullOrWhiteSpace( statusName ) ? " " : "", roleName ); } lPlacementGroup.Text = !string.IsNullOrWhiteSpace( url ) ? string.Format( "<a href='{0}'>{1}</a>{2}", url, connectionRequest.AssignedGroup.Name, roleStatus ) : connectionRequest.AssignedGroup.Name; hfGroupMemberAttributeValues.Value = connectionRequest.AssignedGroupMemberAttributeValues; BuildGroupMemberAttributes( connectionRequest.AssignedGroupId, connectionRequest.AssignedGroupMemberRoleId, connectionRequest.AssignedGroupMemberStatus, true ); } else { lPlacementGroup.Text = "No group assigned"; } if ( connectionRequest != null && connectionRequest.ConnectorPersonAlias != null && connectionRequest.ConnectorPersonAlias.Person != null ) { lConnector.Text = connectionRequest.ConnectorPersonAlias.Person.FullName; } else { lConnector.Text = "No connector assigned"; } if ( connectionRequest != null ) { hlState.Visible = true; hlState.Text = connectionRequest.ConnectionState.ConvertToString(); hlState.LabelType = connectionRequest.ConnectionState == ConnectionState.Inactive ? LabelType.Danger : ( connectionRequest.ConnectionState == ConnectionState.FutureFollowUp ? LabelType.Info : LabelType.Success ); hlStatus.Visible = true; hlStatus.Text = connectionRequest.ConnectionStatus.Name; hlStatus.LabelType = connectionRequest.ConnectionStatus.IsCritical ? LabelType.Warning : LabelType.Type; hlOpportunity.Text = connectionRequest.ConnectionOpportunity != null ? connectionRequest.ConnectionOpportunity.Name : string.Empty; hlCampus.Text = connectionRequest.Campus != null ? connectionRequest.Campus.Name : string.Empty; if ( connectionRequest.ConnectionOpportunity != null ) { var connectionWorkflows = connectionRequest.ConnectionOpportunity.ConnectionWorkflows.Union( connectionRequest.ConnectionOpportunity.ConnectionType.ConnectionWorkflows ); var manualWorkflows = connectionWorkflows .Where( w => w.TriggerType == ConnectionWorkflowTriggerType.Manual && w.WorkflowType != null ) .OrderBy( w => w.WorkflowType.Name ) .Distinct(); if ( manualWorkflows.Any() ) { lblWorkflows.Visible = true; rptRequestWorkflows.DataSource = manualWorkflows.ToList(); rptRequestWorkflows.DataBind(); } else { lblWorkflows.Visible = false; } } BindConnectionRequestActivitiesGrid( connectionRequest, new RockContext() ); BindConnectionRequestWorkflowsGrid(); } else { hlState.Visible = false; hlStatus.Visible = false; hlOpportunity.Visible = false; hlCampus.Visible = false; lblWorkflows.Visible = false; lbConnect.Enabled = false; } }