public void MemberName()
        {
            IValidator validator = Substitute.For <IValidator>();
            EntityPropertyValidationRule <Customer, string> entityPropertyValidationRule = new EntityPropertyValidationRule <Customer, string>(new EntityPropertyValidator(validator), Substitute.For <IPropertyDisplayNameResolver>(), x => x.FirstName);

            Assert.AreEqual(LinqUtils.GetMemberName <Customer, string>(x => x.FirstName), entityPropertyValidationRule.MemberName);
        }
Пример #2
0
        public virtual string toStringShallow(
            string joiner            = ", ",
            DiagnosticLevel minLevel = DiagnosticLevel.debug
            )
        {
            if (foundation_.kReleaseMode)
            {
                return(toString());
            }
            string shallowString = "";

            D.assert(() => {
                var result = new StringBuilder();
                result.Append(toString());
                result.Append(joiner);
                DiagnosticPropertiesBuilder builder = new DiagnosticPropertiesBuilder();
                debugFillProperties(builder);
                result.Append(string.Join(joiner,
                                          LinqUtils <string, DiagnosticsNode> .SelectList(LinqUtils <DiagnosticsNode> .WhereList(builder.properties, (n => !n.isFiltered(minLevel))), (n => n.ToString())))
                              );
                shallowString = result.ToString();
                return(true);
            });
            return(shallowString);
        }
Пример #3
0
        /// <summary>
        /// Assign using an expression, variable name based on input of variable name.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="memberExpression"></param>
        /// <param name="nextCommand"></param>
        /// <example>ScriptCommands.Assign(() => val1, ResultCommand.OK), pm));</example></example>
        /// <returns></returns>
        public static Assign Assign <T>(Expression <Func <T> > memberExpression,
                                        IScriptCommand nextCommand = null)
        {
            string variableName = "{" + LinqUtils.GetMemberName <T>(memberExpression) + "}";

            return(Assign(variableName, memberExpression.Compile()(), nextCommand));
        }
Пример #4
0
        protected void collectGarbage(int leadingGarbage, int trailingGarbage)
        {
            D.assert(_debugAssertChildListLocked());
            D.assert(childCount >= leadingGarbage + trailingGarbage);

            invokeLayoutCallback <SliverConstraints>(constraints => {
                while (leadingGarbage > 0)
                {
                    _destroyOrCacheChild(firstChild);
                    leadingGarbage -= 1;
                }

                while (trailingGarbage > 0)
                {
                    _destroyOrCacheChild(lastChild);
                    trailingGarbage -= 1;
                }

                LinqUtils <RenderBox> .WhereList(_keepAliveBucket.Values, (child => {
                    SliverMultiBoxAdaptorParentData childParentData = (SliverMultiBoxAdaptorParentData)child.parentData;
                    return(!childParentData.keepAlive);
                })).ForEach(_childManager.removeChild);

                D.assert(LinqUtils <RenderBox> .WhereList(_keepAliveBucket.Values, (child => {
                    SliverMultiBoxAdaptorParentData childParentData = (SliverMultiBoxAdaptorParentData)child.parentData;
                    return(!childParentData.keepAlive);
                })).isEmpty());
            });
        }
 public override void debugVisitOnstageChildren(ElementVisitor visitor)
 {
     foreach (var child in LinqUtils <Element> .WhereList(children, (_shouldPaint)))
     {
         visitor(child);
     }
 }
Пример #6
0
 /// <summary>Extension method which produces a projection to NWService.Dtos.DtoClasses.Order which instances are projected from the
 /// results of the specified baseQuery using QuerySpec, which returns NWService.Dal.EntityClasses.OrderEntity instances, the root entity of the derived element returned by this query.</summary>
 /// <param name="baseQuery">The base query to project the derived element instances from.</param>
 /// <param name="qf">The query factory used to create baseQuery.</param>
 /// <returns>DynamicQuery to retrieve NWService.Dtos.DtoClasses.Order instances</returns>
 public static DynamicQuery <NWService.Dtos.DtoClasses.Order> ProjectToOrder(this EntityQuery <NWService.Dal.EntityClasses.OrderEntity> baseQuery, NWService.Dal.FactoryClasses.QueryFactory qf)
 {
     System.Linq.Expressions.Expression <Func <NWService.Dtos.DtoClasses.Order> > projectionAdjustments = null;
     GetAdjustmentsForProjectToOrderQs(ref projectionAdjustments);
     return(qf.Create()
            .From(baseQuery.Select(Projection.Full).As("__BQ"))
            .Select(LinqUtils.MergeProjectionAdjustmentsIntoProjection(() => new NWService.Dtos.DtoClasses.Order()
     {
         CustomerId = OrderFields.CustomerId.Source("__BQ").ToValue <System.String>(),
         EmployeeId = OrderFields.EmployeeId.Source("__BQ").ToValue <Nullable <System.Int32> >(),
         Freight = OrderFields.Freight.Source("__BQ").ToValue <Nullable <System.Decimal> >(),
         OrderDate = OrderFields.OrderDate.Source("__BQ").ToValue <Nullable <System.DateTime> >(),
         OrderDetails = (List <NWService.Dtos.DtoClasses.OrderTypes.OrderDetail>)qf.OrderDetail.TargetAs("__L1_0")
                        .CorrelatedOver(OrderFields.OrderId.Source("__BQ").Equal(OrderDetailFields.OrderId.Source("__L1_0")))
                        .Select(() => new NWService.Dtos.DtoClasses.OrderTypes.OrderDetail()
         {
             Discount = OrderDetailFields.Discount.Source("__L1_0").ToValue <System.Single>(),
             ProductId = OrderDetailFields.ProductId.Source("__L1_0").ToValue <System.Int32>(),
             Quantity = OrderDetailFields.Quantity.Source("__L1_0").ToValue <System.Int16>(),
             UnitPrice = OrderDetailFields.UnitPrice.Source("__L1_0").ToValue <System.Decimal>(),
         }).ToResultset(),
         OrderId = OrderFields.OrderId.Source("__BQ").ToValue <System.Int32>(),
         RequiredDate = OrderFields.RequiredDate.Source("__BQ").ToValue <Nullable <System.DateTime> >(),
         ShipAddress = OrderFields.ShipAddress.Source("__BQ").ToValue <System.String>(),
         ShipCity = OrderFields.ShipCity.Source("__BQ").ToValue <System.String>(),
         ShipCountry = OrderFields.ShipCountry.Source("__BQ").ToValue <System.String>(),
         ShipName = OrderFields.ShipName.Source("__BQ").ToValue <System.String>(),
         ShippedDate = OrderFields.ShippedDate.Source("__BQ").ToValue <Nullable <System.DateTime> >(),
         ShipPostalCode = OrderFields.ShipPostalCode.Source("__BQ").ToValue <System.String>(),
         ShipRegion = OrderFields.ShipRegion.Source("__BQ").ToValue <System.String>(),
         ShipVia = OrderFields.ShipVia.Source("__BQ").ToValue <Nullable <System.Int32> >(),
         // __LLBLGENPRO_USER_CODE_REGION_START ProjectionRegionQS_Order
         // __LLBLGENPRO_USER_CODE_REGION_END
     }, projectionAdjustments, false)));
 }
        public void ValidateMustReturnInvalidValidationResultWhenTheSpecifiedSpecificationIsSatisfiedAndTheValidatorReturnsFalse()
        {
            const string firstName = "Foo";

            IValidator validator = Substitute.For <IValidator>();

            validator.IsValid(null).ReturnsForAnyArgs(false);

            ISpecification <Customer> specification = Substitute.For <ISpecification <Customer> >();

            specification.IsSatisfiedBy(null).ReturnsForAnyArgs(true);

            EntityPropertyValidationRule <Customer, string> entityPropertyValidationRule = new EntityPropertyValidationRule <Customer, string>(new EntityPropertyValidator(validator), Substitute.For <IPropertyDisplayNameResolver>(), x => x.FirstName, specification);
            ValidationResult validationResult = entityPropertyValidationRule.Validate(new Customer
            {
                FirstName = firstName
            });

            validator.Received(1).IsValid(firstName);
            specification.ReceivedWithAnyArgs(1).IsSatisfiedBy(null);

            Assert.AreEqual(1, validationResult.Errors.Count);
            Assert.AreEqual(LinqUtils.GetMemberName <Customer, string>(x => x.FirstName), validationResult.Errors[0].PropertyName);
            Assert.IsFalse(validationResult.IsValid);
        }
Пример #8
0
        void _initControllers()
        {
            _destinationControllers = LinqUtils <AnimationController, NavigationRailDestination> .SelectList(widget.destinations, ((destination) => {
                var result = new AnimationController(
                    duration: ThemeUtils.kThemeAnimationDuration,
                    vsync: this
                    );
                result.addListener(_rebuild);
                return(result);
            }));

            _destinationAnimations = LinqUtils <Animation <float>, AnimationController> .SelectList(_destinationControllers, ((AnimationController controller) => controller.view));

            _destinationControllers[widget.selectedIndex ?? 0].setValue(1.0f);
            _extendedController = new AnimationController(
                duration: ThemeUtils.kThemeAnimationDuration,
                vsync: this,
                value: widget.extended ?? false ? 1.0f : 0.0f
                );
            _extendedAnimation = new CurvedAnimation(
                parent: _extendedController,
                curve: Curves.easeInOut
                );
            _extendedController.addListener(() => { _rebuild(); });
        }
Пример #9
0
        public _ReadingOrderSortData _pickNext(List <_ReadingOrderSortData> candidates)
        {
            FocusTravesalUtils.mergeSort <_ReadingOrderSortData>(candidates, compare: (_ReadingOrderSortData a, _ReadingOrderSortData b) => a.rect.top.CompareTo(b.rect.top));
            _ReadingOrderSortData topmost = candidates.First();

            List <_ReadingOrderSortData> inBand(_ReadingOrderSortData current, IEnumerable <_ReadingOrderSortData> _candidates)
            {
                Rect band = Rect.fromLTRB(float.NegativeInfinity, current.rect.top, float.PositiveInfinity, current.rect.bottom);

                return(LinqUtils <_ReadingOrderSortData> .WhereList(_candidates, ((_ReadingOrderSortData item) => {
                    return !item.rect.intersect(band).isEmpty;
                })));
            }

            List <_ReadingOrderSortData> inBandOfTop = inBand(topmost, candidates);

            D.assert(topmost.rect.isEmpty || inBandOfTop.isNotEmpty());
            if (inBandOfTop.Count <= 1)
            {
                return(topmost);
            }
            TextDirection nearestCommonDirectionality = _ReadingOrderSortData.commonDirectionalityOf(inBandOfTop);

            _ReadingOrderSortData.sortWithDirectionality(inBandOfTop, nearestCommonDirectionality);
            List <_ReadingOrderDirectionalGroupData> bandGroups = _collectDirectionalityGroups(inBandOfTop);

            if (bandGroups.Count == 1)
            {
                return(bandGroups.First().members.First());
            }
            _ReadingOrderDirectionalGroupData.sortWithDirectionality(bandGroups, nearestCommonDirectionality);
            return(bandGroups.First().members.First());
        }
Пример #10
0
        public UIWidgetsError(List <DiagnosticsNode> diagnostics)
        {
            this.diagnostics = diagnostics;
            D.assert(diagnostics != null && diagnostics.isNotEmpty(), () => new UIWidgetsError(new List <DiagnosticsNode>()
            {
                new ErrorSummary("Empty FlutterError")
            }).ToString());
            D.assert(diagnostics.first().level == DiagnosticLevel.summary,
                     () => new UIWidgetsError(new List <DiagnosticsNode>()
            {
                new ErrorSummary("UIWidgetsError is missing a summary."),
                new ErrorDescription("All UIWidgetsError objects should start with a short (one line) " +
                                     "summary description of the problem that was detected."),
                new DiagnosticsProperty <UIWidgetsError>("Malformed", this, expandableValue: true, showSeparator: false, style: DiagnosticsTreeStyle.whitespace),
                new ErrorDescription(
                    "\nThis error should still help you solve your problem, " +
                    "however please also report this malformed error in the " +
                    "framework by filing a bug on GitHub:\n" +
                    "  https://https://github.com/Unity-Technologies/com.unity.uiwidgets"
                    )
            }).ToString());

            D.assert(() => {
                IEnumerable <DiagnosticsNode> summaries =
                    LinqUtils <DiagnosticsNode> .WhereList(diagnostics, ((DiagnosticsNode node) => node.level == DiagnosticLevel.summary));
                if (summaries.Count() > 1)
                {
                    return(false);
                }
                return(true);
            }, () => {
                IEnumerable <DiagnosticsNode> summaries =
                    LinqUtils <DiagnosticsNode> .WhereList(diagnostics, ((DiagnosticsNode node) => node.level == DiagnosticLevel.summary));
                List <DiagnosticsNode> message = new List <DiagnosticsNode>()
                {
                    new ErrorSummary("UIWidgetsError contained multiple error summaries."),
                    new ErrorDescription(
                        "All UIWidgetsError objects should have only a single short " +
                        "(one line) summary description of the problem that was " +
                        "detected."
                        ),
                    new DiagnosticsProperty <UIWidgetsError>("Malformed", this, expandableValue: true, showSeparator: false, style: DiagnosticsTreeStyle.whitespace)
                };

                int i = 0;
                foreach (DiagnosticsNode summary in summaries)
                {
                    message.Add(new DiagnosticsProperty <DiagnosticsNode>($"Summary {i}", summary, expandableValue: true));
                    i += 1;
                }
                message.Add(new ErrorDescription(
                                "\nThis error should still help you solve your problem, " +
                                "however please also report this malformed error in the " +
                                "framework by filing a bug on GitHub:\n" +
                                "  https://https://github.com/Unity-Technologies/com.unity.uiwidgets"
                                ));

                return(new UIWidgetsError(message).ToString());
            });
        }
Пример #11
0
 public Viewport(
     Key key = null,
     AxisDirection axisDirection      = AxisDirection.down,
     AxisDirection?crossAxisDirection = null,
     float anchor                      = 0.0f,
     ViewportOffset offset             = null,
     Key center                        = null,
     float?cacheExtent                 = null,
     CacheExtentStyle cacheExtentStyle = CacheExtentStyle.pixel,
     List <Widget> slivers             = null
     ) : base(key: key, children: slivers)
 {
     D.assert(offset != null);
     D.assert(slivers != null);
     D.assert(center == null || LinqUtils <Widget> .WhereList(slivers, ((Widget child) => child.key == center)).Count() == 1);
     D.assert(cacheExtentStyle != null);
     D.assert(cacheExtentStyle != CacheExtentStyle.viewport || cacheExtent != null);
     this.axisDirection      = axisDirection;
     this.crossAxisDirection = crossAxisDirection;
     this.anchor             = anchor;
     this.offset             = offset;
     this.center             = center;
     this.cacheExtent        = cacheExtent;
     this.cacheExtentStyle   = cacheExtentStyle;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="EntityPropertyValidationRule{TEntity, TProperty}"/> class.
        /// </summary>
        /// <param name="validator">The validator.</param>
        /// <param name="propertyDisplayNameResolver">The property display name resolver.</param>
        /// <param name="propertyExpression">The property expression.</param>
        /// <param name="specification">The specification.</param>
        /// <param name="message">The message.</param>
        public EntityPropertyValidationRule(IEntityPropertyValidator validator, IPropertyDisplayNameResolver propertyDisplayNameResolver, Expression <Func <TEntity, TProperty> > propertyExpression, ISpecification <TEntity> specification = null, string message = null)
        {
            if (validator == null)
            {
                throw new ArgumentNullException("validator");
            }

            if (propertyDisplayNameResolver == null)
            {
                throw new ArgumentNullException("propertyDisplayNameResolver");
            }

            if (propertyExpression == null)
            {
                throw new ArgumentNullException("propertyExpression");
            }

            m_Validator = validator;
            m_PropertyDisplayNameResolver = propertyDisplayNameResolver;
            m_Specification = specification;
            m_Message       = message;

            m_PropertyFunc = propertyExpression.Compile();
            m_MemberInfo   = LinqUtils.GetMemberInfo(propertyExpression);
        }
Пример #13
0
        static List <List <InternodeMessage> > FindInfeasibleMessagesCombinations(ISolver solver, IDictionary <NodeId, Node> nodes, List <InternodeMessage> messages,
                                                                                  List <FixedConstraint> fixedConstraints, HashSet <string> allowInstacesMergingForRoles)
        {
            var ret = new List <HashSet <InternodeMessage> >();

            Func <HashSet <InternodeMessage>, bool> combinationIsInfeasible = comb =>
                                                                              ret.Any(alreadyFoundCombination => comb.IsSupersetOf(alreadyFoundCombination));

            for (var combinationLength = 2; combinationLength < Math.Min(10, (messages.Count - 1)); ++combinationLength)
            {
                var newCombinationCandidates =
                    (from comb in LinqUtils.GetPowerSet(messages, combinationLength)
                     let combDict = new HashSet <InternodeMessage>(comb)
                                    where !combinationIsInfeasible(combDict)
                                    select combDict).ToArray();
                var newCombinations =
                    from combDict in newCombinationCandidates.AsParallel()
                    let solution = solverFn(solver, nodes, new InternodeMessagesMap(nodes, combDict.ToList()), combDict.ToList(), fixedConstraints, allowInstacesMergingForRoles)
                                   where solution.Status == SolutionStatus.Infeasible
                                   select combDict;
                ret.AddRange(newCombinations.ToArray());
            }

            return(ret.Select(d => d.ToList()).ToList());
        }
Пример #14
0
 DataRow _getBlankRowFor(int index)
 {
     return(DataRow.byIndex(
                index: index,
                cells:  LinqUtils <DataCell, DataColumn> .SelectList(widget.columns, ((DataColumn column) => DataCell.empty))
                ));
 }
Пример #15
0
        public override IEnumerable <FocusNode> sortDescendants(IEnumerable <FocusNode> descendants)
        {
            FocusTraversalPolicy     secondaryPolicy   = secondary ?? new ReadingOrderTraversalPolicy();
            IEnumerable <FocusNode>  sortedDescendants = secondaryPolicy.sortDescendants(descendants);
            List <FocusNode>         unordered         = new List <FocusNode>();
            List <_OrderedFocusInfo> ordered           = new List <_OrderedFocusInfo>();

            foreach (FocusNode node in sortedDescendants)
            {
                FocusOrder order = FocusTraversalOrder.of(node.context, nullOk: true);
                if (order != null)
                {
                    ordered.Add(new _OrderedFocusInfo(node: node, order: order));
                }
                else
                {
                    unordered.Add(node);
                }
            }
            FocusTravesalUtils.mergeSort <_OrderedFocusInfo>(ordered, compare: (_OrderedFocusInfo a, _OrderedFocusInfo b) => {
                D.assert(
                    a.order.GetType() == b.order.GetType(), () =>
                    $"When sorting nodes for determining focus order, the order ({a.order}) of " +
                    $"node {a.node}, isn't the same type as the order ({b.order}) of {b.node}. " +
                    "Incompatible order types can't be compared.  Use a FocusTraversalGroup to group " +
                    "similar orders together."
                    );
                return(a.order.CompareTo(b.order));
            });
            return(LinqUtils <FocusNode, _OrderedFocusInfo> .SelectList(ordered, ((_OrderedFocusInfo info) => info.node)).Concat(unordered));
        }
Пример #16
0
        public IEnumerable <FocusNode> _sortAndFilterHorizontally(
            TraversalDirection direction,
            Rect target,
            FocusNode nearestScope)
        {
            D.assert(direction == TraversalDirection.left || direction == TraversalDirection.right);
            IEnumerable <FocusNode> nodes = nearestScope.traversalDescendants;

            D.assert(!nodes.Contains(nearestScope));
            List <FocusNode> sorted = nodes.ToList();

            FocusTravesalUtils.mergeSort <FocusNode>(sorted, compare: (FocusNode a, FocusNode b) => a.rect.center.dx.CompareTo(b.rect.center.dx));
            IEnumerable <FocusNode> result = new List <FocusNode>();

            switch (direction)
            {
            case TraversalDirection.left:
                result = LinqUtils <FocusNode> .WhereList(sorted, ((FocusNode node) => node.rect != target && node.rect.center.dx <= target.left));

                break;

            case TraversalDirection.right:
                result = LinqUtils <FocusNode> .WhereList(sorted, ((FocusNode node) => node.rect != target && node.rect.center.dx >= target.right));

                break;

            case TraversalDirection.up:
            case TraversalDirection.down:
                break;
            }
            return(result);
        }
Пример #17
0
 public override void debugVisitOnstageChildren(ElementVisitor visitor)
 {
     LinqUtils <Element> .WhereList(children, (e => {
         RenderSliver renderSliver = (RenderSliver)e.renderObject;
         return(renderSliver.geometry.visible);
     })).ForEach(e => visitor(e));
 }
Пример #18
0
    //$response[] = array($i, $name, null, '<img src="images/'. $filename . (file_exists('images/' . $filename . '.jpg') ? '.jpg' : '.png') .'" /> ' . $name);

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            Items["UserId"] = 8;
            if (Items["UserId"] != null && Request["search"] != null)
            {
                string search = Request["search"];

                aqufitEntities entities       = new aqufitEntities();
                long           uid            = Convert.ToInt64(Items["UserId"]);
                IList <long>   friendIds      = entities.UserFriends.Where(f => (f.PortalKey == 0) && (f.SrcUserKey == uid || f.DestUserKey == uid)).Select(f => (f.SrcUserKey == uid ? f.DestUserKey : f.SrcUserKey)).ToList();
                UserSettings[] firendSettings = entities.UserSettings.Where(LinqUtils.BuildContainsExpression <UserSettings, long>(s => s.UserKey, friendIds)).Where(f => f.UserName.ToLower().Contains(search) || f.UserFirstName.ToLower().Contains(search) || f.UserLastName.ToLower().Contains(search)).ToArray();
                //
                object[] response = firendSettings.Select(f => new object[] { "" + f.UserKey, f.UserName + " (" + f.UserFirstName + "," + f.UserLastName + ")", null, "<img src=\"" + ResolveUrl("~/services/images/profile.aspx?u=" + f.UserKey) + "\" align=\"middle\"/>&nbsp;&nbsp;" + f.UserName + " (" + f.UserFirstName + "," + f.UserLastName + ")" }).ToArray();
                //object[] response = {new object[]{ "5", "fdsafda dfsa fdsa", null, null } };
                Response.Write(serializer.Serialize(response));
                Response.End();
            }
        }
        catch (Exception)
        {
            //Affine.Data.json.MapRoute route = new Affine.Data.json.MapRoute() { Id = -1 };
            //Response.Write(serializer.Serialize(route));
        }
    }
Пример #19
0
 private static System.Linq.Expressions.Expression <Func <NWService.Dal.EntityClasses.OrderEntity, NWService.Dtos.DtoClasses.Order> > CreateProjectionFunc()
 {
     System.Linq.Expressions.Expression <Func <NWService.Dal.EntityClasses.OrderEntity, NWService.Dtos.DtoClasses.Order> > mainProjection = p__0 => new NWService.Dtos.DtoClasses.Order()
     {
         CustomerId   = p__0.CustomerId,
         EmployeeId   = p__0.EmployeeId,
         Freight      = p__0.Freight,
         OrderDate    = p__0.OrderDate,
         OrderDetails = p__0.OrderDetails.Select(p__1 => new NWService.Dtos.DtoClasses.OrderTypes.OrderDetail()
         {
             Discount  = p__1.Discount,
             ProductId = p__1.ProductId,
             Quantity  = p__1.Quantity,
             UnitPrice = p__1.UnitPrice,
         }).ToList(),
         OrderId        = p__0.OrderId,
         RequiredDate   = p__0.RequiredDate,
         ShipAddress    = p__0.ShipAddress,
         ShipCity       = p__0.ShipCity,
         ShipCountry    = p__0.ShipCountry,
         ShipName       = p__0.ShipName,
         ShippedDate    = p__0.ShippedDate,
         ShipPostalCode = p__0.ShipPostalCode,
         ShipRegion     = p__0.ShipRegion,
         ShipVia        = p__0.ShipVia,
         // __LLBLGENPRO_USER_CODE_REGION_START ProjectionRegion_Order
         // __LLBLGENPRO_USER_CODE_REGION_END
     };
     System.Linq.Expressions.Expression <Func <NWService.Dal.EntityClasses.OrderEntity, NWService.Dtos.DtoClasses.Order> > projectionAdjustments = null;
     GetAdjustmentsForProjectToOrder(ref projectionAdjustments);
     return(LinqUtils.MergeProjectionAdjustmentsIntoProjection(mainProjection, projectionAdjustments, true));
 }
Пример #20
0
        internal static Future <Dictionary <Type, object> > _loadAll(
            Locale locale,
            IEnumerable <LocalizationsDelegate> allDelegates)
        {
            Dictionary <Type, object> output      = new Dictionary <Type, object>();
            List <_Pending>           pendingList = null;

            HashSet <Type> types = new HashSet <Type>();
            List <LocalizationsDelegate> delegates = new List <LocalizationsDelegate>();

            foreach (LocalizationsDelegate del in allDelegates)
            {
                if (!types.Contains(del.type) && del.isSupported(locale))
                {
                    types.Add(del.type);
                    delegates.Add(del);
                }
            }

            foreach (LocalizationsDelegate del in delegates)
            {
                Future <object> inputValue     = del.load(locale).to <object>();
                object          completedValue = null;
                Future <object> futureValue    = inputValue.then_(value => {
                    completedValue = value;
                    return(FutureOr.value(completedValue));
                }).to <object>();

                if (completedValue != null)
                {
                    Type type = del.type;
                    D.assert(!output.ContainsKey(type));
                    output[type] = completedValue;
                }
                else
                {
                    pendingList = pendingList ?? new List <_Pending>();
                    pendingList.Add(new _Pending(del, futureValue));
                }
            }

            if (pendingList == null)
            {
                return(new SynchronousFuture <Dictionary <Type, object> >(output));
            }
            return(Future.wait <object>(LinqUtils <Future <object>, _Pending> .SelectList(pendingList, (p => p.futureValue)))
                   .then(values => {
                var list = (List <object>)values;
                D.assert(list.Count == pendingList.Count);
                for (int i = 0; i < list.Count; i += 1)
                {
                    Type type = pendingList[i].del.type;
                    D.assert(!output.ContainsKey(type));
                    output[type] = list[i];
                }

                return output;
            }).to <Dictionary <Type, object> >());
        }
Пример #21
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                base.Page_Load(sender, e);
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    if (ProfileSettings == null)
                    {
                        Response.Redirect(ResolveUrl("~/"), true);
                    }
                    ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                    service.InlineScript = true;
                    ScriptManager.GetCurrent(Page).Services.Add(service);
                    atiProfileImage.Settings        = base.ProfileSettings;
                    atiProfileImage.IsOwner         = base.Permissions == AqufitPermission.OWNER;
                    atiStreamScript.IsFollowMode    = true;
                    atiStreamScript.DefaultTake     = 10;
                    bEditProfile.HRef               = ResolveUrl("~/Register.aspx");
                    litFriendsTitle.Text            = "Chefs " + ProfileSettings.UserName + " follows";
                    atiWebLinksList.ProfileSettings = base.ProfileSettings;
                    if (Permissions == AqufitPermission.OWNER)
                    {
                        atiFollow.Visible       = false;
                        atiWebLinksList.IsOwner = true;
                    }
                    else if (Permissions == AqufitPermission.PUBLIC)
                    {
                        string url = DotNetNuke.Common.Globals.NavigateURL(PortalSettings.LoginTabId, "Login", new string[] { "returnUrl=/" + this.ProfileSettings.UserName });
                        atiFollow.OnClientClick = "self.location.href='" + url + "'; return false;";
                        atiFollow.Click        -= atiFollow_Click;
                    }
                    else
                    {
                        atiFollow.Text = base.Following ? "Unfollow " : "Follow " + ProfileSettings.UserName;
                    }
                    aqufitEntities entities       = new aqufitEntities();
                    IList <long>   friendIds      = entities.UserFriends.Where(f => (f.SrcUserSettingKey == this.ProfileSettings.Id)).Select(f => f.DestUserSettingKey).ToList();
                    UserSettings[] firendSettings = entities.UserSettings.Where(LinqUtils.BuildContainsExpression <UserSettings, long>(s => s.Id, friendIds)).Where(f => f.PortalKey == this.PortalId).ToArray();
                    atiFriendsPhotos.RelationshipType = Affine.Relationship.FOLLOWING;
                    atiFriendsPhotos.FriendKeyList    = firendSettings;
                    atiFriendsPhotos.User             = base.ProfileSettings;
                    atiFriendsPhotos.FriendCount      = friendIds.Count;

                    Metric numRecipes = ProfileSettings.Metrics.FirstOrDefault(m => m.MetricType == (int)Utils.MetricUtil.MetricType.NUM_RECIPES);
                    lNumCreations.Text = lNumCreations2.Text = ProfileSettings.UserName + "'s Creations (" + (numRecipes != null ? numRecipes.MetricValue : "0") + ")";
                    lNumFavorites.Text = lNumFavorites2.Text = "" + entities.User2StreamFavorites.Where(f => f.UserKey == ProfileSettings.UserKey && f.PortalKey == ProfileSettings.PortalKey).Count();
                    lUserName.Text     = ProfileSettings.UserKey == this.UserId ? "you" : ProfileSettings.UserName;



                    atiStreamScript.EditUrl = ResolveUrl("~/AddRecipe.aspx");
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Пример #22
0
        public override List <DiagnosticsNode> debugDescribeChildren()
        {
            int count = 1;

            return(LinqUtils <DiagnosticsNode, FocusNode> .SelectList(_children, (FocusNode child) => {
                return child.toDiagnosticsNode(name: $"Child {count++}");
            }));
        }
Пример #23
0
        private static Type DetermineEntityType(Expression expression)
        {
            var type = expression.Type;

            return(typeof(IEntityCore).IsAssignableFrom(type)
                       ? type
                       : LinqUtils.DetermineEntityTypeFromEntityCollectionType(type));
        }
Пример #24
0
 public static string toStringList <T>(this IList <T> it)
 {
     if (it == null)
     {
         return(null);
     }
     return("{ " + string.Join(", ", LinqUtils <string, T> .SelectList(it, (item => item.ToString()))) + " }");
 }
Пример #25
0
        public DropdownButton(
            Key key = null,
            List <DropdownMenuItem <T> > items = null,
            material_.DropdownButtonBuilder selectedItemBuilder = null,
            T value                    = default,
            Widget hint                = null,
            Widget disabledHint        = null,
            ValueChanged <T> onChanged = null,
            VoidCallback onTap         = null,
            int elevation              = 8,
            TextStyle style            = null,
            Widget underline           = null,
            Widget icon                = null,
            Color iconDisabledColor    = null,
            Color iconEnabledColor     = null,
            float iconSize             = 24.0f,
            bool isDense               = false,
            bool isExpanded            = false,
            float?itemHeight           = material_.kMinInteractiveDimension,
            Color focusColor           = null,
            FocusNode focusNode        = null,
            bool autofocus             = false,
            Color dropdownColor        = null
            ) :
            base(key: key)
        {
            D.assert(items == null || items.isEmpty() || value == null ||
                     LinqUtils <DropdownMenuItem <T> > .WhereList(items, ((DropdownMenuItem <T> item) => { return(item.value.Equals(value)); })).Count() == 1,
                     () => "There should be exactly one item with [DropdownButton]'s value: " +
                     $"{value}. \n" +
                     "Either zero or 2 or more [DropdownMenuItem]s were detected " +
                     "with the same value"
                     );
            D.assert(itemHeight == null || itemHeight >= material_.kMinInteractiveDimension);

            this.items = items;
            this.selectedItemBuilder = selectedItemBuilder;
            this.value             = value;
            this.hint              = hint;
            this.disabledHint      = disabledHint;
            this.onChanged         = onChanged;
            this.onTap             = onTap;
            this.elevation         = elevation;
            this.style             = style;
            this.underline         = underline;
            this.icon              = icon;
            this.iconDisabledColor = iconDisabledColor;
            this.iconEnabledColor  = iconEnabledColor;
            this.iconSize          = iconSize;
            this.isDense           = isDense;
            this.isExpanded        = isExpanded;
            this.itemHeight        = itemHeight;
            this.focusColor        = focusColor;
            this.focusNode         = focusNode;
            this.autofocus         = autofocus;
            this.dropdownColor     = dropdownColor;
        }
Пример #26
0
        public static IQueryable <TEntity> With <TEntity>(this IQueryable <TEntity> query,
                                                          IEnumerable <Expression <Func <TEntity, Object> > > prefetch)
            where TEntity : class, IEntityCore
        {
            var creator   = LinqUtils.GetElementCreator(query);
            var rootEdges = GetPathEdges(prefetch, creator, typeof(TEntity)).ToArray();

            return(query.WithPath(rootEdges));
        }
Пример #27
0
        public IReadOnlyList <IEvent> GetEvents(string country)
        {
            if (_events.TryGetValue(country, out var events))
            {
                return(events);
            }

            return(LinqUtils.EmptyList <IEvent>());
        }
Пример #28
0
        public void GetProperyName()
        {
            Assert.AreEqual("Name1", LinqUtils.GetMemberName <TestClass, string>(x => x.Name1));
            Assert.AreEqual("Name2", LinqUtils.GetMemberName <TestClass, string>(x => x.Name2));
            Assert.AreEqual("Name3", LinqUtils.GetMemberName <TestClass, object>(x => x.Name3));
            Assert.AreEqual("Method1", LinqUtils.GetMemberName <TestClass, string>(x => x.Method1()));

            Assert.Throws <ArgumentNullException>(() => LinqUtils.GetMemberName <TestClass, string>(null));
        }
        private static void ValidateValidatorPropertyNames(Expression <Func <TestModel, string> > propertyNameExpression, ModelValidatorProvider provider, ControllerContext controllerContext)
        {
            string                 propertyName      = LinqUtils.GetMemberName(propertyNameExpression);
            ModelMetadata          propertyMetaData  = GetModelMetaDataForProperty(typeof(TestModel), propertyName);
            IList <ModelValidator> properyValidators = provider.GetValidators(propertyMetaData, controllerContext).ToList();

            Assert.IsTrue(properyValidators.Count > 0);
            Assert.IsTrue((properyValidators.Cast <LaboPropertyValidator>()).All(x => x.ValidationRule.MemberInfo.Name == propertyName));
        }
Пример #30
0
 public override Gradient scale(float factor)
 {
     return(new RadialGradient(
                center: center,
                radius: radius,
                colors: LinqUtils <Color> .SelectList(colors, (color => Color.lerp(null, color, factor))),
                stops: stops,
                tileMode: tileMode
                ));
 }