Пример #1
0
        private static async Task AggregateTest()
        {
            using (TestDbContext db = new TestDbContext())
            {
                var aggregation = new AggregationHelper <Contract, ContractViewModel>(db.Contracts);

                var query = await aggregation
                            .GroupBy(o => new { o.PartnerId, o.CompanyId })
                            .Sum(o => o.Final)
                            .Sum(o => o.Finished, o => o.Paid)
                            .Sum(o => o.Invoiced)
                            .Max(o => o.Final, o => o.MostExpensive)
                            .Min(o => o.Final, o => o.Cheapest)
                            .OrderByDescending(o => o.Final)
                            .Count(o => o.Count)
                            .Average(o => o.Final, o => o.Average)
                            .ToResultAsync(o => o.CompanyId + "-" + o.PartnerId);

                Console.WriteLine("Before lift:");
                PrintAggregationView(query);

                query.Lift(o => o.CompanyId, o => o.CompanyId + "小计").Lift("合计");

                //Console.WriteLine("Generated");
                //Console.WriteLine(query);

                Console.WriteLine("After lift:");

                PrintAggregationView(query);

                foreach (FlattenMode mode in Enum.GetValues(typeof(FlattenMode)))
                {
                    Console.WriteLine("Flatten " + mode);

                    PrintViewItems(query.Flatten(mode), false);
                }

                //query.Count();

                //var query1 = db.Contracts.GroupBy(o => new { o.PartnerId, o.CompanyId })
                //    .Select(o => new ContractViewModel
                //    {
                //        PartnerId = o.Key.PartnerId,
                //        CompanyId = o.Key.CompanyId,
                //        Final = o.Sum(i => i.Final),
                //        Paid = o.Sum(i => i.Finished),
                //        Invoiced = o.Sum(i => i.Invoiced),
                //        MostExpensive = o.Max(i => i.Final),
                //        Cheapest = o.Min(i => i.Final),
                //        Average = o.Average(i => i.Final),
                //        Count = o.Count()
                //    });

                //Console.WriteLine("Typed");
                ////Console.WriteLine(query1);
                //PrintAggretationResult(query1);
            }

            Console.ReadLine();
        }
        public void TestNestedAggregations()
        {
            var mog =
                this.deserial.Deserialize <MotherOfGodAggregations>(
                    new RestResponse <MotherOfGodAggregations> {
                Content = TestResources.doubleAggregation
            });
            var output     = new Dictionary <string, Dictionary <string, double> >();
            var fieldNames = new Dictionary <string, string>();

            AggregationHelper.ProcessAggregations(mog.aggregations, 0, ref output, string.Empty, false, ref fieldNames);

            bool success = false;

            foreach (var item in output.Keys)
            {
                if (output[item].Keys.Any(subItem => subItem == "HGIS"))
                {
                    success = true;
                }

                if (success)
                {
                    break;
                }
            }

            Assert.IsTrue(success);
        }
Пример #3
0
        protected AggregationFilterModel <TParameters> SignificantTermsFilterFor(string filterName)
        {
            var propertyInfo = ParameterPropertyCache.FirstOrDefault(c => c.Key == filterName);

            if (string.IsNullOrWhiteSpace(propertyInfo.Key))
            {
                throw new ArgumentOutOfRangeException(nameof(filterName), $"Unable to find parameter named '{filterName}', ensure that either the parameters has a matching property or that a JsonProperty attribute is assigned");
            }

            var filterValue = propertyInfo.Value.GetValue(Parameters);

            var model = new AggregationFilterModel <TParameters>();
            var agg   = AggregationHelper.SignificantTerms(filterName);

            if (agg == null)
            {
                return(model);
            }

            model.Name        = filterName;
            model.Meta        = agg.Meta;
            model.Type        = agg.SearchifyAggregationType();
            model.DisplayName = agg.SearchifyDisplayName() ?? model.Name;

            model.Items = agg.Buckets.Select(item =>
            {
                var parameters = QueryStringParser <TParameters> .Copy(Parameters);

                var term  = item.Key;
                var value = item.Key;

                if (FilterField.TryParse(item.Key, out FilterField filterField))
                {
                    term  = filterField.Text;
                    value = filterField.Value;
                }

                var isSelected = value.Equals(filterValue);

                if (propertyInfo.Value != null)
                {
                    var convertablePropertyInfo = Nullable.GetUnderlyingType(propertyInfo.Value.PropertyType) ??
                                                  propertyInfo.Value.PropertyType;
                    propertyInfo.Value.SetValue(parameters,
                                                isSelected ? null : Convert.ChangeType(value, convertablePropertyInfo));
                }

                return(new TermFilterItemModel <TParameters>()
                {
                    Term = term,
                    Value = value,
                    DocCount = item.DocCount,
                    Selected = isSelected,
                    Parameters = parameters
                });
            }).ToList();

            return(model);
        }
Пример #4
0
            public COM_IOleInPlaceObject IOleInPlaceObject;    // cached interface obtained from UserConrol

            public ExposedUserControl()
            {
                _logger.Log(LogLevel.Trace, "ExposedUserControl constructor called");

                // Gain access to the IOleObject and IOleInPlaceObject interfaces implemented by the UserControl
                IOleObject        = (COM_IOleObject)AggregationHelper.ObtainInternalInterface(this, GetType().GetInterface("IOleObject"));
                IOleInPlaceObject = (COM_IOleInPlaceObject)AggregationHelper.ObtainInternalInterface(this, GetType().GetInterface("IOleInPlaceObject"));
            }
        public void TestProcessAggregations()
        {
            AggregationHelper testTarget = new AggregationHelper();

            var mog = deserial.Deserialize <MotherOfGodAggregations>(new RestResponse <MotherOfGodAggregations>
            {
                Content = TestResources.MogJson
            });
        }
Пример #6
0
 /// <summary>
 ///     加载
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void ctlMatchItem_Load(object sender, EventArgs e)
 {
     Common.Utility.FillComberWithArray(cmbComparisonfunction, AggregationHelper.GetComparisonfunction(), true);
     if (RuntimeMongoDbContext.GetCurrentCollection() != null)
     {
         foreach (var item in MongoHelper.GetCollectionSchame(RuntimeMongoDbContext.GetCurrentCollection()))
         {
             cmbField.Items.Add(item);
         }
     }
 }
        public void TestSingleValueAggregation()
        {
            var mog = this.deserial.Deserialize <MotherOfGodAggregations>(
                new RestResponse <MotherOfGodAggregations> {
                Content = TestResources.sentimentAggregation
            });
            var output     = new Dictionary <string, Dictionary <string, double> >();
            var fieldNames = new Dictionary <string, string>();

            AggregationHelper.ProcessAggregations(mog.aggregations, 0, ref output, string.Empty, false, ref fieldNames);
        }
Пример #8
0
 private void ctlMatchItem_Load(object sender, EventArgs e)
 {
     foreach (string item in AggregationHelper.GetComparisonfunction())
     {
         cmbComparisonfunction.Items.Add(item);
     }
     if (SystemManager.GetCurrentCollection() != null)
     {
         foreach (string item in MongoDbHelper.GetCollectionSchame(SystemManager.GetCurrentCollection()))
         {
             cmbField.Items.Add(item);
         }
     }
 }
Пример #9
0
 private void GroupItem_Load(object sender, EventArgs e)
 {
     foreach (string item in AggregationHelper.GetGroupfunction())
     {
         cmbGroupFunction.Items.Add(item);
     }
     if (SystemManager.GetCurrentCollection() != null)
     {
         cmbGroupValue.Items.Add("1");
         foreach (string item in MongoDbHelper.GetCollectionSchame(SystemManager.GetCurrentCollection()))
         {
             cmbGroupFunction.Items.Add("$" + item);
             cmbGroupValue.Items.Add("$" + item);
         }
     }
 }
Пример #10
0
 private void ctlMatchItem_Load(object sender, EventArgs e)
 {
     foreach (var item in AggregationHelper.GetComparisonfunction())
     {
         cmbComparisonfunction.Items.Add(item);
     }
     if (RuntimeMongoDbContext.GetCurrentCollection() != null)
     {
         foreach (
             var item in
             MongoHelper.GetCollectionSchame(RuntimeMongoDbContext.GetCurrentCollection())
             )
         {
             cmbField.Items.Add(item);
         }
     }
 }
Пример #11
0
 private void GroupItem_Load(object sender, EventArgs e)
 {
     foreach (var item in AggregationHelper.GetGroupfunction())
     {
         cmbGroupFunction.Items.Add(item);
     }
     cmbGroupFunction.Items.Add("==========");
     if (RuntimeMongoDbContext.GetCurrentCollection() != null)
     {
         cmbGroupValue.Items.Add("1");
         foreach (var item in MongoHelper.GetCollectionSchame(RuntimeMongoDbContext.GetCurrentCollection()))
         {
             cmbGroupFunction.Items.Add("$" + item);
             cmbGroupValue.Items.Add("$" + item);
         }
     }
 }
Пример #12
0
        /// <summary>
        ///     运行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdOK_Click(object sender, EventArgs e)
        {
            var strKey = string.Empty;

            foreach (RadioButton item in panColumn.Controls)
            {
                if (item.Checked)
                {
                    strKey = item.Name;
                }
            }
            if (strKey == string.Empty)
            {
                MyMessageBox.ShowMessage("Distinct", "Pick the field");
                return;
            }
            var strResult = AggregationHelper.Distinct(strKey, DistinctConditionList);

            MyMessageBox.ShowMessage("Distinct", "Distinct:" + strKey, strResult, true);
        }
Пример #13
0
        protected AggregationFilterModel <TParameters> MultiTermFilterFor(string filterName)
        {
            var propertyInfo = ParameterPropertyCache.FirstOrDefault(c => c.Key == filterName);

            if (string.IsNullOrWhiteSpace(propertyInfo.Key))
            {
                throw new ArgumentOutOfRangeException(nameof(filterName), $"Unable to find parameter named '{filterName}', ensure that either the parameters has a matching property or that a JsonProperty attribute is assigned");
            }

            var filterValue = ((IEnumerable <string>)propertyInfo.Value.GetValue(Parameters))?.ToList() ?? Enumerable.Empty <string>();

            var model = new AggregationFilterModel <TParameters>();
            var agg   = AggregationHelper.Terms(filterName);

            if (agg == null)
            {
                return(model);
            }

            model.Name        = filterName;
            model.Meta        = agg.Meta;
            model.Type        = agg.SearchifyAggregationType();
            model.DisplayName = agg.SearchifyDisplayName() ?? model.Name;

            model.Items = agg.Buckets.Select(item =>
            {
                var parameters = QueryStringParser <TParameters> .Copy(Parameters);

                var term  = item.Key;
                var value = item.Key;

                if (FilterField.TryParse(item.Key, out FilterField filterField))
                {
                    term  = filterField.Text;
                    value = filterField.Value;
                }

                var filterValueList = new HashSet <string>(filterValue);

                var isSelected = filterValue.Contains(value);

                if (isSelected)
                {
                    filterValueList.Remove(value);
                }
                else
                {
                    filterValueList.Add(value);
                }

                propertyInfo.Value.SetValue(parameters, filterValueList);

                return(new TermFilterItemModel <TParameters>()
                {
                    Term = term,
                    Value = value,
                    DocCount = item.DocCount,
                    Selected = isSelected,
                    Parameters = parameters
                });
            }).ToList();

            return(model);
        }
        public static async Task <AggregationResult <T> > ToResultAsync <T>(this AggregationHelper <T> helper, Func <T, string> label)
        {
            var array = await helper.GetQuery().ToArrayAsync();

            return(AggregationResult <T> .Create(array, helper, label));
        }
        public static async Task <AggregationResult <TResult> > ToResultAsync <TSource, TResult>(this AggregationHelper <TSource, TResult> helper, IQueryable <TSource> query, Func <TResult, string> label)
        {
            var array = await helper.GetQuery(query).ToArrayAsync();

            return(AggregationResult <TResult> .Create(array, helper, label));
        }
 public static Task <TResult[]> ToArrayAsync <TSource, TResult>(this AggregationHelper <TSource, TResult> helper, IQueryable <TSource> query)
 {
     return(helper.GetQuery(query).ToArrayAsync());
 }
Пример #17
0
		public object Min(string tableName, string columnName, SimpleExpression criteria)
		{
			var commandBuilder = new AggregationHelper(_adapter.GetSchema()).GetMinCommand(tableName, columnName, criteria);
			return ExecuteScalar(commandBuilder);
		}
Пример #18
0
        public static void CreateOrUpdateConsumerMailbox(WriteOperationType writeOperationType, PropertyBag propertyValuesBag, IRecipientSession session, Action <string> logAction, Action <string> warningLogAction = null)
        {
            MbxReadMode      mbxReadMode      = ((IAggregateSession)session).MbxReadMode;
            BackendWriteMode backendWriteMode = ((IAggregateSession)session).BackendWriteMode;

            try
            {
                if (logAction == null)
                {
                    throw new ArgumentNullException("logAction");
                }
                if (warningLogAction == null)
                {
                    throw new ArgumentNullException("warningLogAction");
                }
                if (!propertyValuesBag.IsModified(ADUserSchema.NetID))
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, "Property 'ADUserSchema.NetID' must be set", new object[0]));
                }
                ulong  puid   = ((NetID)propertyValuesBag[ADUserSchema.NetID]).ToUInt64();
                string text   = ((NetID)propertyValuesBag[ADUserSchema.NetID]).ToString();
                bool   flag   = propertyValuesBag.IsModified("MakeExoPrimary") && (bool)propertyValuesBag["MakeExoPrimary"];
                bool   flag2  = propertyValuesBag.IsModified("MakeExoSecondary") && (bool)propertyValuesBag["MakeExoSecondary"];
                bool   flag3  = propertyValuesBag.IsModified("SkipMigration") && (bool)propertyValuesBag["SkipMigration"];
                ADUser aduser = ConsumerMailboxHelper.ReadUser(session, puid, true);
                if (aduser == null && (writeOperationType == WriteOperationType.Update || writeOperationType == WriteOperationType.RepairUpdate))
                {
                    throw new ADNoSuchObjectException(new LocalizedString(string.Format(CultureInfo.CurrentUICulture, "Cannot update object. Mserv entry for PUID: '{0}' not found", new object[]
                    {
                        text
                    })));
                }
                if (aduser != null && writeOperationType == WriteOperationType.Create && !flag2 && (!flag || !flag3))
                {
                    throw new ADObjectAlreadyExistsException(new LocalizedString(string.Format(CultureInfo.CurrentUICulture, "Cannot create object. Mserv entry for PUID: '{0}' already exists", new object[]
                    {
                        text
                    })));
                }
                if (aduser != null && aduser.Database != null && propertyValuesBag.IsModified(ADMailboxRecipientSchema.Database) && !aduser.Database.Equals((ADObjectId)propertyValuesBag[ADMailboxRecipientSchema.Database]))
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, "Cannot update database of an existing consumer mailbox in EXO. PUID: '{0}' Existing database: {1}", new object[]
                    {
                        text,
                        aduser.Database
                    }));
                }
                if (flag && flag2)
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, "Cannot set MakeExoPrimary and MakeExoSecondary at the same time. PUID: '{0}'", new object[]
                    {
                        text
                    }));
                }
                if (aduser == null)
                {
                    aduser = new ADUser();
                }
                if (flag)
                {
                    if (writeOperationType == WriteOperationType.Create && aduser.PrimaryMailboxSource() == PrimaryMailboxSourceType.None)
                    {
                        logAction("Current state: No mserv footprint - i.e. no mailbox in EXO and Hotmail.");
                        logAction("Action requested: MakeExoPrimary: Create a brand new primary consumer mailbox in EXO. ");
                    }
                    else if (writeOperationType == WriteOperationType.RepairCreate && (aduser.PrimaryMailboxSource() == PrimaryMailboxSourceType.None || aduser.PrimaryMailboxSource() == PrimaryMailboxSourceType.Exo))
                    {
                        logAction("Current state: Either no mserv footprint exists or a primary mailbox exists in EXO.");
                        logAction("Action requested: MakeExoPrimary: Retry creation of primary consumer mailbox in EXO. ");
                    }
                    else if ((writeOperationType == WriteOperationType.Update || writeOperationType == WriteOperationType.RepairUpdate) && aduser.Database != null && aduser.PrimaryMailboxSource() == PrimaryMailboxSourceType.Hotmail)
                    {
                        logAction("Current state: Primary mailbox exists in Hotmail and Secondary mailbox exists in EXO.");
                        logAction("Action requested: MakeExoPrimary: Switch from hotmail to EXO. ");
                    }
                    else
                    {
                        if ((writeOperationType != WriteOperationType.Create && writeOperationType != WriteOperationType.RepairCreate) || aduser.PrimaryMailboxSource() != PrimaryMailboxSourceType.Hotmail || aduser.Database != null || !flag3)
                        {
                            throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, "Cannot proceed with MakeExoPrimary operation. Invalid state detected. PUID: '{0}' Current primary mailbox source: {1} Write operation type: {2}", new object[]
                            {
                                text,
                                aduser.PrimaryMailboxSource(),
                                writeOperationType
                            }));
                        }
                        logAction("Current state: Primary mailbox exists in Hotmail and no secondary mailbox exists in EXO.");
                        logAction("Action requested: MakeExoPrimary: Switch directly from hotmail to EXO w/o migrating email contents and SkipMigration flag is supplied. ");
                    }
                }
                if (flag2)
                {
                    if (writeOperationType == WriteOperationType.Create && aduser.PrimaryMailboxSource() == PrimaryMailboxSourceType.Hotmail)
                    {
                        logAction("Current state: An existing primary mailbox in Hotmail.");
                        logAction("Action requested: MakeExoSecondary: Create a brand new secondary consumer mailbox in EXO. ");
                    }
                    else
                    {
                        if (writeOperationType != WriteOperationType.RepairCreate || aduser.PrimaryMailboxSource() != PrimaryMailboxSourceType.Hotmail)
                        {
                            throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, "Invalid state detected. Cannot proceed with MakeExoSecondary operation. A hotmail account must exist for PUID: '{0}'. Current primary mailbox source: {1} Write operation type: {2}", new object[]
                            {
                                text,
                                aduser.PrimaryMailboxSource(),
                                writeOperationType
                            }));
                        }
                        logAction("Current state: An existing primary mailbox in Hotmail with or without a secondary mailbox in EXO.");
                        logAction("Action requested: MakeExoSecondary: Retry creating a brand new secondary consumer mailbox in EXO. ");
                    }
                    propertyValuesBag[ADUserSchema.IsMigratedConsumerMailbox] = true;
                }
                if ((flag || flag2) && aduser.Database == null && !propertyValuesBag.IsModified(ADMailboxRecipientSchema.Database))
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, "You must specify Database for creating a new mailbox. PUID: '{0}'", new object[]
                    {
                        text
                    }));
                }
                if (!flag && !flag2 && aduser.Database == null)
                {
                    throw new ADNoSuchObjectException(new LocalizedString(string.Format(CultureInfo.CurrentUICulture, "Cannot perform this operation. No consumer mailbox (primary/secondary) exists for this user in EXO. PUID: '{0}'", new object[]
                    {
                        text
                    })));
                }
                ADRawEntry adrawEntry = new ADRawEntry();
                ADObjectId adobjectId = aduser.Database ?? (propertyValuesBag[ADMailboxRecipientSchema.Database] as ADObjectId);
                if (adobjectId != null && ConsumerMailboxHelper.PopulateStoreOnlyProperties(adrawEntry, puid, propertyValuesBag, true))
                {
                    logAction(string.Format("Saving store properties for user - puid: {0}", text));
                    AggregationHelper.PerformMbxModification(adobjectId.ObjectGuid, ConsumerIdentityHelper.GetExchangeGuidFromPuid(puid), adrawEntry.propertyBag as ADPropertyBag, false);
                }
                if (ConsumerMailboxHelper.PopulateMservPuidRecordProperties(aduser, puid, flag, flag2, propertyValuesBag))
                {
                    logAction(string.Format("Saving PUID records in Mserv for user - puid: {0}", text));
                    ((IAggregateSession)session).MbxReadMode      = MbxReadMode.NoMbxRead;
                    ((IAggregateSession)session).BackendWriteMode = BackendWriteMode.WriteToMServ;
                    session.Save(aduser);
                    aduser = ConsumerMailboxHelper.ReadUser(session, puid, true);
                }
                if (writeOperationType == WriteOperationType.RepairCreate || writeOperationType == WriteOperationType.RepairUpdate)
                {
                    ((IAggregateSession)session).MbxReadMode      = MbxReadMode.NoMbxRead;
                    ((IAggregateSession)session).BackendWriteMode = BackendWriteMode.WriteToMServ;
                    ConsumerMailboxHelper.SaveChangesInRepairMode(session, puid, ConsumerMailboxHelper.MServAliasAndOtherRecordProperties, propertyValuesBag, logAction, warningLogAction);
                }
                else if (ConsumerMailboxHelper.PopulateAliasAndOtherRecordProperties(aduser, puid, propertyValuesBag))
                {
                    logAction(string.Format("Saving Aliases and other records in Mserv for user - puid: {0}", text));
                    ((IAggregateSession)session).MbxReadMode      = MbxReadMode.NoMbxRead;
                    ((IAggregateSession)session).BackendWriteMode = BackendWriteMode.WriteToMServ;
                    session.Save(aduser);
                }
            }
            finally
            {
                ((IAggregateSession)session).MbxReadMode      = mbxReadMode;
                ((IAggregateSession)session).BackendWriteMode = backendWriteMode;
            }
        }