public Expression Bind(Expression expression, Type elementType)
 {
     _alias = new Alias();
     _finder = new FieldFinder();
     _elementType = elementType;
     return Visit(expression);
 }
 public CollectionExpression(Alias alias, IMongoDatabase database, string collectionName, Type documentType)
     : base(MongoExpressionType.Collection, typeof(void), alias)
 {
     CollectionName = collectionName;
     Database = database;
     DocumentType = documentType;
 }
Exemple #3
0
 public Expression Bind(Expression expression, Type elementType)
 {
     _alias = new Alias();
     _memberMap = new Dictionary<MemberInfo, Expression>();
     _finder = new FieldFinder(_memberMap);
     _elementType = elementType;
     return Visit(expression);
 }
 public FieldProjection ProjectFields(Expression expression, Alias newAlias, params Alias[] existingAliases)
 {
     _newAlias = newAlias;
     _existingAliases = existingAliases;
     _fields = new List<FieldDeclaration>();
     _fieldNames = new HashSet<string>();
     _candidates = _nominator.Nominate(expression);
     _map = new Dictionary<FieldExpression, FieldExpression>();
     return new FieldProjection(_fields.AsReadOnly(), Visit(expression));
 }
        private void ProcessRequest(Instance request)
        {
            try
            {
                var alias = new Alias
                    {
                        AliasValue = Alias
                    };

                var service = request.DirectoryService.Users.Aliases.Insert(alias, UserId);

                WriteObject(service.Execute());
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to Add User Alias!");
                Console.WriteLine("Error: " + e);
                WriteObject(false);
            }
        }
 private Expression BindTake(Expression source, Expression take)
 {
     var projection = VisitSequence(source);
     take = Visit(take);
     var alias = new Alias();
     var fieldProjection = _projector.ProjectFields(projection.Projector, alias, projection.Source.Alias);
     return new ProjectionExpression(
         new SelectExpression(alias, fieldProjection.Fields, projection.Source, null, null, null, false, null, take),
         fieldProjection.Projector);
 }
 private Expression BindSelect(Type resultType, Expression source, LambdaExpression selector)
 {
     var projection = VisitSequence(source);
     _map[selector.Parameters[0]] = projection.Projector;
     var expression = Visit(selector.Body);
     var alias = new Alias();
     var fieldProjection = _projector.ProjectFields(expression, alias, projection.Source.Alias);
     return new ProjectionExpression(
         new SelectExpression(alias, fieldProjection.Fields, projection.Source, null),
         fieldProjection.Projector);
 }
 private Expression BindSkip(Expression source, Expression skip)
 {
     var projection = VisitSequence(source);
     skip = Visit(skip);
     var alias = new Alias();
     var fieldProjection = _projector.ProjectFields(projection.Projector, alias, projection.Source.Alias);
     return new ProjectionExpression(
         new SelectExpression(alias, fieldProjection.Fields, projection.Source, null, null, null, false, skip, null),
         fieldProjection.Projector);
 }
        protected virtual Expression BindGroupBy(Expression source, LambdaExpression keySelector, LambdaExpression elementSelector, LambdaExpression resultSelector)
        {
            var projection = VisitSequence(source);

            _map[keySelector.Parameters[0]] = projection.Projector;
            var keyExpression = Visit(keySelector.Body);

            var elementExpression = projection.Projector;
            if (elementSelector != null)
            {
                _map[elementSelector.Parameters[0]] = projection.Projector;
                elementExpression = Visit(elementSelector.Body);
            }

            var subqueryBasis = VisitSequence(source);
            _map[keySelector.Parameters[0]] = subqueryBasis.Projector;
            var subqueryKeyExpression = Visit(keySelector.Body);

            var subqueryCorrelation = Expression.Equal(keyExpression, subqueryKeyExpression);

            var subqueryElementExpression = subqueryBasis.Projector;
            if (elementSelector != null)
            {
                _map[elementSelector.Parameters[0]] = subqueryBasis.Projector;
                subqueryElementExpression = Visit(elementSelector.Body);
            }

            var elementAlias = new Alias();
            var elementProjection = _projector.ProjectFields(subqueryElementExpression, elementAlias, subqueryBasis.Source.Alias);
            var elementSubquery =
                new ProjectionExpression(
                    new SelectExpression(elementAlias, elementProjection.Fields, subqueryBasis.Source, subqueryCorrelation),
                    elementProjection.Projector);

            var alias = new Alias();

            var info = new GroupByInfo(alias, elementExpression);
            _groupByMap[elementSubquery] = info;

            Expression resultExpression;
            if (resultSelector != null)
            {
                var saveGroupElement = _currentGroupElement;
                _currentGroupElement = elementSubquery;

                _map[resultSelector.Parameters[0]] = keyExpression;
                _map[resultSelector.Parameters[1]] = elementSubquery;
                resultExpression = Visit(resultSelector.Body);
                _currentGroupElement = saveGroupElement;
            }
            else
            {
                resultExpression = Expression.New(
                    typeof(Grouping<,>).MakeGenericType(keyExpression.Type, subqueryElementExpression.Type).GetConstructors()[0],
                    new[] { keyExpression, elementSubquery });
            }

            var fieldProjection = _projector.ProjectFields(resultExpression, alias, projection.Source.Alias);

            var projectedElementSubquery = ((NewExpression)fieldProjection.Projector).Arguments[1];
            _groupByMap[projectedElementSubquery] = info;

            return new ProjectionExpression(
                new SelectExpression(alias, new FieldDeclaration[0], projection.Source, null, null, keyExpression, false, null, null),
                fieldProjection.Projector);
        }
        private Expression BindOrderBy(Type resultType, Expression source, LambdaExpression orderSelector, OrderType orderType)
        {
            List<OrderExpression> thenBye = _thenBy;
            _thenBy = null;
            var projection = VisitSequence(source);

            _map[orderSelector.Parameters[0]] = projection.Projector;
            var orderings = new List<OrderExpression> {new OrderExpression(orderType, Visit(orderSelector.Body))};
            if (thenBye != null)
            {
                for (int i = thenBye.Count - 1; i >= 0; i--)
                {
                    var oe = thenBye[i];
                    var lambda = (LambdaExpression)oe.Expression;
                    _map[lambda.Parameters[0]] = projection.Projector;
                    orderings.Add(new OrderExpression(oe.OrderType, Visit(lambda.Body)));
                }
            }

            var alias = new Alias();
            var fieldProjection = _projector.ProjectFields(projection.Projector, alias, projection.Source.Alias);
            return new ProjectionExpression(
                new SelectExpression(alias, fieldProjection.Fields, projection.Source, null, orderings.AsReadOnly(), null, false, null, null),
                fieldProjection.Projector);
        }
 public GroupByInfo(Alias alias, Expression element)
 {
     Alias = alias;
     Element = element;
 }
 public CollectionExpression(Alias alias, MongoCollection collection, Type documentType)
     : base(MongoExpressionType.Collection, typeof(void), alias)
 {
     Collection = collection;
     DocumentType = documentType;
 }
Exemple #13
0
        private bool DeleteRelationshipByNameSync(string scenario, string relationshipName, string targetHandlerResourceId)
        {
            MsnServiceState serviceState = new MsnServiceState(scenario, "DeleteRelationships", false);
            StorageService storageService = (StorageService)CreateService(MsnServiceType.Storage, serviceState);

            Alias mycidAlias = new Alias();
            mycidAlias.Name = Convert.ToString(NSMessageHandler.Owner.CID);
            mycidAlias.NameSpace = "MyCidStuff";

            // 3. DeleteRelationships. If an error occurs, don't return, continue...

            // 3.1 UserTiles -> Photo
            DeleteRelationshipsRequestType request = new DeleteRelationshipsRequestType();
            request.sourceHandle = new Handle();
            request.sourceHandle.RelationshipName = relationshipName; //"/UserTiles";
            request.sourceHandle.Alias = mycidAlias;
            request.targetHandles = new Handle[] { new Handle() };
            request.targetHandles[0].ResourceID = targetHandlerResourceId;
            try
            {
                ChangeCacheKeyAndPreferredHostForSpecifiedMethod(storageService, MsnServiceType.Storage, serviceState, request);
                storageService.DeleteRelationships(request);
            }
            catch (Exception ex)
            {
                OnServiceOperationFailed(storageService, new ServiceOperationFailedEventArgs("DeleteRelationships", ex));
                Trace.WriteLineIf(Settings.TraceSwitch.TraceError, ex.Message, GetType().Name);
                return false;
            }

            return true;
        }
Exemple #14
0
        private bool CreatePhotoDocumentSync(string scenario, out string documentResourceId, string photoName, byte[] photoData)
        {
            if (photoData == null)
            {
                documentResourceId = string.Empty;
                return false;
            }

            MsnServiceState serviceState = new MsnServiceState(scenario, "CreateDocument", false);
            StorageService storageService = (StorageService)CreateService(MsnServiceType.Storage, serviceState);

            CreateDocumentRequestType createDocRequest = new CreateDocumentRequestType();

            createDocRequest.relationshipName = "ProfilePhoto";

            Handle parenthandle = new Handle();
            parenthandle.RelationshipName = @"/MyProfile/ExpressionProfile";

            Alias alias = new Alias();
            alias.NameSpace = "MyCidStuff";
            alias.Name = Convert.ToString(NSMessageHandler.Owner.CID);

            parenthandle.Alias = alias;
            createDocRequest.parentHandle = parenthandle;
            createDocRequest.document = new Photo();
            createDocRequest.document.Name = photoName;

            PhotoStream photoStream = new PhotoStream();
            photoStream.DataSize = 0;
            photoStream.MimeType = @"image/png";
            photoStream.DocumentStreamType = "UserTileStatic";
            photoStream.Data = photoData;
            createDocRequest.document.DocumentStreams = new PhotoStream[] { photoStream };

            DisplayImage displayImage = new DisplayImage(NSMessageHandler.Owner.Account.ToLowerInvariant(), new MemoryStream(photoData));

            NSMessageHandler.Owner.DisplayImage = displayImage;

            try
            {
                ChangeCacheKeyAndPreferredHostForSpecifiedMethod(storageService, MsnServiceType.Storage, serviceState, createDocRequest);
                CreateDocumentResponseType createDocResponse = storageService.CreateDocument(createDocRequest);
                documentResourceId = createDocResponse.CreateDocumentResult;
            }
            catch (Exception ex)
            {
                OnServiceOperationFailed(storageService, new ServiceOperationFailedEventArgs("CreateDocument", ex));
                Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "CreateDocument error: " + ex.Message, GetType().Name);
                documentResourceId = string.Empty;
                return false;
            }

            NSMessageHandler.ContactService.Deltas.Profile.Photo.Name = photoName;
            NSMessageHandler.ContactService.Deltas.Profile.Photo.DisplayImage = new SerializableMemoryStream();
            NSMessageHandler.ContactService.Deltas.Profile.Photo.DisplayImage.Write(photoData, 0, photoData.Length);
            NSMessageHandler.ContactService.Deltas.Save(true);

            return true;
        }
Exemple #15
0
        private Expression BindOfType(Expression source, Type selectedType)
        {
            var projection = VisitSequence(source);
            var elementType = projection.Projector.Type;

            var parameter = Expression.Parameter(elementType, "p");
            var predicate = Expression.Lambda(Expression.TypeIs(parameter, selectedType), parameter);

            _map[predicate.Parameters[0]] = projection.Projector;
            var where = Visit(predicate.Body);
            var alias = new Alias();
            var fieldProjection = _projector.ProjectFields(projection.Projector, alias, projection.Source.Alias);
            return new ProjectionExpression(
                new SelectExpression(alias, fieldProjection.Fields, projection.Source, where),
                Expression.Convert(fieldProjection.Projector, selectedType));
        }
 static Dictionary<Alias, string> FindChildren(Alias currentAlias, List<Alias> list)
 {
     Dictionary<Alias, string> result = new Dictionary<Alias, string>();
     foreach (Alias alias in list)
     {
         if (alias.Name.BeginsWithAndIsnt(currentAlias.Name))
         {
             if (alias.MetaData.HasAltName)
             {
                 result.Add(alias, alias.MetaData.AltName);
             }
             else
             {
                 result.Add(alias, currentAlias.ToOption(alias));
             }
         }
     }
     return result;
 }
        internal static string GetGeneratorName(Trade trade)
        {
            var gname = trade.GetProperty(TradeImportHelper.GeneratorProp);
            if (!string.IsNullOrEmpty(gname)) return gname;
            var template = trade.GetProperty(TradeImportHelper.TemplateProp);
            if (template != null)
            {
                var prod = trade.Product;
                string aliasSource = null;
                if (prod is MTMCurrencySwap || prod is CurrencySwap)
                    aliasSource = SwapInfo.AliasSourceCcy;
                else if (prod is FRA)
                    aliasSource = SwapInfo.AliasSourceFra;
                else if (prod is Swap)
                    aliasSource = SwapInfo.AliasSourceIrs;
                else if (prod is Swaption)
                    aliasSource = SwaptionInfo.AliasSourceSwpt;
                if (aliasSource != null)
                {
                    //if (aliasSource.Equals(SwapInfo.AliasSourceIrs) || aliasSource.Equals(SwaptionInfo.AliasSourceSwpt))
                    {
                        // use ot template -> generator mapping
                        var alias =
                            new Alias
                            {
                                AliasType = "Template",
                                EntityId = 0,
                                Source = aliasSource,
                                SourceReference = template
                            };
                        alias = Env.Current.StaticData.GetAlias(alias);
                        if (alias != null)
                        {
                            trade.SetProperty("Generator", alias.Name);
                            return alias.Name;
                        }
                    }
                    /*
                    else
                    {
                        // use generator <- ot template mapping
                        var aliases = Env.Current.StaticData.GetAliasesByName(new Alias
                            {
                                AliasType = "Template",
                                EntityId = 0,
                                Source = aliasSource,
                                Name = template
                            });
                        if (aliases != null && aliases.Count > 0)
                        {
                            var alias = aliases[0];
                            trade.SetProperty("Generator", alias.SourceReference);
                            return alias.SourceReference;

                        }
                    }*/
                }
            }
            return null;
        }
Exemple #18
0
 /// <summary>
 /// Deletes an alias from the data context.
 /// </summary>
 /// <param name="alias">The alias to be deleted.</param>
 public void DeleteAlias(Alias alias)
 {
     _entityContainer.Aliases.Remove(alias);
     _entityContainer.SaveChanges();
 }
Exemple #19
0
 /// <summary>
 /// Adds an alias to the data context.
 /// </summary>
 /// <param name="alias">The alias to be added.</param>
 public void AddAlias(Alias alias)
 {
     _entityContainer.Aliases.Add(alias);
     _entityContainer.SaveChanges();
 }
 private Expression BindWhere(Type resultType, Expression source, LambdaExpression predicate)
 {
     var projection = VisitSequence(source);
     _map[predicate.Parameters[0]] = projection.Projector;
     var where = Visit(predicate.Body);
     var alias = new Alias();
     var fieldProjection = _projector.ProjectFields(projection.Projector, alias, projection.Source.Alias);
     return new ProjectionExpression(
         new SelectExpression(alias, fieldProjection.Fields, projection.Source, where),
         fieldProjection.Projector);
 }
 private Expression BindDistinct(Expression source)
 {
     var projection = VisitSequence(source);
     var alias = new Alias();
     var fieldProjection = _projector.ProjectFields(projection.Projector, alias, projection.Source.Alias);
     return new ProjectionExpression(
         new SelectExpression(alias, fieldProjection.Fields, projection.Source, null, null, null, true, null, null),
         fieldProjection.Projector);
 }
 private ProjectionExpression GetCollectionProjection(object value)
 {
     var collectionAlias = new Alias();
     var selectAlias = new Alias();
     var collection = (IMongoQueryable)value;
     var fields = new List<FieldDeclaration>();
     return new ProjectionExpression(
         new SelectExpression(selectAlias, fields, new CollectionExpression(collectionAlias, collection.Database, collection.CollectionName, collection.ElementType), null),
         Expression.Parameter(collection.ElementType, "document"));
 }
        private Expression BindFirstOrSingle(Expression source, LambdaExpression predicate, string kind, bool isRoot)
        {
            var projection = VisitSequence(source);
            Expression where = null;
            if (predicate != null)
            {
                _map[predicate.Parameters[0]] = projection.Projector;
                where = Visit(predicate.Body);
            }

            Expression take = kind.StartsWith("First") ? Expression.Constant(1) : null;
            if (take == null & kind.StartsWith("Single"))
                take = Expression.Constant(2);

            if (take != null || where != null)
            {
                var alias = new Alias();
                var fieldProjection = _projector.ProjectFields(projection.Projector, alias, projection.Source.Alias);
                projection = new ProjectionExpression(
                    new SelectExpression(alias, fieldProjection.Fields, projection.Source, where, null, null, false, null, take),
                    fieldProjection.Projector);
            }
            if (isRoot)
            {
                var elementType = projection.Projector.Type;
                var p = Expression.Parameter(typeof(IEnumerable<>).MakeGenericType(elementType), "p");
                var lambda = Expression.Lambda(Expression.Call(typeof(Enumerable), kind, new[] { elementType }, p), p);
                return new ProjectionExpression(projection.Source, projection.Projector, lambda);
            }
            return projection;
        }
 protected AliasedExpression(MongoExpressionType nodeType, Type type, Alias alias)
     : base(nodeType, type)
 {
     Alias = alias;
 }
Exemple #25
0
        private InternalOperationReturnValues GetProfileLiteSync(string scenario, out string profileResourceId, out string expressionProfileResourceId, bool syncToOwner)
        {
            MsnServiceState serviceState = new MsnServiceState(scenario, "GetProfile", false);
            StorageService storageService = (StorageService)CreateService(MsnServiceType.Storage, serviceState);

            GetProfileRequestType getprofileRequest = new GetProfileRequestType();

            Alias alias = new Alias();
            alias.NameSpace = "MyCidStuff";
            alias.Name = Convert.ToString(NSMessageHandler.Owner.CID);

            Handle pHandle = new Handle();
            pHandle.RelationshipName = "MyProfile";
            pHandle.Alias = alias;

            getprofileRequest.profileHandle = pHandle;
            getprofileRequest.profileAttributes = new profileAttributes();

            ExpressionProfileAttributesType expAttrib = CreateFullExpressionProfileAttributes();

            getprofileRequest.profileAttributes.ExpressionProfileAttributes = expAttrib;

            try
            {
                ChangeCacheKeyAndPreferredHostForSpecifiedMethod(storageService, MsnServiceType.Storage, serviceState, getprofileRequest);
                GetProfileResponse response = storageService.GetProfile(getprofileRequest);

                #region Process Profile
                profileResourceId = response.GetProfileResult.ResourceID;

                if (response.GetProfileResult.ExpressionProfile == null)
                {
                    Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Get profile cannot get expression profile of this owner.");
                    NSMessageHandler.ContactService.Deltas.Profile.HasExpressionProfile = false;
                    NSMessageHandler.ContactService.Deltas.Profile.DisplayName = NSMessageHandler.Owner.Name;

                    expressionProfileResourceId = string.Empty;
                    return InternalOperationReturnValues.NoExpressionProfile;
                }
                else
                {
                    NSMessageHandler.ContactService.Deltas.Profile.HasExpressionProfile = true;
                    NSMessageHandler.ContactService.Deltas.Profile.ExpressionProfile.ResourceID = response.GetProfileResult.ExpressionProfile.ResourceID;
                    NSMessageHandler.ContactService.Deltas.Profile.ExpressionProfile.DateModified = response.GetProfileResult.ExpressionProfile.DateModified;

                    expressionProfileResourceId = response.GetProfileResult.ExpressionProfile.ResourceID;
                }

                NSMessageHandler.ContactService.Deltas.Profile.DateModified = response.GetProfileResult.DateModified;
                NSMessageHandler.ContactService.Deltas.Profile.ResourceID = response.GetProfileResult.ResourceID;

                // Display name
                NSMessageHandler.ContactService.Deltas.Profile.DisplayName = response.GetProfileResult.ExpressionProfile.DisplayName;

                // Personal status
                if (response.GetProfileResult.ExpressionProfile.PersonalStatus != null)
                {
                    NSMessageHandler.ContactService.Deltas.Profile.PersonalMessage = response.GetProfileResult.ExpressionProfile.PersonalStatus;
                }

                NSMessageHandler.ContactService.Deltas.Save(true);

                // Display photo
                if (null != response.GetProfileResult.ExpressionProfile.Photo)
                {
                    foreach (DocumentStream docStream in response.GetProfileResult.ExpressionProfile.Photo.DocumentStreams)
                    {
                        if (docStream.DocumentStreamType != "UserTileStatic")
                        {
                            continue;
                        }

                        if (NSMessageHandler.ContactService.Deltas.Profile.Photo.PreAthURL == docStream.PreAuthURL)
                        {
                            if (syncToOwner)
                            {
                                DisplayImage newDisplayImage = new DisplayImage(NSMessageHandler.Owner.Account.ToLowerInvariant(), NSMessageHandler.ContactService.Deltas.Profile.Photo.DisplayImage);

                                NSMessageHandler.Owner.DisplayImage = newDisplayImage;
                            }
                        }
                        else
                        {
                            string requesturi = docStream.PreAuthURL;
                            if (requesturi.StartsWith("/"))
                            {
                                requesturi = "http://blufiles.storage.msn.com" + requesturi;  //I found it http://byfiles.storage.msn.com is also ok
                            }

                            // Don't urlencode t= :))
                            string usertitleURL = requesturi + "?t=" + System.Web.HttpUtility.UrlEncode(NSMessageHandler.MSNTicket.SSOTickets[SSOTicketType.Storage].Ticket.Substring(2));
                            SyncUserTile(usertitleURL,
                                syncToOwner,
                                delegate(object imageStream)
                                {
                                    SerializableMemoryStream ms = imageStream as SerializableMemoryStream;
                                    NSMessageHandler.ContactService.Deltas.Profile.Photo.Name = response.GetProfileResult.ExpressionProfile.Photo.Name;
                                    NSMessageHandler.ContactService.Deltas.Profile.Photo.DateModified = response.GetProfileResult.ExpressionProfile.Photo.DateModified;
                                    NSMessageHandler.ContactService.Deltas.Profile.Photo.ResourceID = response.GetProfileResult.ExpressionProfile.Photo.ResourceID;
                                    NSMessageHandler.ContactService.Deltas.Profile.Photo.PreAthURL = docStream.PreAuthURL;
                                    if (ms != null)
                                    {
                                        NSMessageHandler.ContactService.Deltas.Profile.Photo.DisplayImage = ms;
                                    }

                                    NSMessageHandler.ContactService.Deltas.Save(true);
                                },
                                delegate(object param)
                                {
                                    Exception ex = param as Exception;
                                    Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "Get DisplayImage error: " + ex.Message, GetType().Name);
                                    if (NSMessageHandler.Owner.UserTileURL != null)
                                    {
                                        SyncUserTile(NSMessageHandler.Owner.UserTileURL.AbsoluteUri, syncToOwner, null, null);
                                    }
                                });

                        }
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                OnServiceOperationFailed(storageService, new ServiceOperationFailedEventArgs("GetProfile", ex));
                Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "GetProfile error: " + ex.Message, GetType().FullName);
                expressionProfileResourceId = string.Empty;
                profileResourceId = string.Empty;

                if (ex.Message.ToLowerInvariant().Contains("does not exist"))
                {
                    return InternalOperationReturnValues.ProfileNotExist;
                }

                return InternalOperationReturnValues.RequestFailed;
            }

            return InternalOperationReturnValues.Succeed;
        }
        private Expression BindAggregate(Expression source, MethodInfo method, LambdaExpression argument, bool isRoot)
        {
            var returnType = method.ReturnType;
            var aggregateType = GetAggregateType(method.Name);
            bool hasPredicateArgument = HasPredicateArgument(aggregateType);
            bool distinct = false;
            bool argumentWasPredicate = false;

            var methodCallExpression = source as MethodCallExpression;
            if (methodCallExpression != null && !hasPredicateArgument && argument == null)
            {
                if (methodCallExpression.Method.Name == "Distinct" && methodCallExpression.Arguments.Count == 1
                    && (methodCallExpression.Method.DeclaringType == typeof(Queryable) || methodCallExpression.Method.DeclaringType == typeof(Enumerable)))
                {
                    source = methodCallExpression.Arguments[0];
                    distinct = true;
                }
            }

            if (argument != null && hasPredicateArgument)
            {
                source = Expression.Call(typeof(Queryable), "Where", method.GetGenericArguments(), source, argument);
                argument = null;
                argumentWasPredicate = true;
            }

            var projection = VisitSequence(source);
            Expression argExpression = null;
            if (argument != null)
            {
                _map[argument.Parameters[0]] = projection.Projector;
                argExpression = Visit(argument.Body);
            }
            else if (!hasPredicateArgument)
                argExpression = projection.Projector;

            var alias = new Alias();
            Expression aggregateExpression = new AggregateExpression(returnType, aggregateType, argExpression, distinct);
            var selectType = typeof(IEnumerable<>).MakeGenericType(returnType);
            string fieldName = "_$agg" + (_aggregateCount++);
            var select = new SelectExpression(alias, new[] { new FieldDeclaration(fieldName, aggregateExpression) }, projection.Source, null);

            if (isRoot)
            {
                var parameter = Expression.Parameter(selectType, "p");
                var lambda = Expression.Lambda(Expression.Call(typeof(Enumerable), "Single", new[] { returnType }, parameter), parameter);
                return new ProjectionExpression(
                    select,
                    new FieldExpression(aggregateExpression, alias, fieldName),
                    lambda);
            }

            var subquery = new ScalarExpression(returnType, select);

            GroupByInfo info;
            if (!argumentWasPredicate && _groupByMap.TryGetValue(projection, out info))
            {
                if (argument != null)
                {
                    _map[argument.Parameters[0]] = info.Element;
                    argExpression = Visit(argument.Body);
                }
                else if (!hasPredicateArgument)
                    argExpression = info.Element;

                aggregateExpression = new AggregateExpression(returnType, aggregateType, argExpression, distinct);

                if (projection == _currentGroupElement)
                    return aggregateExpression;

                return new AggregateSubqueryExpression(info.Alias, aggregateExpression, subquery);
            }

            return subquery;
        }
        /// <summary>
        /// Creates an <see cref="Alias"/> object from a using import (such as using in C++ and C# and import in Java).
        /// </summary>
        /// <param name="aliasStatement">The statement to parse. Should be of type <see cref="AliasElementName"/></param>
        /// <param name="context">The context to place the resulting alias in</param>
        /// <returns>a new alias object that represents this alias statement</returns>
        public Alias ParseAliasElement(XElement aliasStatement, ParserContext context) {
            if(null == aliasStatement) throw new ArgumentNullException("aliasStatement");
            if(aliasStatement.Name != AliasElementName) throw new ArgumentException(String.Format("must be a {0} statement", AliasElementName), "usingStatement");

            var alias = new Alias() {
                Location = context.CreateLocation(aliasStatement, true),
                ProgrammingLanguage = ParserLanguage,
            };

            IEnumerable<XElement> namespaceNames = GetNamesFromAlias(aliasStatement);

            if(!AliasIsNamespaceImport(aliasStatement)) {
                var lastNameElement = namespaceNames.LastOrDefault();
                namespaceNames = from name in namespaceNames
                                 where name.IsBefore(lastNameElement)
                                 select name;

                alias.ImportedNamedScope = new NamedScopeUse() {
                    Name = lastNameElement.Value,
                    Location = context.CreateLocation(lastNameElement),
                    ProgrammingLanguage = ParserLanguage,
                };
            }

            NamespaceUse current = null;
            foreach(var namespaceName in namespaceNames) {
                var use = new NamespaceUse() {
                    Name = namespaceName.Value,
                    Location = context.CreateLocation(namespaceName),
                    ProgrammingLanguage = ParserLanguage,
                };

                if(alias.ImportedNamespace == null) {
                    alias.ImportedNamespace = use;
                    current = use;
                } else {
                    current.ChildScopeUse = use;
                    current = use;
                }
            }

            return alias;
        }