/// <summary> /// Gets the filter value control. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id">The identifier.</param> /// <param name="required">if set to <c>true</c> [required].</param> /// <param name="filterMode">The filter mode.</param> /// <returns></returns> public override Control FilterValueControl(Dictionary <string, ConfigurationValue> configurationValues, string id, bool required, FilterMode filterMode) { var dateFiltersPanel = new Panel(); dateFiltersPanel.ID = string.Format("{0}_dtFilterControls", id); var datePickerPanel = new Panel(); dateFiltersPanel.Controls.Add(datePickerPanel); var datePickerControlType = configurationValues?.GetValueOrNull("datePickerControlType").ConvertToEnumOrNull <DatePickerControlType>() ?? DatePickerControlType.DatePicker; switch (datePickerControlType) { case DatePickerControlType.DatePartsPicker: var datePartsPicker = new DatePartsPicker { ID = id }; datePartsPicker.ID = string.Format("{0}_dtPicker", id); datePartsPicker.FutureYearCount = configurationValues?.GetValueOrNull("futureYearCount").AsIntegerOrNull(); datePickerPanel.AddCssClass("js-filter-control"); datePickerPanel.Controls.Add(datePartsPicker); break; case DatePickerControlType.DatePicker: default: var datePicker = new DatePicker(); datePicker.ID = string.Format("{0}_dtPicker", id); datePicker.DisplayCurrentOption = true; datePickerPanel.AddCssClass("js-filter-control"); datePickerPanel.Controls.Add(datePicker); break; } var slidingDateRangePicker = new SlidingDateRangePicker(); slidingDateRangePicker.ID = string.Format("{0}_dtSlidingDateRange", id); slidingDateRangePicker.AddCssClass("js-filter-control-between"); slidingDateRangePicker.Label = string.Empty; slidingDateRangePicker.PreviewLocation = SlidingDateRangePicker.DateRangePreviewLocation.Right; dateFiltersPanel.Controls.Add(slidingDateRangePicker); return(dateFiltersPanel); }
/// <summary> /// Validate that Put or Patch long running operations must have valid terminal status code 200 or 201. /// </summary> /// <param name="responses">Dictionary of responses for the operation.</param> /// <returns><c>true</c> if at least one valid terminal status code availabe, otherwise <c>false</c>.</returns> private static bool IsPutPatchResponseCodesValid(Dictionary <string, OperationResponse> responses) { OperationResponse response200 = responses?.GetValueOrNull("200"); OperationResponse response201 = responses?.GetValueOrNull("201"); if (response200 == null && response201 == null) { return(false); } if (response200 == null && response201 == null) { return(false); } return(true); }
public Task Defer(DateTimeOffset approximateDueTime, Dictionary<string, string> headers, byte[] body) { var messageIdToPrint = headers.GetValueOrNull(Headers.MessageId) ?? "<no message ID>"; var message = $"Received message with ID {messageIdToPrint} which is supposed to be deferred until {approximateDueTime} -" + " this is a problem, because the internal handling of deferred messages is" + " disabled when using SQS as the transport layer in, which" + " case the native support for a specific future enqueueing time is used..."; throw new InvalidOperationException(message); }
public async Task Defer(DateTimeOffset approximateDueTime, Dictionary<string, string> headers, byte[] body) { var messageIdToPrint = headers.GetValueOrNull(Headers.MessageId) ?? "<no message ID>"; var message = string.Format("Received message with ID {0} which is supposed to be deferred until {1} -" + " this is a problem, because the internal handling of deferred messages is" + " disabled when using Azure Storage Queues as the transport layer in, which" + " case the native support for a specific initial visibility delay is used...", messageIdToPrint, approximateDueTime); throw new InvalidOperationException(message); }
/// <summary> /// Creates the control(s) necessary for prompting user for a new value /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id"></param> /// <returns> /// The control /// </returns> public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id) { var datePickerControlType = configurationValues?.GetValueOrNull("datePickerControlType").ConvertToEnumOrNull <DatePickerControlType>() ?? DatePickerControlType.DatePicker; switch (datePickerControlType) { case DatePickerControlType.DatePartsPicker: var datePartsPicker = new DatePartsPicker { ID = id }; datePartsPicker.FutureYearCount = configurationValues?.GetValueOrNull("futureYearCount").AsIntegerOrNull(); return(datePartsPicker); case DatePickerControlType.DatePicker: default: var datePicker = new DatePicker { ID = id }; datePicker.DisplayCurrentOption = configurationValues?.GetValueOrNull("displayCurrentOption")?.AsBooleanOrNull() ?? false; return(datePicker); } }
/// <summary> /// Validate that Post long running operations must have valid terminal status code 200, 201 or 204. /// </summary> /// <param name="responses">Dictionary of responses for the operation.</param> /// <returns><c>true</c> if at least one valid terminal status code availabe, otherwise <c>false</c>.</returns> private static bool IsPostResponseCodesValid(Dictionary <string, OperationResponse> responses) { if (!IsPutPatchResponseCodesValid(responses)) { OperationResponse response204 = responses?.GetValueOrNull("204"); if (response204 == null) { return(false); } } return(true); }
/// <summary> /// Gets the filter value control. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id">The identifier.</param> /// <param name="required">if set to <c>true</c> [required].</param> /// <param name="filterMode">The filter mode.</param> /// <returns></returns> public override Control FilterValueControl(Dictionary <string, ConfigurationValue> configurationValues, string id, bool required, FilterMode filterMode) { var configurationJSON = configurationValues.GetValueOrNull(ConfigurationKey.ConfigurationJSON); List <ConditionalScaleRangeRule> conditionalScaleRangeRuleList = configurationJSON.FromJsonOrNull <List <ConditionalScaleRangeRule> >() ?? new List <ConditionalScaleRangeRule>(); var cblRangeRules = new RockCheckBoxList { ID = $"cblRangeRules_{id}", RepeatDirection = RepeatDirection.Horizontal }; cblRangeRules.AddCssClass("js-filter-control").AddCssClass("checkboxlist-group"); foreach (var conditionalScaleRangeRule in conditionalScaleRangeRuleList.OrderBy(a => a.RangeIndex)) { cblRangeRules.Items.Add(new ListItem(conditionalScaleRangeRule.Label, conditionalScaleRangeRule.Guid.ToString())); } return(cblRangeRules); }
/// <summary> /// Gets the type of the entity cache associated with this EntityType (if applicable) /// </summary> /// <returns></returns> public Type GetEntityCacheType() { if (_cacheableEntityTypeIds == null) { _cacheableEntityTypeIds = Reflection.FindTypes(typeof(IEntityCache)).Values .Select(a => new { CacheTypeType = a.BaseType.GenericTypeArguments[0], EntityTypeType = a.BaseType.GenericTypeArguments[1] }) .ToDictionary(k => EntityTypeCache.Get(k.EntityTypeType).Id, v => v.CacheTypeType); } var entityCacheType = _cacheableEntityTypeIds?.GetValueOrNull(this.Id); return(entityCacheType); }
/// <summary> /// Formats the filter values. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="filterValues">The filter values.</param> /// <returns></returns> public override string FormatFilterValues(Dictionary <string, ConfigurationValue> configurationValues, List <string> filterValues) { if (filterValues.Count < 2) { return(string.Empty); } var filterCompareType = filterValues[0]; var filterCompareValues = filterValues[1].FromJsonOrNull <List <Guid> >() ?? new List <Guid>(); var configurationJSON = configurationValues.GetValueOrNull(ConfigurationKey.ConfigurationJSON); List <ConditionalScaleRangeRule> conditionalScaleRangeRuleList = configurationJSON.FromJsonOrNull <List <ConditionalScaleRangeRule> >() ?? new List <ConditionalScaleRangeRule>(); var selectedLabels = conditionalScaleRangeRuleList.Where(a => filterCompareValues.Contains(a.Guid)).Select(a => a.Label).ToList(); var selectLabelsText = selectedLabels.AsDelimited("' OR '"); return("Is " + AddQuotes(selectLabelsText)); }
/// <summary> /// Gets the type of the entity cache associated with this EntityType (if applicable) /// </summary> /// <returns></returns> public Type GetEntityCacheType() { if (_cachedEntityTypeByEntityType == null) { _cachedEntityTypeByEntityType = Reflection.FindTypes(typeof(IEntityCache)).Values .Select(a => new { CacheTypeType = a.BaseType.GenericTypeArguments[0], EntityTypeType = a.BaseType.GenericTypeArguments[1] }) .ToDictionary(k => k.EntityTypeType.FullName, v => v.CacheTypeType); } var entityCacheType = _cachedEntityTypeByEntityType?.GetValueOrNull(this.Name); return(entityCacheType); }
/// <summary> /// Sets the configuration value. /// </summary> /// <param name="controls"></param> /// <param name="configurationValues"></param> public override void SetConfigurationValues(List <Control> controls, Dictionary <string, ConfigurationValue> configurationValues) { if (controls != null && configurationValues != null) { DropDownList ddlDefinedType = controls.Count > 0 ? controls[0] as DropDownList : null; CheckBox cbAllowMultipleValues = controls.Count > 1 ? controls[1] as CheckBox : null; CheckBox cbDescription = controls.Count > 2 ? controls[2] as CheckBox : null; CheckBox cbEnhanced = controls.Count > 3 ? controls[3] as CheckBox : null; CheckBox cbIncludeInactive = controls.Count > 4 ? controls[4] as CheckBox : null; CheckBox cbAllowAddNewValues = controls.Count > 5 ? controls[5] as CheckBox : null; NumberBox nbRepeatColumns = controls.Count > 6 ? controls[6] as NumberBox : null; if (ddlDefinedType != null) { ddlDefinedType.SelectedValue = configurationValues.GetValueOrNull(DEFINED_TYPE_KEY); } if (cbAllowMultipleValues != null) { cbAllowMultipleValues.Checked = configurationValues.GetValueOrNull(ALLOW_MULTIPLE_KEY).AsBooleanOrNull() ?? false; } if (cbDescription != null) { cbDescription.Checked = configurationValues.GetValueOrNull(DISPLAY_DESCRIPTION).AsBooleanOrNull() ?? false; } if (cbEnhanced != null) { cbEnhanced.Checked = configurationValues.GetValueOrNull(ENHANCED_SELECTION_KEY).AsBooleanOrNull() ?? false; } if (cbIncludeInactive != null) { cbIncludeInactive.Checked = configurationValues.GetValueOrNull(INCLUDE_INACTIVE_KEY).AsBooleanOrNull() ?? false; } if (cbAllowAddNewValues != null) { cbAllowAddNewValues.Checked = configurationValues.GetValueOrNull(ALLOW_ADDING_NEW_VALUES_KEY).AsBooleanOrNull() ?? false; } if (nbRepeatColumns != null) { nbRepeatColumns.Text = configurationValues.GetValueOrNull(REPEAT_COLUMNS_KEY); } } }
private ITypeIO Create(Type type) { var ioAttr = type.GetCustomAttribute <Attributes.IOAttribute>(); if (ioAttr != null) { var io = (ITypeIO)Activator.CreateInstance(ioAttr.IOType); Add(type, io); return(io); } if (type.IsEnum) { var io = PrimitiveIOs[type.GetEnumUnderlyingType()]; Add(type, io); return(io); } if (type.IsCollection()) { var elementType = type.GetCollectionElementType(); // Check element type exist var io = ListElementMap.GetValueOrNull(elementType); if (io != null) { Add(type, io); } else { io = new ListIO(elementType, this); Add(type, io); ListElementMap.Add(elementType, io); } return(io); } var cio = new CompositeTypeIO(type); Add(type, cio); cio.Init(this); return(cio); }
public virtual AcquiredJobs Execute(CommandContext commandContext) { AcquiredJobs = new AcquiredJobs(NumJobsToAcquire); if (!_isRunning) { _isRunning = true; IList <JobEntity> jobs = commandContext.JobManager.FindNextJobsToExecute(new Page(0, NumJobsToAcquire)); IDictionary <string, IList <string> > exclusiveJobsByProcessInstance = new Dictionary <string, IList <string> >(); foreach (var job in jobs) { LockJob(job); if (job.Exclusive) { // java中null值可以作为字典的key var list = exclusiveJobsByProcessInstance.GetValueOrNull(job.ProcessInstanceId ?? "null"); if (list == null) { list = new List <string>(); exclusiveJobsByProcessInstance[job.ProcessInstanceId ?? "null"] = list; } list.Add(job.Id); } else { AcquiredJobs.AddJobIdBatch(job.Id); } } foreach (var jobIds in exclusiveJobsByProcessInstance.Values) { AcquiredJobs.AddJobIdBatch(jobIds); } // register an OptimisticLockingListener which is notified about jobs which cannot be acquired. // the listener removes them from the list of acquired jobs. commandContext.RegisterOptimisticLockingListener(this); _isRunning = false; } return(AcquiredJobs); }
private static List <ShaderSerializedProperty> AsList(Material material, SerializedObject so, SerializedProperty parent, Dictionary <string, ShaderMaterialProperty> matProps) { var result = new List <ShaderSerializedProperty>(); if (parent != null) { for (int i = 0; i < parent.arraySize; i++) { var prop = parent.GetArrayElementAtIndex(i); var name = GetSerializedName(prop); if (name != null) { result.Add(new ShaderSerializedProperty(name, matProps.GetValueOrNull(name), so, parent, prop)); } } } return(result); }
/// <summary> /// Get an instance of a Lava service component of the specified type. /// </summary> /// <param name="serviceType"></param> /// <param name="configuration"></param> /// <returns></returns> public ILavaService GetService(Type serviceType, object configuration = null) { var factoryFunc = _services.GetValueOrNull(serviceType); if (factoryFunc == null) { throw new LavaException($"GetService failed. The service type \"{ serviceType.FullName }\" is not registered."); } var service = factoryFunc(serviceType, configuration); if (service == null) { throw new LavaException($"GetService failed. The service type \"{ serviceType.FullName }\" could not be created."); } return(service); }
static int GetMessagePriority(Dictionary <string, string> headers) { var valueOrNull = headers.GetValueOrNull(MessagePriorityHeaderKey); if (valueOrNull == null) { return(0); } try { return(int.Parse(valueOrNull)); } catch (Exception exception) { throw new FormatException($"Could not parse '{valueOrNull}' into an Int32!", exception); } }
/// <summary> /// Gets a filter expression for an entity property value. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="filterValues">The filter values.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="propertyType">Type of the property.</param> /// <returns></returns> public override Expression PropertyFilterExpression(Dictionary <string, ConfigurationValue> configurationValues, List <string> filterValues, Expression parameterExpression, string propertyName, Type propertyType) { if (filterValues.Count < 2) { return(null); } var filterCompareValues = filterValues[1].FromJsonOrNull <List <Guid> >() ?? new List <Guid>(); var configurationJSON = configurationValues.GetValueOrNull(ConfigurationKey.ConfigurationJSON); List <ConditionalScaleRangeRule> conditionalScaleRangeRuleList = configurationJSON.FromJsonOrNull <List <ConditionalScaleRangeRule> >() ?? new List <ConditionalScaleRangeRule>(); MemberExpression propertyExpression = Expression.Property(parameterExpression, propertyName); Expression rangeComparison = null; var conditionalScaleRangeRuleListToFilter = conditionalScaleRangeRuleList.Where(a => filterCompareValues.Contains(a.Guid)).ToList(); foreach (var conditionalScaleRangeRule in conditionalScaleRangeRuleListToFilter) { decimal lowValue = conditionalScaleRangeRule.LowValue ?? decimal.MinValue; decimal highValue = conditionalScaleRangeRule.HighValue ?? decimal.MaxValue; ConstantExpression constantExpressionLowValue = Expression.Constant(lowValue, typeof(decimal)); ConstantExpression constantExpressionHighValue = Expression.Constant(highValue, typeof(decimal)); var rangeBetweenExpression = ComparisonHelper.ComparisonExpression(ComparisonType.Between, propertyExpression, constantExpressionLowValue, constantExpressionHighValue); if (rangeComparison == null) { rangeComparison = rangeBetweenExpression; } else { rangeComparison = Expression.Or(rangeComparison, rangeBetweenExpression); } } var notNullComparison = ComparisonHelper.ComparisonExpression(ComparisonType.IsNotBlank, propertyExpression, AttributeConstantExpression(string.Empty)); var expression = Expression.AndAlso(notNullComparison, rangeComparison); return(expression); }
/// <summary> /// An <paramref name="operationDefinition"/> fails this rule if delete operation does not have an empty request body. /// </summary> /// <param name="operationDefinition">Operation Definition to validate</param> /// <returns>true if delete operation does not have a body. false otherwise.</returns> public override bool IsValid(Dictionary <string, Operation> operationDefinition, RuleContext context) { foreach (string httpVerb in operationDefinition.Keys) { if (httpVerb.ToLower().Equals("delete")) { Operation operation = operationDefinition.GetValueOrNull(httpVerb); if (operation == null) { return(false); } if (operation.Parameters == null) { continue; } foreach (SwaggerParameter parameter in operation.Parameters) { if (parameter.Reference == null) { if (parameter.In == ParameterLocation.Body) { return(false); } } else { if (context == null || context.Root == null) { return(false); } if (this.GetParameterLocation(parameter, (ServiceDefinition)context.Root) == ParameterLocation.Body) { return(false); } } } } } return(true); }
/// <summary> /// Validates if the name of property and x-ms-client-name(if exists) does not match. /// </summary> /// <param name="definitions">Operation Definition to validate</param> /// <returns>true if the validation succeeds. false otherwise.</returns> public override bool IsValid(Dictionary <string, Schema> definitions) { foreach (string key in definitions.Keys) { Schema schema = definitions.GetValueOrNull(key); if (schema != null) { if (schema.Extensions != null && schema.Extensions.Count != 0) { string valueToCompare = (string)schema.Extensions.GetValueOrNull(extensionToCheck); if (valueToCompare != null && valueToCompare.Equals(key)) { return(false); } } } } return(true); }
/// <summary> /// Handles the ItemDataBound event of the rptCommunicationLists control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param> protected void rptCommunicationLists_ItemDataBound(object sender, RepeaterItemEventArgs e) { var group = e.Item.DataItem as Rock.Model.Group; if (group != null) { var hfGroupId = e.Item.FindControl("hfGroupId") as HiddenField; var cbCommunicationListIsSubscribed = e.Item.FindControl("cbCommunicationListIsSubscribed") as RockCheckBox; var tglCommunicationPreference = e.Item.FindControl("tglCommunicationPreference") as Toggle; hfGroupId.Value = group.Id.ToString(); cbCommunicationListIsSubscribed.Text = group.GetAttributeValue("PublicName"); var groupMember = personCommunicationListsMember.GetValueOrNull(group.Id); if (cbCommunicationListIsSubscribed.Text.IsNullOrWhiteSpace()) { cbCommunicationListIsSubscribed.Text = group.Name; } cbCommunicationListIsSubscribed.Checked = groupMember != null && groupMember.GroupMemberStatus == GroupMemberStatus.Active; CommunicationType communicationType = CurrentPerson.CommunicationPreference == CommunicationType.SMS ? CommunicationType.SMS : CommunicationType.Email; if (groupMember != null) { groupMember.LoadAttributes(); var groupMemberCommunicationType = ( CommunicationType? )groupMember.GetAttributeValue("PreferredCommunicationMedium").AsIntegerOrNull(); if (groupMemberCommunicationType.HasValue) { // if GroupMember record has SMS or Email specified, that takes precedence over their Person.CommunicationPreference if (groupMemberCommunicationType.Value == CommunicationType.SMS) { communicationType = CommunicationType.SMS; } else if (groupMemberCommunicationType.Value == CommunicationType.Email) { communicationType = CommunicationType.Email; } } } tglCommunicationPreference.Checked = communicationType == CommunicationType.Email; tglCommunicationPreference.Visible = showMediumPreference; } }
/// <summary> /// Apply the filter settings to the filter controls. /// </summary> /// <param name="settingsKeyValueMap"></param> private void OnApplyFilterSettings(Dictionary <string, string> settingsKeyValueMap) { BindSitesFilter(); var dataContext = GetDataContext(); // Site int siteId = settingsKeyValueMap.GetValueOrDefault(FilterSettingName.Site, string.Empty).AsInteger(); if (siteId != 0) { if (ddlSite.Items.FindByValue(siteId.ToString()) != null) { ddlSite.SelectedValue = siteId.ToString(); } } // Page int pageId = settingsKeyValueMap.GetValueOrDefault(FilterSettingName.Page, string.Empty).AsInteger(); if (pageId != 0) { var pageService = new PageService(dataContext); var page = pageService.Get(pageId); ppPage.SetValue(page); } // User int userPersonId = settingsKeyValueMap.GetValueOrDefault(FilterSettingName.User, string.Empty).AsInteger(); if (userPersonId != 0) { var personService = new PersonService(dataContext); var person = personService.Get(userPersonId); ppUser.SetValue(person); } sdpDateRange.DelimitedValues = settingsKeyValueMap.GetValueOrNull(FilterSettingName.DateRange); }
/// <summary> /// An <paramref name="definitions"/> fails this rule if the resource definition does not have /// x-ms-azure-resource extension set to true. /// </summary> /// <param name="definitions">Operation Definition to validate</param> /// <returns>true if the validation succeeds. false otherwise.</returns> public override bool IsValid(Dictionary <string, Schema> definitions) { foreach (string key in definitions.Keys) { if (key.ToLower().Equals("resource")) { Schema resourceSchema = definitions.GetValueOrNull(key); if (resourceSchema == null || resourceSchema.Extensions == null || resourceSchema.Extensions.Count <= 0 || resourceSchema.Extensions.GetValueOrNull(requiredExtension) == null || (bool)resourceSchema.Extensions.GetValueOrNull(requiredExtension) == false) { return(false); } } } return(true); }
/// <summary> /// Sets the configuration value. /// </summary> /// <param name="controls"></param> /// <param name="configurationValues"></param> public override void SetConfigurationValues(List <Control> controls, Dictionary <string, ConfigurationValue> configurationValues) { base.SetConfigurationValues(controls, configurationValues); if (controls != null && controls.Count > 3 && configurationValues != null) { var tbValues = controls[0] as RockTextBox; var cbEnhanced = controls[1] as RockCheckBox; var tbRepeatColumns = controls[2] as NumberBox; var ddlRepeatDirection = controls[3] as RockDropDownList; tbValues.Text = configurationValues.ContainsKey(VALUES_KEY) ? configurationValues[VALUES_KEY].Value : string.Empty; cbEnhanced.Checked = configurationValues.ContainsKey(ENHANCED_SELECTION_KEY) ? configurationValues[ENHANCED_SELECTION_KEY].Value.AsBoolean() : cbEnhanced.Checked; tbRepeatColumns.Text = configurationValues.ContainsKey(REPEAT_COLUMNS) ? configurationValues[REPEAT_COLUMNS].Value : string.Empty; tbRepeatColumns.Visible = !cbEnhanced.Checked; ddlRepeatDirection.SetValue(configurationValues.GetValueOrNull(REPEAT_DIRECTION)); ddlRepeatDirection.Visible = !cbEnhanced.Checked; } }
/// <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) { if (value != null) { string[] valuePair = value.Split(new char[] { ',' }, StringSplitOptions.None); if (valuePair.Length == 2) { bool useDescription = false; if (!condensed && configurationValues.GetValueOrNull(DISPLAY_DESCRIPTION).AsBoolean()) { useDescription = true; } var lowerDefinedValue = DefinedValueCache.Get(valuePair[0].AsGuid()); var upperDefinedValue = DefinedValueCache.Get(valuePair[1].AsGuid()); if (lowerDefinedValue != null || upperDefinedValue != null) { if (useDescription) { return(string.Format( "{0} to {1}", lowerDefinedValue != null ? lowerDefinedValue.Description : string.Empty, upperDefinedValue != null ? upperDefinedValue.Description : string.Empty)); } else { return(string.Format( "{0} to {1}", lowerDefinedValue != null ? lowerDefinedValue.Value : string.Empty, upperDefinedValue != null ? upperDefinedValue.Value : string.Empty)); } } else { return(string.Empty); } } } // something unexpected. Let the base format it return(base.FormatValue(parentControl, value, configurationValues, condensed)); }
static string GetMessageLabel(Dictionary <string, string> headers) { var id = headers.GetValueOrNull(Headers.MessageId) ?? "<unknown>"; if (headers.TryGetValue(Headers.Type, out var type)) { var dotnetType = Type.GetType(type); if (dotnetType != null) { type = dotnetType.Name; } } else { type = "<unknown>"; } return($"{type}/{id}"); }
static void InnerSetDeferHeaders(DateTimeOffset approximateDeliveryTime, Dictionary <string, string> headers, string destinationAddress) { headers[Headers.DeferredUntil] = approximateDeliveryTime.ToIso8601DateTimeOffset(); // do not overwrite the recipient if it has been set if (!headers.ContainsKey(Headers.DeferredRecipient)) { headers[Headers.DeferredRecipient] = destinationAddress; } // if the headers indicate that this message has been deferred before, we increment the count if (int.TryParse(headers.GetValueOrNull(Headers.DeferCount), out var deferCount)) { headers[Headers.DeferCount] = (deferCount + 1).ToString(); } else { // otherwise we set to 1 headers[Headers.DeferCount] = "1"; } }
/// <summary> /// Get a dictionary of distances to each group. If a group has no /// locations then it will not be present in the dictionary. If a /// group has multiple locations then the closest location will be /// used. /// </summary> /// <param name="groups">The groups to be queried.</param> /// <param name="groupTypeLocation">The map of group types and the allowed location type to use.</param> /// <param name="latitude">The latitude of the reference point.</param> /// <param name="longitude">The longitude of the reference point.</param> /// <returns> /// A dictionary of group identifiers as the key and distance from the /// reference point as the values. /// </returns> private Dictionary <int, double> GetDistances(IEnumerable <Group> groups, Dictionary <int, int> groupTypeLocation, double latitude, double longitude) { var distances = new Dictionary <int, double>(); foreach (var group in groups) { var groupLocations = group.GroupLocations .Where(gl => gl.Location.GeoPoint != null); var locationTypeId = groupTypeLocation.GetValueOrNull(group.GroupTypeId); if (locationTypeId.HasValue) { groupLocations = groupLocations.Where(gl => gl.GroupLocationTypeValueId == locationTypeId.Value); } foreach (var groupLocation in groupLocations) { var geoPoint = System.Data.Entity.Spatial.DbGeography.FromText(string.Format("POINT({0} {1})", longitude, latitude)); double meters = groupLocation.Location.GeoPoint.Distance(geoPoint) ?? 0.0D; double miles = meters * Location.MilesPerMeter; // If this group already has a distance calculated, see if this location is closer and if so, use it instead if (distances.ContainsKey(group.Id)) { if (miles < distances[group.Id]) { distances[group.Id] = miles; } } else { distances.Add(group.Id, miles); } } } return(distances); }
/// <summary> /// Updates the persons times attended. /// </summary> /// <param name="attributeValuesByPersonId">The attribute values by person identifier.</param> /// <param name="attendanceQuery">The attendance query.</param> /// <param name="timesAttendedAttributeKey">The times attended attribute key.</param> /// <param name="startDate">The start date.</param> private void UpdatePersonsTimesAttended(Dictionary <int, Dictionary <string, string> > attributeValuesByPersonId, IQueryable <Attendance> attendanceQuery, string timesAttendedAttributeKey, DateTime startDate) { var attendancesByPerson = attendanceQuery.Where(a => a.StartDateTime >= startDate).GroupBy(a => a.PersonAlias.PersonId); var timesAttendedByPersonList = attendancesByPerson.Select(s => new { PersonId = s.Key, TimesAttended = s.Count() }).ToList(); foreach (var timesAttendedByPerson in timesAttendedByPersonList) { var personAttributeValues = attributeValuesByPersonId.GetValueOrNull(timesAttendedByPerson.PersonId); if (personAttributeValues == null) { personAttributeValues = new Dictionary <string, string>(); attributeValuesByPersonId.AddOrReplace(timesAttendedByPerson.PersonId, personAttributeValues); } personAttributeValues.AddOrReplace(timesAttendedAttributeKey, timesAttendedByPerson.TimesAttended.ToString()); } }
/// <summary> /// Evaluates if the reference is of the provided data type. /// </summary> /// <param name="reference">reference to evaluate</param> /// <param name="definitions">definition list</param> /// <param name="dataType">Datatype value to evaluate</param> /// <returns>true if the reference is of the provided data type. False otherwise.</returns> public static bool IsReferenceOfType(string reference, Dictionary <string, Schema> definitions, Model.DataType dataType) { if (reference == null) { return(false); } string definitionName = Extensions.StripDefinitionPath(reference); Schema schema = definitions.GetValueOrNull(definitionName); if (schema == null) { return(false); } if (schema.Type == dataType || (schema.Type == null && schema.Reference != null && IsReferenceOfType(schema.Reference, definitions, dataType))) { return(true); } return(false); }
/// <summary> /// Gets the block change handlers used for change detection. /// </summary> /// <returns>A dictionary of <see cref="IStructuredContentBlockChangeHandler"/> instances.</returns> private static IReadOnlyDictionary <string, IReadOnlyList <IStructuredContentBlockChangeHandler> > GetBlockChangeHandlers() { if (_changeHandlers == null) { var blockChangesTypes = Reflection.FindTypes(typeof(IStructuredContentBlockChangeHandler)) .Where(a => a.Value.GetCustomAttribute <StructuredContentBlockAttribute>() != null) .OrderBy(a => a.Value.Assembly == typeof(BlockTypes.ParagraphRenderer).Assembly) .Select(a => a.Value); var changeHandlers = new Dictionary <string, IReadOnlyList <IStructuredContentBlockChangeHandler> >(); foreach (var type in blockChangesTypes) { try { var blockType = type.GetCustomAttribute <StructuredContentBlockAttribute>().BlockType; var list = (List <IStructuredContentBlockChangeHandler>)changeHandlers.GetValueOrNull(blockType); if (list == null) { list = new List <IStructuredContentBlockChangeHandler>(); changeHandlers.Add(blockType, list); } var changeHandler = ( IStructuredContentBlockChangeHandler )Activator.CreateInstance(type); list.Add(changeHandler); } catch { /* Intentionally left blank. */ } } _changeHandlers = changeHandlers; } return(_changeHandlers); }
/// <summary> /// Validates the structure of Resource Model /// </summary> /// <param name="definitions">Operation Definition to validate</param> /// <returns>true if the resource model is valid.false otherwise.</returns> public override bool IsValid(Dictionary <string, Schema> definitions) { foreach (string key in definitions.Keys) { if (key.ToLower().Equals("resource")) { Schema resourceSchema = definitions.GetValueOrNull(key); if (resourceSchema == null || resourceSchema.Properties.Count == 0) { return(false); } if (!this.validateSchemaProperty(resourceSchema, "id", true) || !this.validateSchemaProperty(resourceSchema, "name", true) || !this.validateSchemaProperty(resourceSchema, "type", true) || !this.validateSchemaProperty(resourceSchema, "location", false) || !this.validateSchemaProperty(resourceSchema, "tags", false)) { return(false); } } } return(true); }
/// <summary> /// Processes the databound. /// </summary> /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param> private void ProcessDatabound(RepeaterItemEventArgs e) { var group = e.Item.DataItem as Rock.Model.Group; if (group != null) { var hfGroupId = e.Item.FindControl("hfGroupId") as HiddenField; hfGroupId.Value = group.Id.ToString(); var groupDescription = group.Description.IsNullOrWhiteSpace() ? string.Empty : $@"<br>{group.Description}"; var groupPublicName = group.GetAttributeValue("PublicName"); var cbCommunicationListIsSubscribed = e.Item.FindControl("cbCommunicationListIsSubscribed") as RockCheckBox; cbCommunicationListIsSubscribed.Text = $@"<strong>{groupPublicName}</strong>{groupDescription}"; if (groupPublicName.IsNullOrWhiteSpace()) { cbCommunicationListIsSubscribed.Text = $@"<strong>{group.Name}</strong>{groupDescription}"; } var groupMember = personCommunicationListsMember.GetValueOrNull(group.Id); cbCommunicationListIsSubscribed.Checked = groupMember != null && groupMember.GroupMemberStatus == GroupMemberStatus.Active; CommunicationType communicationType = CurrentPerson.CommunicationPreference == CommunicationType.SMS ? CommunicationType.SMS : CommunicationType.Email; // if GroupMember record has SMS or Email specified, that takes precedence over their Person.CommunicationPreference var groupMemberHasSmsOrEmailPreference = groupMember != null && (groupMember.CommunicationPreference == CommunicationType.SMS || groupMember.CommunicationPreference == CommunicationType.Email); if (groupMemberHasSmsOrEmailPreference) { communicationType = groupMember.CommunicationPreference; } var tglCommunicationPreference = e.Item.FindControl("tglCommunicationPreference") as Toggle; tglCommunicationPreference.Checked = communicationType == CommunicationType.Email; tglCommunicationPreference.Visible = showMediumPreference; } }
/// <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 ) { if ( value != null ) { string[] valuePair = value.Split( new char[] { ',' }, StringSplitOptions.None ); if ( valuePair.Length == 2 ) { bool useDescription = false; if ( !condensed && configurationValues.GetValueOrNull( DISPLAY_DESCRIPTION ).AsBoolean() ) { useDescription = true; } var lowerDefinedValue = DefinedValueCache.Read( valuePair[0].AsGuid() ); var upperDefinedValue = DefinedValueCache.Read( valuePair[1].AsGuid() ); if ( lowerDefinedValue != null || upperDefinedValue != null ) { if ( useDescription ) { return string.Format( "{0} to {1}", lowerDefinedValue != null ? lowerDefinedValue.Description : string.Empty, upperDefinedValue != null ? upperDefinedValue.Description : string.Empty ); } else { return string.Format( "{0} to {1}", lowerDefinedValue != null ? lowerDefinedValue.Value : string.Empty, upperDefinedValue != null ? upperDefinedValue.Value : string.Empty ); } } else { return string.Empty; } } } // something unexpected. Let the base format it return base.FormatValue( parentControl, value, configurationValues, condensed ); }
static string GetMessageLabel(Dictionary<string, string> headers) { var id = headers.GetValueOrNull(Headers.MessageId) ?? "<unknown>"; string type; if (headers.TryGetValue(Headers.Type, out type)) { var dotnetType = Type.GetType(type); if (dotnetType != null) { type = dotnetType.Name; } } else { type = "<unknown>"; } return $"{type}/{id}"; }
int GetMessagePriority(Dictionary<string, string> headers) { var valueOrNull = headers.GetValueOrNull(MessagePriorityHeaderKey); if (valueOrNull == null) return 0; try { return int.Parse(valueOrNull); } catch (Exception exception) { throw new FormatException(string.Format("Could not parse '{0}' into an Int32!", valueOrNull), exception); } }
/// <summary> /// Sets the configuration value. /// </summary> /// <param name="controls"></param> /// <param name="configurationValues"></param> public override void SetConfigurationValues( List<Control> controls, Dictionary<string, ConfigurationValue> configurationValues ) { if ( controls != null && configurationValues != null ) { DropDownList ddlDefinedType = controls.Count > 0 ? controls[0] as DropDownList : null; CheckBox cbDisplayDescription = controls.Count > 1 ? controls[1] as CheckBox : null; if ( ddlDefinedType != null ) { ddlDefinedType.SelectedValue = configurationValues.GetValueOrNull( DEFINED_TYPE_KEY ); } if ( cbDisplayDescription != null ) { cbDisplayDescription.Checked = configurationValues.GetValueOrNull( DISPLAY_DESCRIPTION ).AsBoolean(); } } }
/// <summary> /// Creates the control(s) necessary for prompting user for a new value /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id"></param> /// <returns> /// The control /// </returns> public override Control EditControl( Dictionary<string, ConfigurationValue> configurationValues, string id ) { Panel pnlRange = new Panel { ID = id, CssClass = "form-control-group" }; //Panel pnlCol1 = new Panel { CssClass = "col-md-6" }; //Panel pnlCol2 = new Panel { CssClass = "col-md-6" }; RockDropDownList lowerValueControl = new RockDropDownList { ID = string.Format( "{0}_ddlLower", id ) }; lowerValueControl.CssClass = "input-width-md"; RockDropDownList upperValueControl = new RockDropDownList { ID = string.Format( "{0}_ddlUpper", id ) }; upperValueControl.CssClass = "input-width-md"; pnlRange.Controls.Add( lowerValueControl ); pnlRange.Controls.Add( new Label { CssClass = "to", Text = " to " } ); pnlRange.Controls.Add( upperValueControl ); if ( configurationValues != null && configurationValues.ContainsKey( DEFINED_TYPE_KEY ) ) { Guid definedTypeGuid = configurationValues.GetValueOrNull( DEFINED_TYPE_KEY ).AsGuid(); DefinedTypeCache definedType = DefinedTypeCache.Read( definedTypeGuid ); if ( definedType != null ) { var definedValues = definedType.DefinedValues; if ( definedValues.Any() ) { bool useDescription = configurationValues.GetValueOrNull( DISPLAY_DESCRIPTION ).AsBoolean(); lowerValueControl.Items.Add( new ListItem() ); upperValueControl.Items.Add( new ListItem() ); foreach ( var definedValue in definedValues) { lowerValueControl.Items.Add( new ListItem( useDescription ? definedValue.Description : definedValue.Value, definedValue.Guid.ToString() ) ); upperValueControl.Items.Add( new ListItem( useDescription ? definedValue.Description : definedValue.Value, definedValue.Guid.ToString() ) ); } } return pnlRange; } } return null; }