public void GetHighScores()
		{
			ParseQuery query = new ParseQuery("GameScore");
			query.Limit = 100;
			query.OrderByDescending("Score");
			query.FindObjectsAsync(FoundResults);
		}
Exemple #2
0
        public async Task getNearbyToilets(ParseGeoPoint location, Boolean shouldSkip)
        {
            if (currentLocation.Latitude != location.Latitude || currentLocation.Longitude != location.Longitude)
            {
                //New location, so empty data
                _parseToilets.Clear();
                currentLocation = location;
            } 

            var query = new ParseQuery<Toilet>();
            query = query.WhereNear("Location", location);
            query = query.Limit(20);

            if (shouldSkip)
            {
                query = query.Skip(skipCount);
                skipCount += 20;
            }

            IEnumerable<Toilet> result = await query.FindAsync();

            if (shouldSkip)
            {
                result.ToList().ForEach(_parseToilets.Add);
            } else
            {
                _parseToilets.Clear();
                result.ToList().ForEach(_parseToilets.Add);
            }

            foreach (Toilet toilet in _parseToilets)
            {
                toilet.searchLocationPoint = location;
            }
        }
    public Task TestSendPush() {
      MutablePushState state = new MutablePushState {
        Query = ParseInstallation.Query
      };

      ParsePush thePush = new ParsePush();
      ParseCorePlugins.Instance.PushController = GetMockedPushController(state);

      thePush.Alert = "Alert";
      state.Alert = "Alert";

      return thePush.SendAsync().ContinueWith(t => {
        Assert.True(t.IsCompleted);
        Assert.False(t.IsFaulted);

        thePush.Channels = new List<string> { { "channel" } };
        state.Channels = new List<string> { { "channel" } };

        return thePush.SendAsync();
      }).Unwrap().ContinueWith(t => {
        Assert.True(t.IsCompleted);
        Assert.False(t.IsFaulted);

        ParseQuery<ParseInstallation> query = new ParseQuery<ParseInstallation>("aClass");
        thePush.Query = query;
        state.Query = query;

        return thePush.SendAsync();
      }).Unwrap().ContinueWith(t => {
        Assert.True(t.IsCompleted);
        Assert.False(t.IsFaulted);

        ParseCorePlugins.Instance.PushController = null;
      });
    }
        public async Task<IEnumerable<PUser>> GetCurrentCompanyUsers(ParseQuery<ParseUser> query = null)
        {
            IEnumerable<ParseUser> currentCompanyUsers;
            if (query == null)
            {
                var currentUser = await UserUtility.GetCurrentParseUser();
                if (currentUser == null)
                    return new List<PUser>();

                currentCompanyUsers = await ParseUser.Query.WhereEqualTo("CompanyId", currentUser["CompanyId"].ToString()).FindAsync();
            }
            else
                currentCompanyUsers = await query.FindAsync();

            if (currentCompanyUsers == null)
                return new List<PUser>();

            return currentCompanyUsers
                .Select(user => new PUser
                {
                    Id = user.ObjectId,
                    Email = user["email"]?.ToString(),
                    UserName = user["username"]?.ToString(),
                    Role = (user["Role"]?.ToString() == UserRole.Admin) ? "Admin" : "Employee"
                });
        }
        public async Task<RepositoryResponse<List<City>>> GetCities()
        {
            var response = new RepositoryResponse<List<City>>
            {
                Data = new List<City>()
            };
            try
            {

                ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("City");
                IEnumerable<ParseObject> result =  await query.FindAsync();

                foreach(ParseObject res in result)
                {
                    response.Data.Add(new City(){ ID = res.ObjectId, NAME =  res.Get<String>("Name")});
                }

                response.Success = true;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Error = ex;
        }

            return response;
        }
        /// <summary>
        /// Visits the binary.
        /// </summary>
        /// <returns>The binary.</returns>
        /// <param name="node">The node.</param>
        protected override Expression VisitBinary(BinaryExpression node)
        {
            if (node.NodeType == ExpressionType.Equal)
            {
                var keyExpression = node.Left as MemberExpression;

                string value = null;
                var valueExpression = node.Right as ConstantExpression;

                if (valueExpression == null)
                {
                    var memberExpression = node.Right as MemberExpression;

                    if (memberExpression != null)
                    {
                        value = Expression.Lambda(memberExpression).Compile().DynamicInvoke().ToString();
                    }
                }
                else
                {
                    value = valueExpression.Value.ToString();
                }

                if (keyExpression != null && value != null)
                {
                    var key = keyExpression.Member.Name;

                    m_parseQuery = m_parseQuery.WhereEqualTo(key, value);
                }
            }

            return base.VisitBinary(node);
        }
Exemple #7
0
 internal static string GetRandomSentence() {
     var data = new ParseQuery<ParseObject>("TypingArticles").FindAsync().Result;
     try {
         return data.ToList()[(new Random()).Next(0, data.Count())].Get<string>("text");
     } catch (Exception) {
         return "Failed retrieving data from parse. Owner didn't add any articles to type using `typeadd`.";
     }
 }
Exemple #8
0
        /// <summary>
        /// Pushes an arbitrary payload to every device matching target. This is shorthand for:
        ///
        /// <code>
        /// var push = new ParsePush();
        /// push.Query = query
        /// push.Data = data;
        /// return push.SendAsync();
        /// </code>
        /// </summary>
        /// <param name="data">A push payload. See the ParsePush.Data property for more information.</param>
        /// <param name="query">A query filtering the devices which should receive this Push Notification.</param>
        public static Task SendDataAsync(IDictionary <string, object> data, ParseQuery <ParseInstallation> query)
        {
            var push = new ParsePush();

            push.Query = query;
            push.Data  = data;
            return(push.SendAsync());
        }
Exemple #9
0
        /// <summary>
        /// Pushes a simple message to every device matching the target query. This is shorthand for:
        ///
        /// <code>
        /// var push = new ParsePush();
        /// push.Query = query;
        /// push.Data = new Dictionary&lt;string, object&gt;{{"alert", alert}};
        /// return push.SendAsync();
        /// </code>
        /// </summary>
        /// <param name="alert">The alert message to send.</param>
        /// <param name="query">A query filtering the devices which should receive this Push Notification.</param>
        public static Task SendAlertAsync(string alert, ParseQuery <ParseInstallation> query)
        {
            var push = new ParsePush();

            push.Query = query;
            push.Alert = alert;
            return(push.SendAsync());
        }
Exemple #10
0
        /// <summary>
        /// Filters a query based upon the predicate provided.
        /// </summary>
        /// <typeparam name="TSource">The type of ParseObject being queried for.</typeparam>
        /// <param name="source">The base <see cref="ParseQuery{TSource}"/> to which
        /// the predicate will be added.</param>
        /// <param name="predicate">A function to test each ParseObject for a condition.
        /// The predicate must be able to be represented by one of the standard Where
        /// functions on ParseQuery</param>
        /// <returns>A new ParseQuery whose results will match the given predicate as
        /// well as the source's filters.</returns>
        public static ParseQuery <TSource> Where <TSource>(
            this ParseQuery <TSource> source, Expression <Func <TSource, bool> > predicate)
            where TSource : ParseObject
        {
            // Handle top-level logic operators && and ||
            var binaryExpression = predicate.Body as BinaryExpression;

            if (binaryExpression != null)
            {
                if (binaryExpression.NodeType == ExpressionType.AndAlso)
                {
                    return(source
                           .Where(Expression.Lambda <Func <TSource, bool> >(
                                      binaryExpression.Left, predicate.Parameters))
                           .Where(Expression.Lambda <Func <TSource, bool> >(
                                      binaryExpression.Right, predicate.Parameters)));
                }
                if (binaryExpression.NodeType == ExpressionType.OrElse)
                {
                    var left = source.Where(Expression.Lambda <Func <TSource, bool> >(
                                                binaryExpression.Left, predicate.Parameters));
                    var right = source.Where(Expression.Lambda <Func <TSource, bool> >(
                                                 binaryExpression.Right, predicate.Parameters));
                    return(left.Or(right));
                }
            }

            var normalized = new WhereNormalizer().Visit(predicate.Body);

            var methodCallExpr = normalized as MethodCallExpression;

            if (methodCallExpr != null)
            {
                return(source.WhereMethodCall(predicate, methodCallExpr));
            }

            var binaryExpr = normalized as BinaryExpression;

            if (binaryExpr != null)
            {
                return(source.WhereBinaryExpression(predicate, binaryExpr));
            }

            var unaryExpr = normalized as UnaryExpression;

            if (unaryExpr != null && unaryExpr.NodeType == ExpressionType.Not)
            {
                var node = unaryExpr.Operand as MethodCallExpression;
                if (IsParseObjectGet(node) && (node.Type == typeof(bool) || node.Type == typeof(bool?)))
                {
                    // This is a raw boolean field access like 'where !obj.Get<bool>("foo")'
                    return(source.WhereNotEqualTo(GetValue(node.Arguments[0]) as string, true));
                }
            }

            throw new InvalidOperationException(
                      "Encountered an unsupported expression for ParseQueries.");
        }
Exemple #11
0
 /// <summary>
 /// Adds a constraint to the query that requires that a particular key's value
 /// matches another ParseQuery. This only works on keys whose values are
 /// ParseObjects or lists of ParseObjects.
 /// </summary>
 /// <param name="key">The key to check.</param>
 /// <param name="query">The query that the value should match.</param>
 /// <returns>A new query with the additional constraint.</returns>
 public ParseQuery <T> WhereMatchesQuery <TOther>(string key, ParseQuery <TOther> query)
     where TOther : ParseObject
 {
     return(new ParseQuery <T>(this, where : new Dictionary <string, object> {
         { key, new Dictionary <string, object> {
               { "$inQuery", query.BuildParameters(true) }
           } }
     }));
 }
Exemple #12
0
 public void loadHighScore()
 {
     ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("HighScorer");
     query.GetAsync("7qrQVagc9u").ContinueWith(t =>{
         highScoreObject = t.Result;
     });
     //highScoreObject.FetchAsync<ParseObject>();
     //highScoreObject.FetchAsync();
 }
        public async Task GetWorkout(string name)
        {
            var query = new ParseQuery<Workout>().WhereEqualTo("name", name);
            IEnumerable<Workout> result = await query.FindAsync();
            if (result.ToList().Count > 0)
                _workout = result.ElementAt(0);

            await GetExercises();
        }
        public async Task<CrueltySpotCategory> GetByIdAsync(string id)
        {
            //var query = ParseObject.GetQuery(ParseHelper.CrueltySpotCategoryClassName);
            //var crueltySpotCategoryParse = await query.GetAsync(id);
            //return ConvertToPoco(crueltySpotCategoryParse);

            var query = new ParseQuery<CrueltySpotCategory>();
            var result = await query.GetAsync(id);
            return result;
        }
        /// <summary>
        /// Private constructor for composition of queries. A source query is required,
        /// but the remaining values can be null if they won't be changed in this
        /// composition.
        /// </summary>
        private ParseQuery(ParseQuery <T> source, IDictionary <string, object> where = null, IEnumerable <string> replacementOrderBy = null, IEnumerable <string> thenBy = null, int?skip = null, int?limit = null, IEnumerable <string> includes = null, IEnumerable <string> selectedKeys = null, String redirectClassNameForKey = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            className                    = source.className;
            this.where                   = where != null ? new Dictionary <string, object>(MergeWhereClauses(where)) : source.where;
            orderBy                      = replacementOrderBy != null ? new ReadOnlyCollection <string>(replacementOrderBy.ToList()) : source.orderBy;
            this.skip                    = source.skip;
            this.limit                   = source.limit;
            this.includes                = source.includes;
            this.selectedKeys            = source.selectedKeys;
            this.redirectClassNameForKey = source.redirectClassNameForKey;

            if (thenBy != null)
            {
                if (orderBy == null)
                {
                    throw new ArgumentException("You must call OrderBy before calling ThenBy.");
                }
                (thenBy as List <string>).AddRange(orderBy);
                orderBy = new ReadOnlyCollection <string>(thenBy as List <string>);
            }

            // Remove duplicates.
            orderBy = orderBy != null ? new ReadOnlyCollection <string>(new HashSet <string>(orderBy).ToList()) : orderBy;

            if (skip != null)
            {
                this.skip = (this.skip ?? 0) + skip;
            }

            if (limit != null)
            {
                this.limit = limit;
            }

            if (includes != null)
            {
                this.includes = new ReadOnlyCollection <string>(MergeIncludes(includes).ToList());
            }

            if (selectedKeys != null)
            {
                this.selectedKeys = new ReadOnlyCollection <string>(MergeSelectedKeys(selectedKeys).ToList());
            }

            if (redirectClassNameForKey != null)
            {
                this.redirectClassNameForKey = redirectClassNameForKey;
            }
        }
        public ServerGreetCommand() : base() {
            AnnouncementsDictionary = new ConcurrentDictionary<ulong, AnnounceControls>();

            NadekoBot.client.UserJoined += UserJoined;
            NadekoBot.client.UserLeft += UserLeft;

            var data = new ParseQuery<ParseObject>("Announcements")
                               .FindAsync()
                               .Result;
            if(data.Any())
            foreach (var po in data)
                AnnouncementsDictionary.TryAdd(po.Get<ulong>("serverId"), new AnnounceControls(po.Get<ulong>("serverId")).Initialize(po));
        }
		public async Task<IEnumerable<ITag>> FetchTags(int pageSize, int offset)
		{
			using (var tokenSource = new CancellationTokenSource(Constants.FetchTagsTimeout))
			{
				var query = new ParseQuery<ParseTag>().OrderBy(p => p.Text);
				if (pageSize > 0 && offset >= 0)
				{
					query = query.Limit(pageSize).Skip(offset);
				}
				var result = await query.FindAsync(tokenSource.Token).ConfigureAwait(false);
				return result.Select(p => new Tag(p) as ITag);
			}
		}
		public async Task<IEnumerable<ITag>> FindTags(string searchQuery, int pageSize, int offset)
		{
			using (var tokenSource = new CancellationTokenSource(Constants.FindTagsTimeout))
			{
				var parseQuery = new ParseQuery<ParseTag>().Where(t => t.Text.StartsWith(searchQuery.Trim())).OrderBy(t => t.Text);
				if (pageSize > 0 && offset >= 0)
				{
					parseQuery = parseQuery.Limit(pageSize).Skip(offset);
				}
				var result = await parseQuery.FindAsync(tokenSource.Token).ConfigureAwait(false);
				return result.Select(s => new Tag(s) as ITag);
			}
		}
Exemple #19
0
        public async Task<IList<Site>> GetNearbySites(double latitude, double longitude, double distanceRadians = 0)
        {
            if (distanceRadians == 0) distanceRadians = 0.5;
            var pos = new ParseGeoPoint(latitude, longitude);
            var sitesQuery = new ParseQuery<ApParseSite>()
                .WhereWithinDistance("location", pos, new ParseGeoDistance(distanceRadians))
                .Limit(100);

            var sites = await sitesQuery.FindAsync();

            return sites
                .Select(s => ConvertToSite(s, pos))
                .OrderByDescending(s => s.DistanceKm)
                .ToList();
        }
Exemple #20
0
        /// <summary>
        /// Adds a constraint to the query that requires a particular key's value
        /// does not match any value for a key in the results of another ParseQuery.
        /// </summary>
        /// <param name="key">The key whose value is being checked.</param>
        /// <param name="keyInQuery">The key in the objects from the subquery to look in.</param>
        /// <param name="query">The subquery to run</param>
        /// <returns>A new query with the additional constraint.</returns>
        public ParseQuery <T> WhereDoesNotMatchesKeyInQuery <TOther>(string key,
                                                                     string keyInQuery,
                                                                     ParseQuery <TOther> query) where TOther : ParseObject
        {
            var parameters = new Dictionary <string, object> {
                { "query", query.BuildParameters(true) },
                { "key", keyInQuery }
            };

            return(new ParseQuery <T>(this, where : new Dictionary <string, object> {
                { key, new Dictionary <string, object> {
                      { "$dontSelect", parameters }
                  } }
            }));
        }
        /// <summary>
        /// Constructs a ParseObject whose id is already known by fetching data
        /// from the server.
        /// </summary>
        /// <param name="objectId">ObjectId of the ParseObject to fetch.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The ParseObject for the given objectId.</returns>
        public Task <T> GetAsync(string objectId, CancellationToken cancellationToken)
        {
            ParseQuery <T> singleItemQuery = new ParseQuery <T>(className).WhereEqualTo("objectId", objectId);

            singleItemQuery = new ParseQuery <T>(singleItemQuery, includes: includes, selectedKeys: selectedKeys, limit: 1);
            return(singleItemQuery.FindAsync(cancellationToken).OnSuccess(t =>
            {
                T first = t.Result.FirstOrDefault();
                if (first == null)
                {
                    throw new ParseException(ParseException.ErrorCode.ObjectNotFound, "Object with the given objectId not found.");
                }
                return first;
            }));
        }
        /// <summary>
        /// Constructs a query that is the or of the given queries.
        /// </summary>
        /// <param name="queries">The list of ParseQueries to 'or' together.</param>
        /// <returns>A ParseQquery that is the 'or' of the passed in queries.</returns>
        public static ParseQuery <T> ConstructOrQuery <T>(this IServiceHub serviceHub, IEnumerable <ParseQuery <T> > queries) where T : ParseObject
        {
            string className = default;
            List <IDictionary <string, object> > orValue = new List <IDictionary <string, object> > {
            };

            // We need to cast it to non-generic IEnumerable because of AOT-limitation

            IEnumerable nonGenericQueries = queries;

            foreach (object obj in nonGenericQueries)
            {
                ParseQuery <T> query = obj as ParseQuery <T>;

                if (className is { } && query.ClassName != className)
Exemple #23
0
    public static bool CacheParseObjectQuery(string queryId, ParseQuery<ParseObject> parseQuery)
    {
        if (LocalParseObjectQueries==null)
        {
            LocalParseObjectQueries = new Dictionary<string, ParseQuery<ParseObject>>();
        }

        if (parseQuery!=null && ! string.IsNullOrEmpty(queryId))
        {
            LocalParseObjectQueries[queryId] = parseQuery;
        }else{
            return false;
        }

        return true;
    }
        // RETRIEVE USER TASKS
        public async Task GetUserTasks() {
            // Get current user's tasks
            ParseQuery<ParseObject> userTaskQuery = new ParseQuery<ParseObject>("UserTask").WhereEqualTo("owner", ParseUser.CurrentUser);
            IEnumerable<ParseObject> poUserTasks = await userTaskQuery.FindAsync();

            // Add each task to UserTasks collection (which will be viewed in WebView)
            foreach (var poUserTask in poUserTasks) {
                UserTask toAdd = new UserTask() {
                    Title = poUserTask.Get<string>("title"),
                    Description = poUserTask.Get<string>("description"),
                    DueDate = poUserTask.Get<DateTime>("dueDate")
                };
                UserTasks.Add(toAdd);
                UserTasks.OrderBy(x => x.DueDate);
            }
        }
        public async void getObject()
        {
            Console.WriteLine("I reached line 32");
            var query = new ParseQuery<TVShowForParse>();
            IEnumerable<TVShowForParse> result = await query.FindAsync();


            Console.WriteLine("I reached line 37 with count "+result.Count());

            foreach (var listItem in result)
            {
                Console.WriteLine("Show name "+listItem.Name +" with ID "+listItem.TMDBID);
            }


        }
Exemple #26
0
        /// <summary>
        /// Converts a normalized binary expression into the appropriate ParseQuery clause.
        /// </summary>
        private static ParseQuery <T> WhereBinaryExpression <T>(
            this ParseQuery <T> source, Expression <Func <T, bool> > expression, BinaryExpression node)
            where T : ParseObject
        {
            var leftTransformed = new ObjectNormalizer().Visit(node.Left) as MethodCallExpression;

            if (!(IsParseObjectGet(leftTransformed) &&
                  leftTransformed.Object == expression.Parameters[0]))
            {
                throw new InvalidOperationException(
                          "Where expressions must have one side be a field operation on a ParseObject.");
            }

            var fieldPath   = GetValue(leftTransformed.Arguments[0]) as string;
            var filterValue = GetValue(node.Right);

            if (filterValue != null && !ParseEncoder.IsValidType(filterValue))
            {
                throw new InvalidOperationException(
                          "Where clauses must use types compatible with ParseObjects.");
            }

            switch (node.NodeType)
            {
            case ExpressionType.GreaterThan:
                return(source.WhereGreaterThan(fieldPath, filterValue));

            case ExpressionType.GreaterThanOrEqual:
                return(source.WhereGreaterThanOrEqualTo(fieldPath, filterValue));

            case ExpressionType.LessThan:
                return(source.WhereLessThan(fieldPath, filterValue));

            case ExpressionType.LessThanOrEqual:
                return(source.WhereLessThanOrEqualTo(fieldPath, filterValue));

            case ExpressionType.Equal:
                return(source.WhereEqualTo(fieldPath, filterValue));

            case ExpressionType.NotEqual:
                return(source.WhereNotEqualTo(fieldPath, filterValue));

            default:
                throw new InvalidOperationException(
                          "Where expressions do not support this operator.");
            }
        }
 public async Task<RepositoryResponse<Dependency>> Get(string objectID)
 {
     var response = new RepositoryResponse<Dependency>();
     try
     {
         ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Dependency");
         ParseObject result = await query.GetAsync(objectID);
         response.Success = true;
         response.Data = new Dependency { ID = result.ObjectId, NAME = result["Name"].ToString() };
     }
     catch (Exception ex)
     {
         response.Success = false;
         response.Error = ex;
     }
     return response;
 }
        /// <summary>
        /// Private constructor for composition of queries. A source query is required,
        /// but the remaining values can be null if they won't be changed in this
        /// composition.
        /// </summary>
        private ParseQuery(ParseQuery <T> source, IDictionary <string, object> where = null, IEnumerable <string> replacementOrderBy = null, IEnumerable <string> thenBy = null, int?skip = null, int?limit = null, IEnumerable <string> includes = null, IEnumerable <string> selectedKeys = null, String redirectClassNameForKey = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            className                    = source.className;
            this.where                   = source.where;
            orderBy                      = replacementOrderBy is null ? source.orderBy : new ReadOnlyCollection <string>(replacementOrderBy.ToList());
            this.skip                    = skip is null ? source.skip : (source.skip ?? 0) + skip; // 0 could be handled differently from null
            this.limit                   = limit ?? source.limit;
            this.includes                = source.includes;
            this.selectedKeys            = source.selectedKeys;
            this.redirectClassNameForKey = redirectClassNameForKey ?? source.redirectClassNameForKey;

            if (thenBy != null)
            {
                List <string> newOrderBy = new List <string>(orderBy ??
                                                             throw new ArgumentException("You must call OrderBy before calling ThenBy."));

                newOrderBy.AddRange(thenBy);
                orderBy = new ReadOnlyCollection <string>(newOrderBy);
            }

            // Remove duplicates.
            if (orderBy != null)
            {
                orderBy = new ReadOnlyCollection <string>(new HashSet <string>(orderBy).ToList());
            }

            if (where != null)
            {
                this.where = new Dictionary <string, object>(MergeWhereClauses(where));
            }

            if (includes != null)
            {
                this.includes = new ReadOnlyCollection <string>(MergeIncludes(includes).ToList());
            }

            if (selectedKeys != null)
            {
                this.selectedKeys = new ReadOnlyCollection <string>(MergeSelectedKeys(selectedKeys).ToList());
            }
        }
        public async Task<ActionResult> EditProduct(string ObjectId, FormCollection fc)
        {
            var query = new ParseQuery<ParseObject>("Product");
            ParseObject product = await query.GetAsync(ObjectId);

            product["mTitle"] = fc["mTitle"];
            product["mPrice"] = fc["mPrice"];
            product["mQuantity"] = fc["mQuantity"];
            product["mManufacture"] = fc["mManufacture"];
            product["ReturningOrder"] = fc["ReturningOrder"];
            product["salePrice"] = fc["salePrice"];
            product["oldPrice"] = fc["oldPrice"];

            await product.SaveAsync();

            return RedirectToAction("ProductsList");
        }
		public async Task<IEnumerable<House>> GetHousesAsync(MapFilter mapFilter)
		{
			var query = new ParseQuery<House>();

//
//			if (mapFilter == MapFilter.RecentlyAdded) {
//				query = query.WhereGreaterThanOrEqualTo("createdAt",DateTime.Today.AddDays(-3));
//			}
			if (mapFilter == MapFilter.Top5) {
				var houses = await  query.FindAsync ();
				return houses.GroupBy (x => x.Likes).OrderByDescending(x=>x.Key).Take (5).SelectMany (x => x);
			}


			var results = await  query.FindAsync ();

			return results;
		}
Exemple #31
0
        protected async void BindContactGridView()
        {
            List<Contact> listOfContacts = new List<Contact>();
            var query = new ParseQuery<ParseObject>("Contacts");
            IEnumerable<ParseObject> results = await query.FindAsync();

            foreach (var item in results)
            {
                Contact newContact = new Contact();
                newContact.FirstName = item.Get<string>("FirstName");
                newContact.LastName = item.Get<string>("LastName");
                newContact.EmailAddress = item.Get<string>("EmailAddress");
                newContact.Message = item.Get<string>("Message");
                listOfContacts.Add(newContact);
            }

            gvContacts.DataSource = listOfContacts;
            gvContacts.DataBind();
        }
        /// <summary>
        /// Private constructor for composition of queries. A source query is required,
        /// but the remaining values can be null if they won't be changed in this
        /// composition.
        /// </summary>
        internal ParseQuery(ParseQuery <T> source, IDictionary <string, object> where = null, IEnumerable <string> replacementOrderBy = null, IEnumerable <string> thenBy = null, int?skip = null, int?limit = null, IEnumerable <string> includes = null, IEnumerable <string> selectedKeys = null, string redirectClassNameForKey = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            Services  = source.Services;
            ClassName = source.ClassName;
            Filters   = source.Filters;
            Orderings = replacementOrderBy is null ? source.Orderings : new ReadOnlyCollection <string>(replacementOrderBy.ToList());

            // 0 could be handled differently from null.

            SkipAmount              = skip is null ? source.SkipAmount : (source.SkipAmount ?? 0) + skip;
            LimitAmount             = limit ?? source.LimitAmount;
            Includes                = source.Includes;
            KeySelections           = source.KeySelections;
            RedirectClassNameForKey = redirectClassNameForKey ?? source.RedirectClassNameForKey;

            if (thenBy is { })
        public async Task<RepositoryResponse<ParseObject>> GetDependencyById(string id)
        {
            var response = new RepositoryResponse<ParseObject>{ };

            try
            {

                ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Dependency");
                ParseObject result = await query.GetAsync(id);

                response.Data = result;

                response.Success = true;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Error = ex;
            }

            return response;
        }
Exemple #34
0
        protected async void BindSurveyGridView()
        {
            List<Survey> listOfSurveys = new List<Survey>();
            var query = new ParseQuery<ParseObject>("Survey");
            IEnumerable<ParseObject> results = await query.FindAsync();

            foreach (var item in results)
            {
                Survey newSurvey = new Survey();
                newSurvey.Email = item.Get<string>("EmailAddress");
                newSurvey.Food = item.Get<string>("Food");
                newSurvey.Value = item.Get<string>("Value");
                newSurvey.FavoriteDish = item.Get<string>("FavoriteDish");
                newSurvey.LeastFavoriteDish = item.Get<string>("LeastFavoriteDish");
                newSurvey.Critique = item.Get<string>("Critique");
                newSurvey.AddToMenu = item.Get<string>("AddToMenu");
                listOfSurveys.Add(newSurvey);
            }

            gvSurvey.DataSource = listOfSurveys;
            gvSurvey.DataBind();
        }
Exemple #35
0
        public async Task<IList<Site>> GetSites(string searchText, double latitude = 0, double longitude = 0)
        {
            var sitesQuery = new ParseQuery<ApParseSite>()
                .OrderByDescending(x => x.UseCount)
                .Limit(100);

            if (!string.IsNullOrEmpty(searchText))
            {
                var lowerSearchText = searchText.ToLower();
                sitesQuery = sitesQuery.Where(s => s.Search.Contains(lowerSearchText));
            }
            else
            {
                sitesQuery = sitesQuery.WhereGreaterThan("UseCount", 1000);
            }

            var allSites = (await sitesQuery.FindAsync())
                .Select(s => ConvertToSite(s, new ParseGeoPoint(latitude, longitude)));

            // Remove duplicates
            var siteIds = new HashSet<long>();
            var sites = new List<Site>();
            foreach (var site in allSites)
            {
                if (site.SiteId.HasValue)
                {
                    if (!siteIds.Contains(site.SiteId.Value))
                    {
                        siteIds.Add(site.SiteId.Value);
                        sites.Add(site);
                    }
                }
            }

            return sites
                .OrderByDescending(s => s.DistanceKm)
                .ThenBy(s => s.UseCount)
                .ToList();
        }
Exemple #36
0
        //public async List<Contact> readContacts()
        //{
        //    List<Contact> listOfContacts = new List<Contact>();

        //    var query = from myContacts in ParseObject.GetQuery("Contacts")
        //                orderby myContacts.Get<DateTime>("updatedAt") descending
        //                select myContacts;

        //    IEnumerable<ParseObject> results = await query.FindAsync();

        //    foreach (var item in results)
        //    {
        //        Contact newContact = new Contact();
        //        newContact.FirstName = item.Get<string>("FirstName");
        //        newContact.LastName = item.Get<string>("LastName");
        //        newContact.EmailAddress = item.Get<string>("EmailAddress");
        //        newContact.Message = item.Get<string>("Message");
        //        listOfContacts.Add(newContact);
        //    }

        //    return listOfContacts;
        //}

        public async void readContacts()
        {
            List<Contact> listOfContacts = new List<Contact>();

            //var query = from myContacts in ParseObject.GetQuery("Contacts")
            //            orderby myContacts.Get<DateTime>("updatedAt") descending
            //            select myContacts;

            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Contacts");

            IEnumerable<ParseObject> results = await query.FindAsync();

            foreach (var item in results)
            {
                Contact newContact = new Contact();
                newContact.FirstName = item.Get<string>("FirstName");
                newContact.LastName = item.Get<string>("LastName");
                newContact.EmailAddress = item.Get<string>("EmailAddress");
                newContact.Message = item.Get<string>("Message");
                listOfContacts.Add(newContact);
            }
        }
        public async Task<ActionResult> ClientUserList()
        {
            var query = new ParseQuery<ParseObject>("ClientUser");
            IEnumerable<ParseObject> clientUsers = await query.FindAsync();

            int count = await query.CountAsync();
            List<ClientUser> _clientUsers = new List<ClientUser>();

            foreach (ParseObject p in clientUsers)
            {
                ClientUser clientUser = new ClientUser();
                clientUser.ClientUserId = p.ObjectId;
                clientUser.firstName = p.Get<string>("firstName");
                clientUser.lastName = p.Get<string>("lastName");
                clientUser.emailAddress = p.Get<string>("emailAddress");
                clientUser.phoneNumber = p.Get<string>("phoneNumber");
                clientUser.birthday = p.Get<DateTime>("birthday");
                clientUser.address = p.Get<string>("address");
                _clientUsers.Add(clientUser);
            }

            ViewBag.count = count;
            return View(_clientUsers);
        }
        public async Task<RepositoryResponse<User>> RegisterUser(User user)
        {
            var response = new RepositoryResponse<User> { };

            try
            {
                var userObject = new ParseUser()
                {
                    Username = user.USERNAME,
                    Password = user.PASSWORD
                };
                userObject["Name"] = user.NAME;

                DependencyRepository DependencyContext = new DependencyRepository();

                RepositoryResponse<ParseObject> Dependency = await DependencyContext.GetDependencyById(user.ID_DEPENDENCY);

                ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Dependency");
                IEnumerable<ParseObject> result = await query.FindAsync();

                var relation = userObject.GetRelation<ParseObject>("ID_Dependency");
                relation.Add(Dependency.Data);

                await userObject.SignUpAsync();
                response.Success = true;
                response.Data = userObject.ToUser();
                // Register was successful.
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Error = ex;
            }

            return response;
        }
 /// <summary>
 /// Adds a constraint to the query that requires a particular key's value
 /// to match a value for a key in the results of another ParseQuery.
 /// </summary>
 /// <param name="key">The key whose value is being checked.</param>
 /// <param name="keyInQuery">The key in the objects from the subquery to look in.</param>
 /// <param name="query">The subquery to run</param>
 /// <returns>A new query with the additional constraint.</returns>
 public ParseQuery <T> WhereMatchesKeyInQuery <TOther>(string key, string keyInQuery, ParseQuery <TOther> query) where TOther : ParseObject => new ParseQuery <T>(this, where : new Dictionary <string, object> {
     { key, new Dictionary <string, object> {
           { "$select", new Dictionary <string, object> {
                                                                                                                                                                                                                        { "query", query.BuildParameters(true) }, { "key", keyInQuery }
                                                                                                                                                                                                                    } }
       } }
 });
 protected void listNotifications_ItemCommand(object source, RepeaterCommandEventArgs e)
 {
     var query = new ParseQuery<NotificationTutor>();
     NotificationTutor notification = AsyncHelpers.RunSync(() => query.GetAsync(e.CommandName));
     if (notification.FirstSeenAt == null)
     {
         notification.FirstSeenAt = DateTime.Now;
         AsyncHelpers.RunSync(notification.SaveAsync);
     }
     if (notification.Type == Constants.NotificationType.MESSAGE)
     {
         Session["ConversationUserId"] = notification.UserFrom.ObjectId;
     }
     Response.Redirect(notification.RedirectLink);
 }
Exemple #41
0
        /// <summary>
        /// Converts a normalized method call expression into the appropriate ParseQuery clause.
        /// </summary>
        private static ParseQuery <T> WhereMethodCall <T>(
            this ParseQuery <T> source, Expression <Func <T, bool> > expression, MethodCallExpression node)
            where T : ParseObject
        {
            if (IsParseObjectGet(node) && (node.Type == typeof(bool) || node.Type == typeof(bool?)))
            {
                // This is a raw boolean field access like 'where obj.Get<bool>("foo")'
                return(source.WhereEqualTo(GetValue(node.Arguments[0]) as string, true));
            }

            MethodInfo translatedMethod;

            if (functionMappings.TryGetValue(node.Method, out translatedMethod))
            {
                var objTransformed = new ObjectNormalizer().Visit(node.Object) as MethodCallExpression;
                if (!(IsParseObjectGet(objTransformed) &&
                      objTransformed.Object == expression.Parameters[0]))
                {
                    throw new InvalidOperationException(
                              "The left-hand side of a supported function call must be a ParseObject field access.");
                }
                var fieldPath   = GetValue(objTransformed.Arguments[0]);
                var containedIn = GetValue(node.Arguments[0]);
                var queryType   = translatedMethod.DeclaringType.GetGenericTypeDefinition()
                                  .MakeGenericType(typeof(T));
                translatedMethod = ReflectionHelpers.GetMethod(queryType,
                                                               translatedMethod.Name,
                                                               translatedMethod.GetParameters().Select(p => p.ParameterType).ToArray());
                return(translatedMethod.Invoke(source, new[] { fieldPath, containedIn }) as ParseQuery <T>);
            }

            if (node.Arguments[0] == expression.Parameters[0])
            {
                // obj.ContainsKey("foo") --> query.WhereExists("foo")
                if (node.Method == containsKeyMethod)
                {
                    return(source.WhereExists(GetValue(node.Arguments[1]) as string));
                }
                // !obj.ContainsKey("foo") --> query.WhereDoesNotExist("foo")
                if (node.Method == notContainsKeyMethod)
                {
                    return(source.WhereDoesNotExist(GetValue(node.Arguments[1]) as string));
                }
            }

            if (node.Method.IsGenericMethod)
            {
                if (node.Method.GetGenericMethodDefinition() == containsMethod)
                {
                    // obj.Get<IList<T>>("path").Contains(someValue)
                    if (IsParseObjectGet(node.Arguments[0] as MethodCallExpression))
                    {
                        return(source.WhereEqualTo(
                                   GetValue(((MethodCallExpression)node.Arguments[0]).Arguments[0]) as string,
                                   GetValue(node.Arguments[1])));
                    }
                    // someList.Contains(obj.Get<T>("path"))
                    if (IsParseObjectGet(node.Arguments[1] as MethodCallExpression))
                    {
                        var collection = GetValue(node.Arguments[0]) as System.Collections.IEnumerable;
                        return(source.WhereContainedIn(
                                   GetValue(((MethodCallExpression)node.Arguments[1]).Arguments[0]) as string,
                                   collection.Cast <object>()));
                    }
                }

                if (node.Method.GetGenericMethodDefinition() == notContainsMethod)
                {
                    // !obj.Get<IList<T>>("path").Contains(someValue)
                    if (IsParseObjectGet(node.Arguments[0] as MethodCallExpression))
                    {
                        return(source.WhereNotEqualTo(
                                   GetValue(((MethodCallExpression)node.Arguments[0]).Arguments[0]) as string,
                                   GetValue(node.Arguments[1])));
                    }
                    // !someList.Contains(obj.Get<T>("path"))
                    if (IsParseObjectGet(node.Arguments[1] as MethodCallExpression))
                    {
                        var collection = GetValue(node.Arguments[0]) as System.Collections.IEnumerable;
                        return(source.WhereNotContainedIn(
                                   GetValue(((MethodCallExpression)node.Arguments[1]).Arguments[0]) as string,
                                   collection.Cast <object>()));
                    }
                }
            }
            throw new InvalidOperationException(node.Method + " is not a supported method call in a where expression.");
        }
        private async Task<IEnumerable<TVEpisodeForParse>> GetParseEpisodeObject()
        {
            var query = new ParseQuery<TVEpisodeForParse>().WhereEqualTo("userEmail", ParseUser.CurrentUser.Email).WhereEqualTo("tmdbIDShow" , Intent.GetStringExtra("TMDBID"));
            IEnumerable<TVEpisodeForParse> result = await query.FindAsync();

            Console.WriteLine("Count of returned list is "+result.Count());

            return result;
        }
Exemple #43
0
 /// <summary>
 /// Pushes a simple message to every device matching the target query. This is shorthand for:
 ///
 /// <code>
 /// var push = new ParsePush();
 /// push.Query = query;
 /// push.Data = new Dictionary&lt;string, object&gt;{{"alert", alert}};
 /// return push.SendAsync();
 /// </code>
 /// </summary>
 /// <param name="alert">The alert message to send.</param>
 /// <param name="query">A query filtering the devices which should receive this Push Notification.</param>
 public static Task SendPushAlertAsync(this IServiceHub serviceHub, string alert, ParseQuery <ParseInstallation> query) => new ParsePush(serviceHub)
 {
     Query = query, Alert = alert
 }.SendAsync();
Exemple #44
0
        /// <summary>
        /// Correlates the elements of two queries based on matching keys.
        /// </summary>
        /// <typeparam name="TOuter">The type of ParseObjects of the first query.</typeparam>
        /// <typeparam name="TInner">The type of ParseObjects of the second query.</typeparam>
        /// <typeparam name="TKey">The type of the keys returned by the key selector
        /// functions.</typeparam>
        /// <typeparam name="TResult">The type of the result. This must match either
        /// TOuter or TInner</typeparam>
        /// <param name="outer">The first query to join.</param>
        /// <param name="inner">The query to join to the first query.</param>
        /// <param name="outerKeySelector">A function to extract a join key from the results of
        /// the first query.</param>
        /// <param name="innerKeySelector">A function to extract a join key from the results of
        /// the second query.</param>
        /// <param name="resultSelector">A function to select either the outer or inner query
        /// result to determine which query is the base query.</param>
        /// <returns>A new ParseQuery with a WhereMatchesQuery or WhereMatchesKeyInQuery
        /// clause based upon the query indicated in the <paramref name="resultSelector"/>.</returns>
        public static ParseQuery <TResult> Join <TOuter, TInner, TKey, TResult>(
            this ParseQuery <TOuter> outer,
            ParseQuery <TInner> inner,
            Expression <Func <TOuter, TKey> > outerKeySelector,
            Expression <Func <TInner, TKey> > innerKeySelector,
            Expression <Func <TOuter, TInner, TResult> > resultSelector)
            where TOuter : ParseObject
            where TInner : ParseObject
            where TResult : ParseObject
        {
            // resultSelector must select either the inner object or the outer object. If it's the inner
            // object, reverse the query.
            if (resultSelector.Body == resultSelector.Parameters[1])
            {
                // The inner object was selected.
                return(inner.Join <TInner, TOuter, TKey, TInner>(
                           outer,
                           innerKeySelector,
                           outerKeySelector,
                           (i, o) => i) as ParseQuery <TResult>);
            }
            if (resultSelector.Body != resultSelector.Parameters[0])
            {
                throw new InvalidOperationException("Joins must select either the outer or inner object.");
            }

            // Normalize both selectors
            Expression           outerNormalized = new ObjectNormalizer().Visit(outerKeySelector.Body);
            Expression           innerNormalized = new ObjectNormalizer().Visit(innerKeySelector.Body);
            MethodCallExpression outerAsGet      = outerNormalized as MethodCallExpression;
            MethodCallExpression innerAsGet      = innerNormalized as MethodCallExpression;

            if (IsParseObjectGet(outerAsGet) && outerAsGet.Object == outerKeySelector.Parameters[0])
            {
                var outerKey = GetValue(outerAsGet.Arguments[0]) as string;

                if (IsParseObjectGet(innerAsGet) && innerAsGet.Object == innerKeySelector.Parameters[0])
                {
                    // Both are key accesses, so treat this as a WhereMatchesKeyInQuery
                    var innerKey = GetValue(innerAsGet.Arguments[0]) as string;
                    return(outer.WhereMatchesKeyInQuery(outerKey, innerKey, inner) as ParseQuery <TResult>);
                }

                if (innerKeySelector.Body == innerKeySelector.Parameters[0])
                {
                    // The inner selector is on the result of the query itself, so treat this as a
                    // WhereMatchesQuery
                    return(outer.WhereMatchesQuery(outerKey, inner) as ParseQuery <TResult>);
                }
                throw new InvalidOperationException(
                          "The key for the joined object must be a ParseObject or a field access " +
                          "on the ParseObject.");
            }

            // TODO (hallucinogen): If we ever support "and" queries fully and/or support a "where this object
            // matches some key in some other query" (as opposed to requiring a key on this query), we
            // can add support for even more types of joins.

            throw new InvalidOperationException(
                      "The key for the selected object must be a field access on the ParseObject.");
        }
Exemple #45
0
 /// <summary>
 /// Pushes an arbitrary payload to every device matching target. This is shorthand for:
 ///
 /// <code>
 /// var push = new ParsePush();
 /// push.Query = query
 /// push.Data = data;
 /// return push.SendAsync();
 /// </code>
 /// </summary>
 /// <param name="data">A push payload. See the ParsePush.Data property for more information.</param>
 /// <param name="query">A query filtering the devices which should receive this Push Notification.</param>
 public static Task SendPushDataAsync(this IServiceHub serviceHub, IDictionary <string, object> data, ParseQuery <ParseInstallation> query) => new ParsePush(serviceHub)
 {
     Query = query, Data = data
 }.SendAsync();
 /// <summary>
 /// Adds a constraint to the query that requires that a particular key's value
 /// does not match another ParseQuery. This only works on keys whose values are
 /// ParseObjects or lists of ParseObjects.
 /// </summary>
 /// <param name="key">The key to check.</param>
 /// <param name="query">The query that the value should not match.</param>
 /// <returns>A new query with the additional constraint.</returns>
 public ParseQuery <T> WhereDoesNotMatchQuery <TOther>(string key, ParseQuery <TOther> query) where TOther : ParseObject => new ParseQuery <T>(this, where : new Dictionary <string, object> {
     { key, new Dictionary <string, object> {
           { "$notInQuery", query.BuildParameters(true) }
       } }
 });
 /// <summary>
 /// Constructs a query that is the or of the given queries.
 /// </summary>
 /// <typeparam name="T">The type of ParseObject being queried.</typeparam>
 /// <param name="source">An initial query to 'or' with additional queries.</param>
 /// <param name="queries">The list of ParseQueries to 'or' together.</param>
 /// <returns>A query that is the or of the given queries.</returns>
 public static ParseQuery <T> Or <T>(this ParseQuery <T> source, params ParseQuery <T>[] queries)
     where T : ParseObject
 {
     return(ParseQuery <T> .Or(queries.Concat(new[] { source })));
 }
        // ALTERNATE NAME: BuildOrQuery

        /// <summary>
        /// Constructs a query that is the or of the given queries.
        /// </summary>
        /// <typeparam name="T">The type of ParseObject being queried.</typeparam>
        /// <param name="source">An initial query to 'or' with additional queries.</param>
        /// <param name="queries">The list of ParseQueries to 'or' together.</param>
        /// <returns>A query that is the or of the given queries.</returns>
        public static ParseQuery <T> ConstructOrQuery <T>(this IServiceHub serviceHub, ParseQuery <T> source, params ParseQuery <T>[] queries) where T : ParseObject => serviceHub.ConstructOrQuery(queries.Concat(new[] { source }));
        private async Task  DownloadTrakkedShows()
        {
            var query = new ParseQuery<TVShowForParse>();
            var myListOfShows = await query.FindAsync();

            var mySingleton = ParseTVShowListSingleton.Instance;

            mySingleton.SetParseTVShows(myListOfShows);

        }
        /// <summary>
        /// Determines whether the specified object is equal to the current object.
        /// </summary>
        /// <param name="obj">The object to compare with the current object.</param>
        /// <returns><c>true</c> if the specified object is equal to the current object; otherwise, <c>false</c></returns>
        public override bool Equals(object obj)
        {
            ParseQuery <T> other = obj as ParseQuery <T>;

            return(obj == null || other == null ? false : Equals(className, other.ClassName) && where.CollectionsEqual(other.where) && orderBy.CollectionsEqual(other.orderBy) && includes.CollectionsEqual(other.includes) && selectedKeys.CollectionsEqual(other.selectedKeys) && Equals(skip, other.skip) && Equals(limit, other.limit));
        }
Exemple #51
0
 /// <summary>
 /// Performs a subsequent ordering of a query based upon the key selector provided.
 /// </summary>
 /// <typeparam name="TSource">The type of ParseObject being queried for.</typeparam>
 /// <typeparam name="TSelector">The type of key returned by keySelector.</typeparam>
 /// <param name="source">The query to order.</param>
 /// <param name="keySelector">A function to extract a key from the ParseObject.</param>
 /// <returns>A new ParseQuery based on source whose results will be ordered by
 /// the key specified in the keySelector.</returns>
 public static ParseQuery <TSource> ThenByDescending <TSource, TSelector>(
     this ParseQuery <TSource> source, Expression <Func <TSource, TSelector> > keySelector)
     where TSource : ParseObject
 {
     return(source.ThenByDescending(GetOrderByPath(keySelector)));
 }