public void GenerateInstallEvents()
 {
     //TEMP: this is really part of the extension manager's job. an extension
     // install event is being simulated here on each web app startup
     var enabled = new List<ExtensionEntry>();
     foreach (var extension in _extensionManager.ActiveExtensions_Obsolete()) {
         var context = new ExtensionEventContext {
                                                     Extension = extension,
                                                     EnabledExtensions = enabled.ToReadOnlyCollection(),
                                                 };
         _extensionEvents.Invoke(x => x.Enabling(context), Logger);
         enabled.Add(extension);
         context.EnabledExtensions = enabled.ToReadOnlyCollection();
         _extensionEvents.Invoke(x => x.Enabled(context), Logger);
     }
 }
        public ReadOnlyCollection<ExternalLink> GetAllLinks()
        {
            const int count = 50;
            var i = 0;
            var allExternalLinks = new List<ExternalLink>();

            do
            {
                var currentLinks = _fave.GetLinks(count, i * count);
                if (currentLinks != null) allExternalLinks.AddRange(currentLinks);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return allExternalLinks.ToReadOnlyCollection();
        }
        public ReadOnlyCollection<User> GetAll(long uid, ProfileFields fields = null, FriendsOrder order = null, NameCase nameCase = null, int? listId = null)
        {
            const int count = 50;
            var i = 0;
            var result = new List<User>();

            do
            {
                var currentItems = _friends.Get(uid, fields, count, i * count, order, nameCase, listId);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
        public ReadOnlyCollection<Document> GetAll(long? owner_id = null)
        {
            const int count = 50;
            var i = 0;
            var result = new List<Document>();

            do
            {
                var currentItems = _docs.Get(count, i * count, owner_id);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
        public ReadOnlyCollection<City> GetAllCities(int countryId, int? regionId = null, string query = "", bool? needAll = false)
        {
            const int count = 1000;
            var i = 0;
            var result = new List<City>();

            do
            {
                var currentItems = _database.GetCities(countryId, regionId, query, needAll, count, i * count);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
        public ReadOnlyCollection<User> GetAllBanned(long groupId)
        {
            const int count = 200;
            var i = 0;
            var result = new List<User>();

            do
            {
                var currentItems = _groups.GetBanned(groupId, count, i * count);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
        public ReadOnlyCollection<Group> GetAll(long uid, bool extended = false, GroupsFilters filters = null, GroupsFields fields = null)
        {
            const int count = 1000;
            var i = 0;
            var result = new List<Group>();

            do
            {
                var currentItems = _groups.Get(uid, extended, filters, fields, i * count, count);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
        public ReadOnlyCollection<Video> GetAll(long? ownerId = null, long? albumId = null, VideoWidth width = VideoWidth.Medium160, bool extended = false)
        {
            const int count = 200;
            var i = 0;
            var result = new List<Video>();

            do
            {
                var currentItems = _video.Get(ownerId, albumId, width, count, i * count, extended);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
        public ReadOnlyCollection<Photo> GetAllPhotos()
        {
            const int count = 50;
            var i = 0;
            var allPhotos = new List<Photo>();

            do
            {
                var currentPhotos = _fave.GetPhotos(count, i * count);
                if (currentPhotos != null) allPhotos.AddRange(currentPhotos);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return allPhotos.ToReadOnlyCollection();
        }
        public ReadOnlyCollection<Audio> GetAll(long uid, out User user, long? albumId = null, IEnumerable<long> aids = null)
        {
            const int count = 6000;
            var i = 0;
            var result = new List<Audio>();

            do
            {
                var currentItems = _audio.Get(uid, out user, albumId, aids, count, i * count);
                if (currentItems != null) result.AddRange(currentItems);
            } while ((++i * count < (_vk.CountFromLastResponse ?? 0)) && (i * count < 6000));

            return result.ToReadOnlyCollection();
        }
        public ReadOnlyCollection<User> GetAllFollowers(long? userId = null, ProfileFields fields = null, NameCase nameCase = null)
        {
            const int count = 1000;
            var i = 0;
            var result = new List<User>();

            do
            {
                var currentItems = _users.GetFollowers(userId, count, i * count, fields, nameCase);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
        public IEnumerable<User> GetAllBanned()
        {
            const int count = 200;
            var i = 0;
            var result = new List<User>();

            do
            {
                int total;
                var currentItems = _account.GetBanned(out total, i * count, count);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
Example #13
0
        public ReadOnlyCollection<Post> GetAll(long ownerId, WallFilter filter = WallFilter.All)
        {
            const int count = 100;
            var i = 0;
            var allPosts = new List<Post>();

            do
            {
                int totalCount;
                var currentPosts = _wall.Get(ownerId, out totalCount, count, i * count, filter);
                if (currentPosts != null) allPosts.AddRange(currentPosts);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return allPosts.ToReadOnlyCollection();
        }
        protected override Expression VisitMethodDefinitionExpression(MethodDefinitionExpression method)
        {
            var methodName = method.Name.ToCamelCase();

            var body = new Expression[]
            {
                Expression.Return(Expression.Label(), Expression.Constant(null)).ToStatement()
            };

            var responseType = ObjectiveBinderHelpers.GetWrappedResponseType(this.CodeGenerationContext, method.ReturnType);

            var newParameters = new List<Expression>(method.Parameters)
            {
                FickleExpression.Parameter(new FickleDelegateType(typeof(void), new FickleParameterInfo(responseType, "response")), "callback")
            };

            return new MethodDefinitionExpression(methodName, newParameters.ToReadOnlyCollection(), typeof(void), Expression.Block(body), true, null);
        }
        public ReadOnlyCollection<Message> GetAll(
            MessageType type,
            out int totalCount,
            TimeSpan? timeOffset = null,
            MessagesFilter? filter = null,
            int? previewLength = null,
            long? lastMessageId = null)
        {
            const int count = 200;
            var i = 0;
            var result = new List<Message>();

            do
            {
                var currentItems = _messages.Get(type, out totalCount, count, i * count, timeOffset, filter, previewLength, lastMessageId);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
		protected override Expression VisitSelect(SqlSelectExpression select)
		{
			select = (SqlSelectExpression)base.VisitSelect(select);

			if (this.aggregateSubqueriesBySelectAlias.Contains(select.Alias))
			{
				var columnsIncludingAggregates = new List<SqlColumnDeclaration>(select.Columns);

				foreach (var aggregateSubqueryExpression in this.aggregateSubqueriesBySelectAlias[select.Alias])
				{
					var name = "__AGGR" + columnsIncludingAggregates.Count;

					var columnDeclaration = new SqlColumnDeclaration(name, aggregateSubqueryExpression.AggregateInGroupSelect);

					this.aggregateSubqueryInstances.Add(aggregateSubqueryExpression, new SqlColumnExpression(aggregateSubqueryExpression.Type, aggregateSubqueryExpression.GroupByAlias, name));

					columnsIncludingAggregates.Add(columnDeclaration);
				}

				return new SqlSelectExpression(select.Type, select.Alias, columnsIncludingAggregates.ToReadOnlyCollection(), select.From, select.Where, select.OrderBy, select.GroupBy, select.Distinct, select.Skip, select.Take, select.ForUpdate);
			}

			return select;
		}
        private MethodDefinitionExpression CreateInitMethod(TypeDefinitionExpression expression)
        {
            var type = expression.Type;
            Expression superInitExpression;

            var parameters = new List<Expression>
            {
                Expression.Parameter(new FickleType("NSDictionary"), "properties")
            };

            var methodBodyExpressions = new List<Expression>();

            if (type.BaseType.IsServiceType())
            {
                superInitExpression = Expression.Call(Expression.Parameter(type.BaseType, "super"), new FickleMethodInfo(type.BaseType, type, "initWithPropertyDictionary", new [] { new FickleParameterInfo(parameters[0].Type, "dictionary")}), parameters[0]);
            }
            else
            {
                superInitExpression = Expression.Call(Expression.Parameter(type.BaseType, "super"), new FickleMethodInfo(type.BaseType, type, "init", new ParameterInfo[0]));
            }

            var assignExpression = Expression.Assign(Expression.Parameter(type, "self"), superInitExpression);
            var compareToNullExpression = Expression.ReferenceEqual(assignExpression, Expression.Constant(null, type));
            int count;

            methodBodyExpressions.Add(Expression.IfThen(compareToNullExpression, Expression.Block(Expression.Return(Expression.Label(), Expression.Constant(null)).ToStatement())));
            methodBodyExpressions.Add(PropertiesFromDictionaryExpressonBinder.Bind(expression, out count));
            methodBodyExpressions.Add(Expression.Return(Expression.Label(), Expression.Parameter(type, "self")).ToStatement());

            IEnumerable<ParameterExpression> variables;

            if (count > 0)
            {
                variables = new[] { Expression.Parameter(FickleType.Define("id"), "currentValueFromDictionary") };
            }
            else
            {
                variables = new ParameterExpression[0];
            }

            var methodBody = Expression.Block(variables, (Expression)methodBodyExpressions.ToStatementisedGroupedExpression(GroupedExpressionsExpressionStyle.Wide));

            return new MethodDefinitionExpression("initWithPropertyDictionary", parameters.ToReadOnlyCollection(), typeof(object), methodBody, false, null);
        }
        protected override Expression VisitTypeDefinitionExpression(TypeDefinitionExpression expression)
        {
            var includeExpressions = new List<IncludeExpression>();
            var importExpressions = new List<Expression>();

            var optionsProperty = new PropertyDefinitionExpression("options", FickleType.Define("NSDictionary"), true);
            var responseFilterProperty = new PropertyDefinitionExpression("responseFilter", FickleType.Define("FKGatewayResponseFilter", isInterface:true), true, new[] { "weak" });

            var body = FickleExpression.GroupedWide
            (
                optionsProperty,
                responseFilterProperty,
                new GroupedExpressionsExpression(methods.Select(c => c.ChangePredeclaration(true)))
            );

            var referencedTypes = ReferencedTypesCollector.CollectReferencedTypes(body);
            referencedTypes.Sort((x, y) => String.Compare(x.Name, y.Name, StringComparison.InvariantCultureIgnoreCase));

            var lookup = new HashSet<Type>(referencedTypes.Where(TypeSystem.IsPrimitiveType));

            if (!this.CodeGenerationContext.Options.ImportDependenciesAsFramework)
            {
                if (lookup.Contains(typeof(Guid)) || lookup.Contains(typeof(Guid?)))
                {
                    includeExpressions.Add(FickleExpression.Include("PKUUID.h"));
                }

                if (lookup.Contains(typeof(TimeSpan)) || lookup.Contains(typeof(TimeSpan?)))
                {
                    includeExpressions.Add(FickleExpression.Include("PKTimeSpan.h"));
                }

                includeExpressions.Add(FickleExpression.Include("PKWebServiceClient.h"));
                includeExpressions.Add(FickleExpression.Include("PKDictionarySerializable.h"));
            }
            else
            {
                importExpressions.Add(new CodeLiteralExpression(c => c.WriteLine("@import PlatformKit;")));
            }

            includeExpressions.Add(FickleExpression.Include("FKGatewayResponseFilter.h"));

            var referencedUserTypes = referencedTypes
                .Where(c => (c is FickleType && ((FickleType)c).ServiceClass != null) || c is FickleType && ((FickleType)c).ServiceEnum != null)
                .Sorted((x, y) => x.Name.Length == y.Name.Length ? String.CompareOrdinal(x.Name, y.Name) : x.Name.Length - y.Name.Length);

            includeExpressions.AddRange(referencedUserTypes.Select(c => FickleExpression.Include(c.Name + ".h")));

            var comment = new CommentExpression("This file is AUTO GENERATED");

            var header = new Expression[]
            {
                comment,
                importExpressions.Count == 0 ? null : importExpressions.ToStatementisedGroupedExpression(),
                includeExpressions.Sorted(IncludeExpression.Compare).ToStatementisedGroupedExpression()
            }.ToStatementisedGroupedExpression(GroupedExpressionsExpressionStyle.Wide);

            var interfaceTypes = new List<Type>();

            if (expression.InterfaceTypes != null)
            {
                interfaceTypes.AddRange(expression.InterfaceTypes);
            }

            interfaceTypes.Add(FickleType.Define("PKWebServiceClientDelegate"));

            return new TypeDefinitionExpression(expression.Type, header, body, true, expression.Attributes, interfaceTypes.ToReadOnlyCollection());
        }
Example #19
0
        public static IEnumerable<Folder> GetFolders(XElement element, out IDictionary<Guid, Folder> folderMapper)
        {
            Contract.Requires(element.Name == "Folders");
            var list = new List<Folder>();
            Guid key;
            Folder folder;
            folderMapper = new Dictionary<Guid, Folder>();
            foreach (var folderElement in element.Elements())
            {
                list.Add(folder = GetFolder(folderElement, out key));
                folderMapper[key] = folder;
            }

            return list.ToReadOnlyCollection();
        }
        protected override Expression VisitTypeDefinitionExpression(TypeDefinitionExpression expression)
        {
            var includeExpressions = new List<IncludeExpression>();
            var optionsProperty = new PropertyDefinitionExpression("options", FickleType.Define("NSDictionary"), true);

            var body = FickleExpression.GroupedWide
            (
                optionsProperty,
                FickleExpression.Grouped
                (
                    this.CreateInitWithOptionsMethod(),
                    this.Visit(expression.Body)
                )
            );

            var referencedTypes = ReferencedTypesCollector.CollectReferencedTypes(body);
            referencedTypes.Sort((x, y) => String.Compare(x.Name, y.Name, StringComparison.InvariantCultureIgnoreCase));

            var lookup = new HashSet<Type>(referencedTypes.Where(TypeSystem.IsPrimitiveType));

            if (lookup.Contains(typeof(Guid)) || lookup.Contains(typeof(Guid?)))
            {
                includeExpressions.Add(FickleExpression.Include("PKUUID.h"));
            }

            if (lookup.Contains(typeof(TimeSpan)) || lookup.Contains(typeof(TimeSpan?)))
            {
                includeExpressions.Add(FickleExpression.Include("PKTimeSpan.h"));
            }

            includeExpressions.Add(FickleExpression.Include("PKDictionarySerializable.h"));
            includeExpressions.Add(FickleExpression.Include("PKWebServiceClient.h"));

            var referencedUserTypes = referencedTypes
                .Where(c => (c is FickleType && ((FickleType)c).ServiceClass != null) || c is FickleType && ((FickleType)c).ServiceEnum != null)
                .Sorted((x, y) => x.Name.Length == y.Name.Length ? String.CompareOrdinal(x.Name, y.Name) : x.Name.Length - y.Name.Length);

            includeExpressions.AddRange(referencedUserTypes.Select(c => FickleExpression.Include(c.Name + ".h")));

            var comment = new CommentExpression("This file is AUTO GENERATED");
            var header = new Expression[] { comment, includeExpressions.Sorted(IncludeExpression.Compare).ToStatementisedGroupedExpression() }.ToStatementisedGroupedExpression(GroupedExpressionsExpressionStyle.Wide);

            var interfaceTypes = new List<Type>();

            if (expression.InterfaceTypes != null)
            {
                interfaceTypes.AddRange(expression.InterfaceTypes);
            }

            interfaceTypes.Add(FickleType.Define("PKWebServiceClientDelegate"));

            return new TypeDefinitionExpression(expression.Type, header, body, true, expression.Attributes, interfaceTypes.ToReadOnlyCollection());
        }
        public ReadOnlyCollection<Audio> SearchAll(
            string query,
            out int totalCount,
            bool? autoComplete = null,
            AudioSort? sort = null,
            bool? findLyrics = null)
        {
            const int count = 300;
            var i = 0;
            var result = new List<Audio>();

            do
            {
                var currentItems = _audio.Search(query, out totalCount, autoComplete, sort, findLyrics, count, i * count);
                if (currentItems != null) result.AddRange(currentItems);
            } while ((++i * count < (_vk.CountFromLastResponse ?? 0)) && (i * count < 1000));

            return result.ToReadOnlyCollection();
        }
Example #22
0
        public ReadOnlyCollection<Comment> GetAllComments(
            long ownerId,
            long postId,
            CommentsSort sort = null,
            bool needLikes = false,
            int previewLength = 0)
        {
            const int count = 100;
            var i = 0;
            var allComments = new List<Comment>();

            do
            {
                int totalCount;
                var currentComments = _wall.GetComments(ownerId, postId, out totalCount, sort, needLikes, count, i * count, previewLength);
                if (currentComments != null) allComments.AddRange(currentComments);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return allComments.ToReadOnlyCollection();
        }
        protected override Expression VisitMethodDefinitionExpression(MethodDefinitionExpression method)
        {
            var client = Expression.Variable(this.httpClientType, HttpClientFieldName);

            var methodName = method.Name;
            var methodParameters = new List<Expression>(method.Parameters);
            var methodVariables = new List<ParameterExpression>();
            var methodStatements = new List<Expression>();

            var hostname = this.currentTypeDefinitionExpression.Attributes["Hostname"];
            var fullPath = "http://" + hostname + method.Attributes["Path"];
            var relativePath = method.Attributes["Path"];

            if (relativePath.StartsWith("/"))
            {
                relativePath = relativePath.Substring(1);
            }

            var requestUrl = Expression.Variable(typeof(InterpolatedString), "requestUrl");
            methodVariables.Add(requestUrl);

            var baseAddressProperty = FickleExpression.Property(client, this.httpClientType, "BaseAddress");
            methodStatements.Add(Expression.IfThenElse(Expression.Equal(baseAddressProperty, Expression.Constant(null)),
                Expression.Assign(requestUrl, Expression.Constant(new InterpolatedString(fullPath))).ToStatementBlock(),
                Expression.Assign(requestUrl, Expression.Constant(new InterpolatedString(relativePath))).ToStatementBlock()));

            var httpMethodType = FickleType.Define("HttpMethod");
            var httpRequestMessageType = FickleType.Define("HttpRequestMessage");
            var httpRequestMessagesArgs = new
            {
                httpMethod = FickleExpression.New(httpMethodType, "HttpMethod", method.Attributes["Method"]),
                requestUrl
            };

            var httpRequestMessageNew = FickleExpression.New(httpRequestMessageType, "HttpRequestMessage", httpRequestMessagesArgs);
            var httpRequestMessage = Expression.Variable(httpRequestMessageType, "httpRequestMessage");
            methodVariables.Add(httpRequestMessage);
            methodStatements.Add(Expression.Assign(httpRequestMessage, httpRequestMessageNew));

            var streamType = FickleType.Define("Stream");
            var httpStreamSerializer = Expression.Variable(this.httpStreamSerializerType, HttpStreamSerializerFieldName);

            var contentParameterName = method.Attributes["Content"];

            if (!string.IsNullOrEmpty(contentParameterName))
            {
                var contentParam = method.Parameters.FirstOrDefault(x => ((ParameterExpression)x).Name.Equals(contentParameterName, StringComparison.InvariantCultureIgnoreCase));

                if (contentParam == null)
                {
                    throw new Exception("Content paramter not found");
                }

                var serializeCall = FickleExpression.Call(httpStreamSerializer, typeof(string), "Serialize", contentParam);
                var stringContentNew = FickleExpression.New(FickleType.Define("StringContent"), "StringContent", serializeCall);
                methodStatements.Add(Expression.Assign(FickleExpression.Property(httpRequestMessage, httpRequestMessageType, "Content"), stringContentNew));
            }

            var httpResponseMessageType = FickleType.Define("HttpResponseMessage");
            var httpResponseMessage = Expression.Variable(httpResponseMessageType, "httpResponseMessage");
            methodVariables.Add(httpResponseMessage);

            var clientCall = FickleExpression.Call(client, new CSharpAwaitedTaskType(httpResponseMessageType), "SendAsync", httpRequestMessage);
            methodStatements.Add(Expression.Assign(httpResponseMessage, clientCall));
            methodStatements.Add(FickleExpression.Call(httpResponseMessage, "EnsureSuccessStatusCode", null));

            if (method.ReturnType != typeof (void))
            {
                var result = Expression.Variable(method.ReturnType, "result");
                methodVariables.Add(result);

                var contentStream = Expression.Variable(streamType, "contentStream");
                methodVariables.Add(contentStream);
                methodStatements.Add(Expression.Assign(contentStream, Expression.Constant(null)));

                var responseContent = Expression.Property(httpResponseMessage, "Content");
                var contentStreamCall = FickleExpression.Call(responseContent, new CSharpAwaitedTaskType(streamType), "ReadAsStreamAsync", null);

                var deserializeCall = FickleExpression.Call(httpStreamSerializer, method.ReturnType, "Deserialize", contentStream);
                deserializeCall.Method.MakeGenericMethod(method.ReturnType);

                var tryBlock = FickleExpression.Grouped(
                    Expression.Assign(contentStream, contentStreamCall).ToStatement(),
                    Expression.Assign(result, deserializeCall).ToStatement()
                    );

                var diposeStream = Expression.IfThen(Expression.NotEqual(contentStream, Expression.Constant(null)), FickleExpression.Call(contentStream, "Dispose", null).ToStatementBlock());

                var tryFinally = Expression.TryFinally(tryBlock, diposeStream);
                methodStatements.Add(tryFinally);

                methodStatements.Add(FickleExpression.Return(result));
            }

            var methodBody = FickleExpression.Block
            (
                methodVariables.ToArray(),
                methodStatements.ToArray()
            );

            var returnType = method.ReturnType != typeof (void) ? method.ReturnType : null;
            var returnTaskType = new CSharpAwaitedTaskType(returnType);

            return new MethodDefinitionExpression(methodName, methodParameters.ToReadOnlyCollection(), AccessModifiers.Public, returnTaskType, methodBody, false, null);
        }
        public ReadOnlyCollection<long> GetAllRequests(bool extended = false, bool needMutual = false, bool @out = false, bool sort = false, bool suggested = false)
        {
            const int count = 1000;
            var i = 0;
            var result = new List<long>();

            do
            {
                var currentItems = _friends.GetRequests(count, i * count, extended, needMutual, @out, sort, suggested);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
        public ReadOnlyCollection<AudioAlbum> GetAllAlbums(long ownerid)
        {
            const int count = 100;
            var i = 0;
            var result = new List<AudioAlbum>();

            do
            {
                var currentItems = _audio.GetAlbums(ownerid, count, i * count);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
        public ReadOnlyCollection<Audio> GetAllPopular(bool onlyEng = false, AudioGenre? genre = null)
        {
            const int count = 1000;
            var i = 0;
            var result = new List<Audio>();

            do
            {
                var currentItems = _audio.GetPopular(onlyEng, genre, count, i * count);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }
Example #27
0
        protected override Expression VisitMethodDefinitionExpression(MethodDefinitionExpression method)
        {
            var methodName = method.Name.Uncapitalize();
            var methodParameters = new List<Expression>(method.Parameters);
            var methodVariables = new List<ParameterExpression>();
            var methodStatements = new List<Expression>();

            var requestParameters = new List<Expression>(method.Parameters);

            var httpMethod = method.Attributes["Method"];
            var hostname = currentTypeDefinitionExpression.Attributes["Hostname"];
            var path = "http://" + hostname + method.Attributes["Path"];

            var client = Expression.Variable(webServiceClientType, "webServiceClient");
            var responseType = JavaBinderHelpers.GetWrappedResponseType(this.CodeGenerationContext, method.ReturnType);
            var responseTypeArgument = Expression.Variable(typeof(String), responseType.Name + ".class");
            var callback = Expression.Parameter(new FickleType("RequestCallback<" + responseType.Name + ">"), "callback");

            methodParameters.Add(callback);

            var url = Expression.Variable(typeof(string), "url");

            methodVariables.Add(url);
            methodStatements.Add(Expression.Assign(url, Expression.Constant(path)));

            Object serviceCallArguments;

            if (httpMethod.Equals("post", StringComparison.InvariantCultureIgnoreCase)
                || httpMethod.Equals("put", StringComparison.InvariantCultureIgnoreCase))
            {
                var contentParameterName = method.Attributes["Content"];

                var contentParam = requestParameters.FirstOrDefault(x => ((ParameterExpression)x).Name.Equals(contentParameterName, StringComparison.InvariantCultureIgnoreCase));

                if (contentParam == null)
                {
                    throw new Exception("Post or Put method defined with null Content. You must define a @content field in your FicklefileKeyword");
                }

                requestParameters = requestParameters.Where(x => x != contentParam).ToList();

                var payloadVar = Expression.Variable(typeof(string), "requestPayload");

                methodVariables.Add(payloadVar);

                var jsonBuilder = FickleType.Define("DefaultJsonBuilder");

                var jsonBuilderInstance = FickleExpression.StaticCall(jsonBuilder, "instance");

                var toJsonCall = FickleExpression.Call(jsonBuilderInstance, typeof(String), "toJson", contentParam);

                var payloadAssign = Expression.Assign(payloadVar, toJsonCall);

                methodStatements.Add(payloadAssign);

                serviceCallArguments = new
                {
                    url,
                    responseTypeArgument,
                    payloadVar,
                    callback
                };
            }
            else
            {
                serviceCallArguments = new
                {
                    url,
                    responseTypeArgument,
                    callback
                };
            }

            foreach (var parameter in requestParameters)
            {
                var param = (ParameterExpression)parameter;

                if (param.Type is FickleNullable)
                {
                    param = FickleExpression.Parameter(param.Type.GetUnwrappedNullableType(), param.Name);
                }

                var valueToReplace = Expression.Constant("{" + param.Name + "}", typeof(String));
                var valueAsString = FickleExpression.Call(param, param.Type, typeof(String), SourceCodeGenerator.ToStringMethod, parameter);

                var replaceArgs = new
                {
                    valueToReplace,
                    valueAsString
                };

                methodStatements.Add(Expression.Assign(url, FickleExpression.Call(url, typeof(String), "replace", replaceArgs)));
            }

            methodStatements.Add(FickleExpression.Call(client, httpMethod, serviceCallArguments));

            var methodBody = FickleExpression.Block
            (
                methodVariables.ToArray(),
                methodStatements.ToArray()
            );

            return new MethodDefinitionExpression(methodName, methodParameters.ToReadOnlyCollection(), AccessModifiers.Public, typeof(void), methodBody, false, null);
        }
Example #28
0
        private void Initialize()
        {
            var content = new StringBuilder();
            var prettyPrintedContent = new StringBuilder();

            var parts = new List<SymbolDisplayPart>();
            var prettyPrintedParts = new List<SymbolDisplayPart>();

            var parameters = new List<IParameter>();

            var signaturePrefixParts = _signatureHelpItem.PrefixDisplayParts;
            var signaturePrefixContent = _signatureHelpItem.PrefixDisplayParts.GetFullText();

            AddRange(signaturePrefixParts, parts, prettyPrintedParts);
            Append(signaturePrefixContent, content, prettyPrintedContent);

            var separatorParts = _signatureHelpItem.SeparatorDisplayParts;
            var separatorContent = separatorParts.GetFullText();

            var newLinePart = new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
            var newLineContent = newLinePart.ToString();
            var spacerPart = new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', signaturePrefixContent.Length));
            var spacerContent = spacerPart.ToString();

            var paramColumnCount = 0;

            for (int i = 0; i < _signatureHelpItem.Parameters.Length; i++)
            {
                var sigHelpParameter = _signatureHelpItem.Parameters[i];

                var parameterPrefixParts = sigHelpParameter.PrefixDisplayParts;
                var parameterPrefixContext = sigHelpParameter.PrefixDisplayParts.GetFullText();

                var parameterParts = AddOptionalBrackets(sigHelpParameter.IsOptional, sigHelpParameter.DisplayParts);
                var parameterContent = parameterParts.GetFullText();

                var parameterSuffixParts = sigHelpParameter.SuffixDisplayParts;
                var parameterSuffixContext = sigHelpParameter.SuffixDisplayParts.GetFullText();

                paramColumnCount += separatorContent.Length + parameterPrefixContext.Length + parameterContent.Length + parameterSuffixContext.Length;

                if (i > 0)
                {
                    AddRange(separatorParts, parts, prettyPrintedParts);
                    Append(separatorContent, content, prettyPrintedContent);

                    if (paramColumnCount > MaxParamColumnCount)
                    {
                        prettyPrintedParts.Add(newLinePart);
                        prettyPrintedParts.Add(spacerPart);
                        prettyPrintedContent.Append(newLineContent);
                        prettyPrintedContent.Append(spacerContent);

                        paramColumnCount = 0;
                    }
                }

                AddRange(parameterPrefixParts, parts, prettyPrintedParts);
                Append(parameterPrefixContext, content, prettyPrintedContent);

                parameters.Add(new Parameter(this, sigHelpParameter, parameterContent, content.Length, prettyPrintedContent.Length));

                AddRange(parameterParts, parts, prettyPrintedParts);
                Append(parameterContent, content, prettyPrintedContent);

                AddRange(parameterSuffixParts, parts, prettyPrintedParts);
                Append(parameterSuffixContext, content, prettyPrintedContent);
            }

            AddRange(_signatureHelpItem.SuffixDisplayParts, parts, prettyPrintedParts);
            Append(_signatureHelpItem.SuffixDisplayParts.GetFullText(), content, prettyPrintedContent);

            if (_parameterIndex >= 0)
            {
                var sigHelpParameter = _signatureHelpItem.Parameters[_parameterIndex];

                AddRange(sigHelpParameter.SelectedDisplayParts, parts, prettyPrintedParts);
                Append(sigHelpParameter.SelectedDisplayParts.GetFullText(), content, prettyPrintedContent);
            }

            AddRange(_signatureHelpItem.DescriptionParts, parts, prettyPrintedParts);
            Append(_signatureHelpItem.DescriptionParts.GetFullText(), content, prettyPrintedContent);

            var documentation = _signatureHelpItem.DocumentationFactory(CancellationToken.None).ToList();
            if (documentation.Count > 0)
            {
                AddRange(new[] { newLinePart }, parts, prettyPrintedParts);
                Append(newLineContent, content, prettyPrintedContent);

                AddRange(documentation, parts, prettyPrintedParts);
                Append(documentation.GetFullText(), content, prettyPrintedContent);
            }

            _content = content.ToString();
            _prettyPrintedContent = prettyPrintedContent.ToString();
            _displayParts = parts.ToImmutableArrayOrEmpty();
            _prettyPrintedDisplayParts = prettyPrintedParts.ToImmutableArrayOrEmpty();
            _parameters = parameters.ToReadOnlyCollection();
        }
        protected override Expression VisitTypeDefinitionExpression(TypeDefinitionExpression expression)
        {
            var includeExpressions = new List<IncludeExpression>();
            var importExpressions = new List<Expression>();
            var referencedTypes = ReferencedTypesCollector.CollectReferencedTypes(expression);
            referencedTypes.Sort((x, y) => String.Compare(x.Name, y.Name, StringComparison.InvariantCultureIgnoreCase));

            var lookup = new HashSet<Type>(referencedTypes.Where(TypeSystem.IsPrimitiveType));

            if (!this.codeGenerationContext.Options.ImportDependenciesAsFramework)
            {
                if (lookup.Contains(typeof(Guid)) || lookup.Contains(typeof(Guid?)))
                {
                    includeExpressions.Add(FickleExpression.Include("PKUUID.h"));
                }

                if (lookup.Contains(typeof(TimeSpan)) || lookup.Contains(typeof(TimeSpan?)))
                {
                    includeExpressions.Add(FickleExpression.Include("PKTimeSpan.h"));
                }

                includeExpressions.Add(FickleExpression.Include("PKDictionarySerializable.h"));
                includeExpressions.Add(FickleExpression.Include("PKFormEncodingSerializable.h"));
            }
            else
            {
                importExpressions.Add(new CodeLiteralExpression(c => c.WriteLine("@import PlatformKit;")));
            }

            if (ObjectiveBinderHelpers.TypeIsServiceClass(expression.Type.BaseType))
            {
                includeExpressions.Add(FickleExpression.Include(expression.Type.BaseType.Name + ".h"));
            }

            includeExpressions.AddRange(referencedTypes.Where(c => c.IsEnum).Select(c => FickleExpression.Include(c.Name + ".h")));

            includeExpressions.Sort(IncludeExpression.Compare);

            var comment = new CommentExpression("This file is AUTO GENERATED");

            var headerExpressions = new List<Expression>()
            {
                new[] { comment }.ToStatementisedGroupedExpression(),
                importExpressions.Count == 0 ? null : importExpressions.ToStatementisedGroupedExpression(),
                includeExpressions.ToStatementisedGroupedExpression()
            };

            var referencedTypeExpressions = referencedTypes
                .Where(ObjectiveBinderHelpers.TypeIsServiceClass)
                .Where(c => c != expression.Type.BaseType)
                .OrderBy(x => x.Name.Length)
                .ThenBy(x => x.Name)
                .Select(c => (Expression)new ReferencedTypeExpression(c)).ToList();

            if (referencedTypeExpressions.Count > 0)
            {
                headerExpressions.Add(referencedTypeExpressions.ToStatementisedGroupedExpression());
            }

            var header = headerExpressions.ToStatementisedGroupedExpression(GroupedExpressionsExpressionStyle.Wide);

            var propertyBody = this.Visit(expression.Body);

            var interfaceTypes = new List<Type>
            {
                FickleType.Define("NSCopying"),
                FickleType.Define("PKDictionarySerializable"),
                FickleType.Define("PKFormEncodingSerializable")
            };

            return new TypeDefinitionExpression(expression.Type, header, propertyBody, true, expression.Attributes, interfaceTypes.ToReadOnlyCollection());
        }
        public ReadOnlyCollection<Audio> GetAllRecommendations(long? userId = null, bool shuffle = true, string targetAudio = "")
        {
            const int count = 1000;
            var i = 0;
            var result = new List<Audio>();

            do
            {
                var currentItems = _audio.GetRecommendations(userId, count, i * count, shuffle, targetAudio);
                if (currentItems != null) result.AddRange(currentItems);
            } while (++i * count < (_vk.CountFromLastResponse ?? 0));

            return result.ToReadOnlyCollection();
        }