Beispiel #1
0
        static void Main()
        {
            IComparer<IShape> areaComparer = new AreaComparer();
            List<Circle> circles = new List<Circle>();
            circles.Add(new Circle(Point.Empty, 20));
            circles.Add(new Circle(Point.Empty, 10));
            circles.Add(new Circle(Point.Empty, 40));
            circles.Add(new Circle(Point.Empty, 30));

            // Won't work - wrong kind of comparer
            // circles.Sort(areaComparer);

            // Adapt the "general" comparer to work with more specific values
            IComparer<Circle> circleComparer = new ComparisonHelper<IShape, Circle>(areaComparer);
            circles.Sort(circleComparer);

            foreach (Circle circle in circles)
            {
                Console.WriteLine(circle.Area);
            }
        }
Beispiel #2
0
        public async Task <IActionResult> Get([FromQuery] string projectName, [FromQuery] Guid build1Id, [FromQuery] string locale1, [FromQuery] Guid build2Id, [FromQuery] string locale2, [FromQuery] string threshold, bool sliderIsDisabled)
        {
            ComparisonHelper   comparisonHelper = new ComparisonHelper();
            IList <Comparison> comparisons      = await comparisonHelper.GetComparisons(_unitOfWork, projectName, build1Id, locale1, build2Id, locale2);

            // Threshold is read as a percentage
            double dThreshold = Convert.ToDouble(threshold) / 100;

            List <ScreenInBuild> leftScreens  = new List <ScreenInBuild>();
            List <ScreenInBuild> rightScreens = new List <ScreenInBuild>();
            //List<string> diffScreens = new List<string>();
            Dictionary <string, string> diffScreens = new Dictionary <string, string>();

            foreach (var screen in comparisons)
            {
                if (screen.SourceScreenInBuild != null || screen.TargetScreenInBuild != null)
                {
                    // If the slider is enabled, only add differences
                    if (!sliderIsDisabled)
                    {
                        if (dThreshold == 0)
                        {
                            if (screen.Difference > 0)
                            {
                                leftScreens.Add(screen.SourceScreenInBuild);
                                rightScreens.Add(screen.TargetScreenInBuild);
                                leftBuild  = screen.SourceScreenInBuild.Build.BuildName;
                                rightBuild = screen.TargetScreenInBuild.Build.BuildName;

                                diffScreens.Add(StorageHelper.GetDiffImagePath(screen.SourceScreenInBuildId, screen.TargetScreenInBuildId), screen.SourceScreenInBuild.ScreenName);
                            }
                        }
                        else // Threshold is not 0
                        {
                            if (screen.Difference >= dThreshold)
                            {
                                leftScreens.Add(screen.SourceScreenInBuild);
                                rightScreens.Add(screen.TargetScreenInBuild);
                                leftBuild  = screen.SourceScreenInBuild.Build.BuildName;
                                rightBuild = screen.TargetScreenInBuild.Build.BuildName;

                                diffScreens.Add(StorageHelper.GetDiffImagePath(screen.SourceScreenInBuildId, screen.TargetScreenInBuildId), screen.SourceScreenInBuild.ScreenName);
                            }
                        }
                    }
                    else // slider is disabled, so add everything
                    {
                        leftScreens.Add(screen.SourceScreenInBuild);
                        rightScreens.Add(screen.TargetScreenInBuild);
                        leftBuild  = screen.SourceScreenInBuild.Build.BuildName;
                        rightBuild = screen.TargetScreenInBuild.Build.BuildName;

                        diffScreens.Add(StorageHelper.GetDiffImagePath(screen.SourceScreenInBuildId, screen.TargetScreenInBuildId), screen.SourceScreenInBuild.ScreenName);
                    }
                }
                else // There is no comparison, so screen.SourceScreenInBuild is null
                {
                    leftScreens  = getAllScreens(projectName, locale1, build1Id);
                    rightScreens = getAllScreens(projectName, locale2, build2Id);
                    break;
                }
            }

            string tempFolder = createTempFolder();

            List <string> leftScreenPaths  = copyScreens(leftScreens, tempFolder, false);
            List <string> rightScreenPaths = copyScreens(rightScreens, tempFolder, true);

            copyDiffImages(diffScreens, tempFolder, projectName);

            HtmlReportHelper.CreateHtmlFile(leftScreenPaths, projectName, leftBuild, rightBuild, locale1, locale2, tempFolder);

            string randomFileName = Path.GetRandomFileName();
            string zipFile        = Path.Combine(Path.GetTempPath(), randomFileName + ".zip");

            if (!System.IO.File.Exists(zipFile))
            {
                ZipFile.CreateFromDirectory(tempFolder, zipFile, CompressionLevel.Optimal, false);
            }

            byte[] fileBytes = System.IO.File.ReadAllBytes(zipFile);
            string fileName  = "screenshots.zip";

            return(File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName));
        }
        /// <summary>
        /// Gets a filter expression for an attribute value.
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="filterValues">The filter values.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <returns></returns>
        public override Expression AttributeFilterExpression(Dictionary <string, ConfigurationValue> configurationValues, List <string> filterValues, ParameterExpression parameterExpression)
        {
            Expression comparison = null;

            if (filterValues.Count > 1)
            {
                //// OR up the where clauses for each of the selected values
                // and make sure to wrap commas around things so we don't collide with partial matches
                // so it'll do something like this:
                //
                // WHERE ',' + Value + ',' like '%,bacon,%'
                // OR ',' + Value + ',' like '%,lettuce,%'
                // OR ',' + Value + ',' like '%,tomato,%'

                // should be either "Contains" or "Not Contains" or "IsBlank"
                ComparisonType comparisonType = filterValues[0].ConvertToEnum <ComparisonType>(ComparisonType.Contains);

                if (comparisonType == ComparisonType.EqualTo)
                {
                    // If EqualTo was specified, treat it as Contains
                    comparisonType = ComparisonType.Contains;
                }

                if (comparisonType == ComparisonType.NotEqualTo)
                {
                    // If NotEqualTo was specified, treat it as DoesNotContain
                    comparisonType = ComparisonType.DoesNotContain;
                }

                // No comparison value was specified, so we can filter if the Comparison Type using no value still makes sense
                if ((ComparisonType.IsBlank | ComparisonType.IsNotBlank).HasFlag(comparisonType))
                {
                    // Just checking if IsBlank or IsNotBlank, so let ComparisonExpression do its thing
                    MemberExpression propertyExpression = Expression.Property(parameterExpression, this.AttributeValueFieldName);
                    return(ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, AttributeConstantExpression(string.Empty)));
                }

                List <string> selectedValues = filterValues[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

                foreach (var selectedValue in selectedValues)
                {
                    var searchValue     = "," + selectedValue + ",";
                    var qryToExtract    = new AttributeValueService(new Data.RockContext()).Queryable().Where(a => ("," + a.Value + ",").Contains(searchValue));
                    var valueExpression = FilterExpressionExtractor.Extract <AttributeValue>(qryToExtract, parameterExpression, "a");

                    if (comparisonType != ComparisonType.Contains)
                    {
                        valueExpression = Expression.Not(valueExpression);
                    }

                    if (comparison == null)
                    {
                        comparison = valueExpression;
                    }
                    else
                    {
                        comparison = Expression.Or(comparison, valueExpression);
                    }
                }
            }

            if (comparison == null)
            {
                return(new NoAttributeFilterExpression());
            }

            return(comparison);
        }
Beispiel #4
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <returns></returns>
        public override Control[] CreateChildControls(Type entityType, FilterField filterControl)
        {
            var comparisonControl = ComparisonHelper.ComparisonControl(ComparisonType.LessThan | ComparisonType.GreaterThanOrEqualTo | ComparisonType.EqualTo);

            comparisonControl.ID = filterControl.ID + "_comparisonControl";
            filterControl.Controls.Add(comparisonControl);

            var globalAttributes = GlobalAttributesCache.Get();

            CurrencyBox numberBoxAmount = new CurrencyBox();

            numberBoxAmount.ID    = filterControl.ID + "_numberBoxAmount";
            numberBoxAmount.Label = "Amount";

            filterControl.Controls.Add(numberBoxAmount);

            AccountPicker accountPicker = new AccountPicker();

            accountPicker.AllowMultiSelect = true;
            accountPicker.ID = filterControl.ID + "_accountPicker";
            accountPicker.AddCssClass("js-account-picker");
            accountPicker.Label = "Accounts";
            filterControl.Controls.Add(accountPicker);

            RockCheckBox cbIncludeChildAccounts = new RockCheckBox();

            cbIncludeChildAccounts.ID       = filterControl.ID + "_cbIncludeChildAccounts";
            cbIncludeChildAccounts.Text     = "Include Child Accounts";
            cbIncludeChildAccounts.CssClass = "js-include-child-accounts";
            filterControl.Controls.Add(cbIncludeChildAccounts);

            RockCheckBox cbIgnoreInactiveAccounts = new RockCheckBox();

            cbIgnoreInactiveAccounts.ID       = filterControl.ID + "_cbIgnoreInactiveAccounts";
            cbIgnoreInactiveAccounts.Text     = "Ignore Inactive Accounts";
            cbIgnoreInactiveAccounts.CssClass = "js-ignore-inactive-accounts";
            filterControl.Controls.Add(cbIgnoreInactiveAccounts);

            SlidingDateRangePicker slidingDateRangePicker = new SlidingDateRangePicker();

            slidingDateRangePicker.ID = filterControl.ID + "_slidingDateRangePicker";
            slidingDateRangePicker.AddCssClass("js-sliding-date-range");
            slidingDateRangePicker.Label    = "Date Range";
            slidingDateRangePicker.Help     = "The date range of the transactions using the transaction date of each transaction";
            slidingDateRangePicker.Required = true;
            filterControl.Controls.Add(slidingDateRangePicker);

            RockCheckBox cbCombineGiving = new RockCheckBox();

            cbCombineGiving.ID       = filterControl.ID + "_cbCombineGiving";
            cbCombineGiving.Label    = "Combine Giving";
            cbCombineGiving.CssClass = "js-combine-giving";
            cbCombineGiving.Help     = "Combine individuals in the same giving group when calculating totals and reporting the list of individuals.";
            filterControl.Controls.Add(cbCombineGiving);

            RockCheckBox cbUseAnalytics = new RockCheckBox();

            cbUseAnalytics.ID       = filterControl.ID + "_cbUseAnalytics";
            cbUseAnalytics.Label    = "Use Analytics Models";
            cbUseAnalytics.CssClass = "js-use-analytics";
            cbUseAnalytics.Help     = "Using Analytics Data might be faster than querying real-time data, but it may not include data that has been added or updated in the last 24 hours.";
            filterControl.Controls.Add(cbUseAnalytics);

            var controls = new Control[8] {
                comparisonControl, numberBoxAmount, accountPicker, cbIncludeChildAccounts, cbIgnoreInactiveAccounts, slidingDateRangePicker, cbCombineGiving, cbUseAnalytics
            };

            // set an initial config for the selection
            var selectionConfig = new SelectionConfig
            {
                ComparisonType = ComparisonType.GreaterThanOrEqualTo
            };

            SetSelection(entityType, controls, selectionConfig.ToJson());

            return(controls);
        }
        protected sealed override bool AppliesTo(SwimmingPool pool, List <SwimmingPoolLastMeasurementsGetResponse> obj)
        {
            SwimmingPoolLastMeasurementsGetResponse latest = obj.OrderByDescending(s => ComparisonHelper.GetMax(s.LastStripTimestamp, s.LastBlueMeasureTimestamp)).FirstOrDefault();

            return(AppliesTo(pool, obj, latest));
        }
        protected sealed override void UpdateInternal(SwimmingPool pool, List <SwimmingPoolLastMeasurementsGetResponse> obj)
        {
            SwimmingPoolLastMeasurementsGetResponse latest = obj.OrderByDescending(s => ComparisonHelper.GetMax(s.LastStripTimestamp, s.LastBlueMeasureTimestamp)).FirstOrDefault();

            UpdateInternal(pool, obj, latest);
        }
Beispiel #7
0
 public static Treap <T> Create(bool descending = false) =>
 new Treap <T>(ComparisonHelper.Create <T>(descending));
        private async Task PerformUpdate(CancellationToken stoppingToken)
        {
            DateTime lastAutomaticMeasurement = DateTime.MinValue;
            DateTime lastMeasurement          = DateTime.MinValue;
            TimeSpan?measureInterval          = null;

            List <SwimmingPoolLastMeasurementsGetResponse> measurements = new List <SwimmingPoolLastMeasurementsGetResponse>();

            SwimmingPool pool = _pool;

            _updateManager.Process(pool, pool);

            _logger.LogDebug("Fetching blue devices for {Id} ({Name})", pool.SwimmingPoolId, pool.Name);
            SwimmingPoolBlueDevicesGetResponse blueDevices = await _blueClient.GetSwimmingPoolBlueDevices(pool.SwimmingPoolId, stoppingToken);

            bool anyBlueDeviceIsAwake = false;

            foreach (SwimmingPoolDevice blueDevice in blueDevices.Data)
            {
                _logger.LogDebug("Fetching measurements for {Id}, blue {Serial} ({Name})", pool.SwimmingPoolId, blueDevice.BlueDeviceSerial, pool.Name);
                _updateManager.Process(pool, blueDevice);

                SwimmingPoolLastMeasurementsGetResponse blueMeasurement = await _blueClient.GetBlueLastMeasurements(pool.SwimmingPoolId, blueDevice.BlueDeviceSerial, token : stoppingToken);

                if (blueDevice.BlueDevice.WakePeriod > 0)
                {
                    measureInterval = ComparisonHelper.GetMin(measureInterval, TimeSpan.FromSeconds(blueDevice.BlueDevice.WakePeriod));
                }

                measurements.Add(blueMeasurement);

                // Track the last measurement time in order to calculate the next expected measurement.
                // For now, this includes Gateway & sigfox measurements, as these are automated.
                // Manual bluetooth measurements do not affect the interval
                lastAutomaticMeasurement = ComparisonHelper.GetMax(lastAutomaticMeasurement,
                                                                   blueDevice.BlueDevice.LastMeasureMessageSigfox,
                                                                   blueDevice.BlueDevice.LastMeasureMessageGateway).GetValueOrDefault();

                lastMeasurement = ComparisonHelper.GetMax(lastMeasurement,
                                                          blueDevice.BlueDevice.LastMeasureMessage,
                                                          blueDevice.BlueDevice.LastMeasureMessageBle,
                                                          blueDevice.BlueDevice.LastMeasureMessageSigfox).GetValueOrDefault();

                // Track sleep states
                anyBlueDeviceIsAwake |= blueDevice.BlueDevice.SleepState == "awake";
            }

            _logger.LogDebug("Fetching guidance for {Id} ({Name})", pool.SwimmingPoolId, pool.Name);

            SwimmingPoolGuidanceGetResponse guidance = await _blueClient.GetSwimmingPoolGuidance(pool.SwimmingPoolId, _config.Language, token : stoppingToken);

            _updateManager.Process(pool, guidance);

            _logger.LogDebug("Fetching measurements for {Id} ({Name})", pool.SwimmingPoolId, pool.Name);

            SwimmingPoolLastMeasurementsGetResponse measurement = await _blueClient.GetSwimmingPoolLastMeasurements(pool.SwimmingPoolId, stoppingToken);

            measurements.Add(measurement);

            lastMeasurement = ComparisonHelper.GetMax(lastMeasurement,
                                                      measurement.LastStripTimestamp,
                                                      measurement.LastBlueMeasureTimestamp).GetValueOrDefault();

            _updateManager.Process(pool, measurements);

            _logger.LogDebug("Fetching weather for {Id} ({Name})", pool.SwimmingPoolId, pool.Name);

            SwimmingPoolWeatherGetResponse weather = await _blueClient.GetSwimmingPoolWeather(pool.SwimmingPoolId, _config.Language, stoppingToken);

            _updateManager.Process(pool, weather.Data);

            //_logger.LogDebug("Fetching status for {Id} ({Name})", pool.SwimmingPoolId, pool.Name);
            //SwimmingPoolStatusGetResponse status = await _blueClient.GetSwimmingPoolStatus(pool.SwimmingPoolId, stoppingToken);
            //_updateManager.Update(pool, status);

            _delayCalculator.TrackMeasureInterval(measureInterval);
            _delayCalculator.TrackLastAutoMeasurement(lastAutomaticMeasurement);
            _delayCalculator.TrackSleepState(anyBlueDeviceIsAwake);

            if (lastMeasurement > _lastMeasurement)
            {
                _lastMeasurement = lastMeasurement;

                if (_config.ReportUnchangedValues)
                {
                    // A new measurement was made, report potentially unchanged values
                    _hassMqttManager.MarkAllValuesDirty();
                }
            }
        }
Beispiel #9
0
 public static AvlSet <T> Create(bool descending = false) =>
 new AvlSet <T>(ComparisonHelper.Create <T>(descending));
Beispiel #10
0
        /// <summary>
        /// Gets a filter expression for an attribute value.
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="filterValues">The filter values.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <returns></returns>
        public override Expression AttributeFilterExpression(Dictionary <string, ConfigurationValue> configurationValues, List <string> filterValues, ParameterExpression parameterExpression)
        {
            bool          allowMultiple = configurationValues != null && configurationValues.ContainsKey(ALLOW_MULTIPLE_KEY) && configurationValues[ALLOW_MULTIPLE_KEY].Value.AsBoolean();
            List <string> selectedValues;

            if (allowMultiple || filterValues.Count != 1)
            {
                ComparisonType comparisonType = filterValues[0].ConvertToEnum <ComparisonType>(ComparisonType.Contains);

                // if it isn't either "Contains" or "Not Contains", just use the base AttributeFilterExpression
                if (!(new ComparisonType[] { ComparisonType.Contains, ComparisonType.DoesNotContain }).Contains(comparisonType))
                {
                    return(base.AttributeFilterExpression(configurationValues, filterValues, parameterExpression));
                }

                //// OR up the where clauses for each of the selected values
                // and make sure to wrap commas around things so we don't collide with partial matches
                // so it'll do something like this:
                //
                // WHERE ',' + Value + ',' like '%,bacon,%'
                // OR ',' + Value + ',' like '%,lettuce,%'
                // OR ',' + Value + ',' like '%,tomato,%'

                if (filterValues.Count > 1)
                {
                    selectedValues = filterValues[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                }
                else
                {
                    selectedValues = new List <string>();
                }

                Expression comparison = null;

                foreach (var selectedValue in selectedValues)
                {
                    var searchValue     = "," + selectedValue + ",";
                    var qryToExtract    = new AttributeValueService(new Data.RockContext()).Queryable().Where(a => ("," + a.Value + ",").Contains(searchValue));
                    var valueExpression = FilterExpressionExtractor.Extract <AttributeValue>(qryToExtract, parameterExpression, "a");

                    if (comparisonType != ComparisonType.Contains)
                    {
                        valueExpression = Expression.Not(valueExpression);
                    }

                    if (comparison == null)
                    {
                        comparison = valueExpression;
                    }
                    else
                    {
                        comparison = Expression.Or(comparison, valueExpression);
                    }
                }

                if (comparison == null)
                {
                    // No Value specified, so return NoAttributeFilterExpression ( which means don't filter )
                    return(new NoAttributeFilterExpression());
                }
                else
                {
                    return(comparison);
                }
            }

            selectedValues = filterValues[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            int valueCount = selectedValues.Count();
            MemberExpression propertyExpression = Expression.Property(parameterExpression, "Value");

            if (valueCount == 0)
            {
                // No Value specified, so return NoAttributeFilterExpression ( which means don't filter )
                return(new NoAttributeFilterExpression());
            }
            else if (valueCount == 1)
            {
                // only one value, so do an Equal instead of Contains which might compile a little bit faster
                ComparisonType comparisonType = ComparisonType.EqualTo;
                return(ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, AttributeConstantExpression(selectedValues[0])));
            }
            else
            {
                ConstantExpression constantExpression = Expression.Constant(selectedValues, typeof(List <string>));
                return(Expression.Call(constantExpression, typeof(List <string>).GetMethod("Contains", new Type[] { typeof(string) }), propertyExpression));
            }
        }
Beispiel #11
0
        /// <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)
            {
                // uses Tab Delimited since slidingDateRangePicker is | delimited
                var filterValueValues = filterValues[1].Split(new string[] { "\t" }, StringSplitOptions.None);

                // Parse for RelativeValue of DateTime (if specified)
                filterValueValues[0] = ParseRelativeValue(filterValueValues[0]);

                string comparisonValue = filterValues[0];
                if (comparisonValue != "0" && comparisonValue.IsNotNullOrWhiteSpace())
                {
                    ComparisonType   comparisonType     = comparisonValue.ConvertToEnum <ComparisonType>(ComparisonType.EqualTo);
                    MemberExpression propertyExpression = Expression.Property(parameterExpression, propertyName);
                    if (comparisonType == ComparisonType.Between && filterValueValues.Length > 1)
                    {
                        var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(filterValueValues[1]);
                        ConstantExpression constantExpressionLower = dateRange.Start.HasValue
                            ? Expression.Constant(dateRange.Start, typeof(DateTime))
                            : null;

                        ConstantExpression constantExpressionUpper = dateRange.End.HasValue
                            ? Expression.Constant(dateRange.End, typeof(DateTime))
                            : null;

                        if (constantExpressionLower == null && constantExpressionUpper == null)
                        {
                            return(new NoAttributeFilterExpression());
                        }
                        else
                        {
                            /*
                             * Convert expressions to int if the property type is an int
                             */
                            if (propertyType == typeof(int) || propertyType == typeof(int?))
                            {
                                if (constantExpressionLower != null)
                                {
                                    constantExpressionLower = Expression.Constant(Convert.ToDateTime(constantExpressionLower.Value).ToString("yyyyMMdd").AsInteger(), typeof(int));
                                }
                                if (constantExpressionUpper != null)
                                {
                                    constantExpressionUpper = Expression.Constant(Convert.ToDateTime(constantExpressionUpper.Value).ToString("yyyyMMdd").AsInteger(), typeof(int));
                                }
                            }

                            return(ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, constantExpressionLower, constantExpressionUpper));
                        }
                    }
                    else
                    {
                        var dateTime = filterValueValues[0].AsDateTime();
                        if (dateTime.HasValue)
                        {
                            ConstantExpression constantExpression = Expression.Constant(dateTime, typeof(DateTime));
                            if (propertyType == typeof(int) || propertyType == typeof(int?))
                            {
                                constantExpression = Expression.Constant(dateTime?.ToString("yyyyMMdd").AsInteger(), typeof(int));
                            }

                            return(ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, constantExpression));
                        }
                        else
                        {
                            if (comparisonType == ComparisonType.IsBlank || comparisonType == ComparisonType.IsNotBlank)
                            {
                                return(ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, null));
                            }
                            else
                            {
                                return(new NoAttributeFilterExpression());
                            }
                        }
                    }
                }
            }

            return(null);
        }
Beispiel #12
0
 /// <inheritdoc cref="IEquatable{T}.Equals(T)" />
 public bool Equals(JsonMessageSerializer <TMessage>?other) => ComparisonHelper.JsonEquals(this, other);
Beispiel #13
0
        /// <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 virtual Expression PropertyFilterExpression(Dictionary <string, ConfigurationValue> configurationValues, List <string> filterValues, Expression parameterExpression, string propertyName, Type propertyType)
        {
            if (filterValues.Count >= 2)
            {
                string comparisonValue = filterValues[0];
                if (comparisonValue != "0")
                {
                    MemberExpression propertyExpression = Expression.Property(parameterExpression, propertyName);

                    var  type           = propertyType;
                    bool isNullableType = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>);
                    if (isNullableType)
                    {
                        type = Nullable.GetUnderlyingType(type);
                    }

                    ComparisonType comparisonType = comparisonValue.ConvertToEnum <ComparisonType>(ComparisonType.EqualTo);

                    // Parse the comparison string for multiple values.
                    var values = filterValues[1].Split(new string[] { "||" }, StringSplitOptions.None);

                    // Create an Expression with an OR relationship between each value.
                    Expression comparisonExpression = null;

                    foreach (var value in values)
                    {
                        object typedValue = ConvertValueToPropertyType(value, type);

                        if (typedValue != null)
                        {
                            ConstantExpression constantExpression = Expression.Constant(typedValue, type);

                            if (comparisonExpression == null)
                            {
                                comparisonExpression = ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, constantExpression);
                            }
                            else
                            {
                                comparisonExpression = Expression.OrElse(comparisonExpression, ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, constantExpression));
                            }
                        }
                    }

                    return(comparisonExpression);
                }
            }

            return(null);
        }
Beispiel #14
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <returns></returns>
        public override Control[] CreateChildControls(Type entityType, FilterField filterControl)
        {
            var pGroupPicker = new GroupPicker();

            pGroupPicker.AllowMultiSelect = true;
            pGroupPicker.ID = $"{filterControl.ID}_{nameof( pGroupPicker )}";
            pGroupPicker.AddCssClass("js-group-picker");
            filterControl.Controls.Add(pGroupPicker);

            var cbChildGroups = new RockCheckBox();

            cbChildGroups.ID = $"{filterControl.ID}_{nameof( cbChildGroups )}";
            cbChildGroups.AddCssClass("js-child-groups");
            cbChildGroups.Text = "Include Child Groups";
            filterControl.Controls.Add(cbChildGroups);

            var ddlIntegerCompare = ComparisonHelper.ComparisonControl(ComparisonHelper.NumericFilterComparisonTypes);

            ddlIntegerCompare.Label = "Attendance Count";
            ddlIntegerCompare.ID    = $"{filterControl.ID}_{nameof( ddlIntegerCompare )}";
            ddlIntegerCompare.AddCssClass("js-filter-compare");
            filterControl.Controls.Add(ddlIntegerCompare);

            var tbAttendedCount = new RockTextBox();

            tbAttendedCount.ID    = $"{filterControl.ID}_{nameof( tbAttendedCount )}";
            tbAttendedCount.Label = "&nbsp;"; // give it whitespace label so it lines up nicely
            tbAttendedCount.AddCssClass("js-attended-count");
            filterControl.Controls.Add(tbAttendedCount);

            var slidingDateRangePicker = new SlidingDateRangePicker();

            slidingDateRangePicker.Label = "Date Range";
            slidingDateRangePicker.ID    = $"{filterControl.ID}_{nameof( slidingDateRangePicker )}";
            slidingDateRangePicker.AddCssClass("js-sliding-date-range");
            filterControl.Controls.Add(slidingDateRangePicker);

            var schedulePicker = new SchedulePicker();

            schedulePicker.Label = "Schedules";
            schedulePicker.ID    = $"{filterControl.ID}_{nameof( schedulePicker )}";
            schedulePicker.AddCssClass("js-schedule-picker");
            schedulePicker.AllowMultiSelect = true;
            filterControl.Controls.Add(schedulePicker);

            var controls = new Control[6] {
                pGroupPicker, cbChildGroups, ddlIntegerCompare, tbAttendedCount, slidingDateRangePicker, schedulePicker
            };

            var defaultGroupAttendanceFilterSelection = new GroupAttendanceFilterSelection
            {
                IntegerCompare     = ComparisonType.GreaterThanOrEqualTo.ConvertToInt().ToString(),
                AttendedCount      = 4,
                SlidingDateRange   = slidingDateRangePicker.DelimitedValues,
                IncludeChildGroups = false,
            };

            // set the default values in case this is a newly added filter
            SetSelection(
                entityType,
                controls,
                defaultGroupAttendanceFilterSelection.ToJson());

            return(controls);
        }
Beispiel #15
0
 public static Treap <T> Create <TKey>(Func <T, TKey> keySelector, bool descending = false) =>
 new Treap <T>(ComparisonHelper.Create(keySelector, descending));
        /// <summary>
        /// Helper to handle a comparison operator call.  Checks to see if the call can
        /// return NotImplemented and allows the caller to modify the expression that
        /// is ultimately returned (e.g. to turn __cmp__ into a bool after a comparison)
        /// </summary>
        private static bool MakeOneCompareGeneric(SlotOrFunction/*!*/ target, bool reverse, DynamicMetaObject/*!*/[]/*!*/ types, ComparisonHelper returner, ConditionalBuilder/*!*/ bodyBuilder, Type retType) {
            if (target == SlotOrFunction.Empty || !target.Success) return true;

            ParameterExpression tmp;

            if (target.ReturnType == typeof(bool)) {
                tmp = bodyBuilder.CompareRetBool;
            } else {
                tmp = Ast.Variable(target.ReturnType, "compareRetValue");
                bodyBuilder.AddVariable(tmp);
            }

            if (target.MaybeNotImplemented) {
                Expression call = target.Target.Expression;
                Expression assign = Ast.Assign(tmp, call);

                returner(
                    bodyBuilder,
                    Ast.NotEqual(
                        assign,
                        AstUtils.Constant(PythonOps.NotImplemented)
                    ),
                    tmp,
                    reverse,
                    retType);
                return true;
            } else {
                returner(
                    bodyBuilder,
                    null,
                    target.Target.Expression,
                    reverse,
                    retType
                );
                return false;
            }
        }
Beispiel #17
0
        protected override async Task <ResultWithMetrologyProperties <Result> > DoRunAsync(Request request)
        {
            var current = await DbContext.Cards
                          .Include(c => c.CardLanguage)
                          .Include(c => c.TagsInCards)
                          .ThenInclude(t => t.Tag)
                          .Include(c => c.Images)
                          .ThenInclude(i => i.Image)
                          .SingleAsync(c => c.Id == request.CurrentCardId);

            var original = await DbContext.CardPreviousVersions
                           .Include(c => c.CardLanguage)
                           .Include(c => c.Tags)
                           .ThenInclude(t => t.Tag)
                           .Include(c => c.Images)
                           .ThenInclude(i => i.Image)
                           .SingleAsync(c => c.Id == request.OriginalVersionId);

            var result = new Result(current.VersionCreator.UserName, original.VersionCreator.UserName, current.VersionUtcDate, original.VersionUtcDate, current.VersionDescription, original.VersionDescription);

            if (current.FrontSide != original.FrontSide)
            {
                result = result with {
                    FrontSide = new(current.FrontSide, original.FrontSide)
                }
            }
            ;
            if (current.BackSide != original.BackSide)
            {
                result = result with {
                    BackSide = new(current.BackSide, original.BackSide)
                }
            }
            ;
            if (current.AdditionalInfo != original.AdditionalInfo)
            {
                result = result with {
                    AdditionalInfo = new(current.AdditionalInfo, original.AdditionalInfo)
                }
            }
            ;
            if (current.CardLanguage != original.CardLanguage)
            {
                result = result with {
                    Language = new(current.CardLanguage.Name, original.CardLanguage.Name)
                }
            }
            ;
            if (!Enumerable.SequenceEqual(current.TagsInCards.Select(t => t.Tag.Name).OrderBy(tagName => tagName), original.Tags.Select(t => t.Tag.Name).OrderBy(tagName => tagName)))
            {
                var currentTags  = string.Join(",", current.TagsInCards.Select(t => t.Tag.Name).OrderBy(tagName => tagName));
                var originalTags = string.Join(",", original.Tags.Select(t => t.Tag.Name).OrderBy(tagName => tagName));
                result = result with {
                    Tags = new(currentTags, originalTags)
                };
            }
            if (!CardVisibilityHelper.CardsHaveSameUsersWithView(current.UsersWithView, original.UsersWithView))
            {
                var currentUsers      = string.Join(",", current.UsersWithView.Select(u => u.User.UserName).OrderBy(userName => userName));
                var originalUserIds   = original.UsersWithView.Select(u => u.AllowedUserId).ToHashSet();
                var originalUserNames = DbContext.Users.Where(u => originalUserIds.Contains(u.Id)).Select(u => u.UserName);
                var originalUsers     = string.Join(",", originalUserNames.OrderBy(userName => userName));
                result = result with {
                    UsersWithView = new(currentUsers, originalUsers)
                };
            }
            if (!ComparisonHelper.SameSetOfGuid(current.Images.Where(i => i.CardSide == ImageInCard.FrontSide).Select(i => i.ImageId), original.Images.Where(i => i.CardSide == ImageInCard.FrontSide).Select(i => i.ImageId)))
            {
                var currentImages  = string.Join(",", current.Images.Where(i => i.CardSide == ImageInCard.FrontSide).Select(i => i.Image.Name).OrderBy(imageName => imageName));
                var originalImages = string.Join(",", original.Images.Where(i => i.CardSide == ImageInCard.FrontSide).Select(i => i.Image.Name).OrderBy(imageName => imageName));
                result = result with {
                    ImagesOnFrontSide = new(currentImages, originalImages)
                };
            }
            if (!ComparisonHelper.SameSetOfGuid(current.Images.Where(i => i.CardSide == ImageInCard.BackSide).Select(i => i.ImageId), original.Images.Where(i => i.CardSide == ImageInCard.BackSide).Select(i => i.ImageId)))
            {
                var currentImages  = string.Join(",", current.Images.Where(i => i.CardSide == ImageInCard.BackSide).Select(i => i.Image.Name).OrderBy(imageName => imageName));
                var originalImages = string.Join(",", original.Images.Where(i => i.CardSide == ImageInCard.BackSide).Select(i => i.Image.Name).OrderBy(imageName => imageName));
                result = result with {
                    ImagesOnBackSide = new(currentImages, originalImages)
                };
            }
            if (!ComparisonHelper.SameSetOfGuid(current.Images.Where(i => i.CardSide == ImageInCard.AdditionalInfo).Select(i => i.ImageId), original.Images.Where(i => i.CardSide == ImageInCard.AdditionalInfo).Select(i => i.ImageId)))
            {
                var currentImages  = string.Join(",", current.Images.Where(i => i.CardSide == ImageInCard.AdditionalInfo).Select(i => i.Image.Name).OrderBy(imageName => imageName));
                var originalImages = string.Join(",", original.Images.Where(i => i.CardSide == ImageInCard.AdditionalInfo).Select(i => i.Image.Name).OrderBy(imageName => imageName));
                result = result with {
                    ImagesOnAdditionalSide = new(currentImages, originalImages)
                };
            }
            return(new ResultWithMetrologyProperties <Result>(result, ("CurrentCardId", request.CurrentCardId.ToString()), ("OriginalVersionId", request.OriginalVersionId.ToString())));
        }