예제 #1
0
    public Task SendPushNotificationAsync(IPushState state, String sessionToken, CancellationToken cancellationToken) {
      var command = new ParseCommand("/1/push",
          method: "POST",
          sessionToken: sessionToken,
          data: ParsePushEncoder.Instance.Encode(state));

      return ParseClient.ParseCommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken);
    }
    public Task RevokeAsync(string sessionToken, CancellationToken cancellationToken) {
      var command = new ParseCommand("logout",
          method: "POST",
          sessionToken: sessionToken,
          data: new Dictionary<string, object>());

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken);
    }
        public Task RevokeAsync(string sessionToken, CancellationToken cancellationToken)
        {
            var command = new ParseCommand("logout",
                                           method: "POST",
                                           sessionToken: sessionToken,
                                           data: new Dictionary <string, object>());

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
예제 #4
0
        public Task SendPushNotificationAsync(IPushState state, String sessionToken, CancellationToken cancellationToken)
        {
            var command = new ParseCommand("/1/push",
                                           method: "POST",
                                           sessionToken: sessionToken,
                                           data: ParsePushEncoder.Instance.Encode(state));

            return(ParseClient.ParseCommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
    public Task<IObjectState> GetUserAsync(string sessionToken, CancellationToken cancellationToken) {
      var command = new ParseCommand("users/me",
          method: "GET",
          sessionToken: sessionToken,
          data: null);

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
        return ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
      });
    }
    public Task<IObjectState> UpgradeToRevocableSessionAsync(string sessionToken, CancellationToken cancellationToken) {
      var command = new ParseCommand("upgradeToRevocableSession",
          method: "POST",
          sessionToken: sessionToken,
          data: new Dictionary<string, object>());

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
        return ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
      });
    }
예제 #7
0
        public Task RequestPasswordResetAsync(string email, CancellationToken cancellationToken)
        {
            var command = new ParseCommand("requestPasswordReset",
                                           method: "POST",
                                           data: new Dictionary <string, object> {
                { "email", email }
            });

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
        public Task <IObjectState> UpgradeToRevocableSessionAsync(string sessionToken, CancellationToken cancellationToken)
        {
            var command = new ParseCommand("upgradeToRevocableSession",
                                           method: "POST",
                                           sessionToken: sessionToken,
                                           data: new Dictionary <string, object>());

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                return ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
            }));
        }
예제 #9
0
        public Task <IObjectState> GetUserAsync(string sessionToken, CancellationToken cancellationToken)
        {
            var command = new ParseCommand("users/me",
                                           method: "GET",
                                           sessionToken: sessionToken,
                                           data: null);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                return ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
            }));
        }
    public Task DeleteAsync(IObjectState state,
        string sessionToken,
        CancellationToken cancellationToken) {
      var command = new ParseCommand(string.Format("/1/classes/{0}/{1}",
              state.ClassName, state.ObjectId),
          method: "DELETE",
          sessionToken: sessionToken,
          data: null);

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken);
    }
예제 #11
0
        public Task DeleteAsync(IObjectState state,
                                string sessionToken,
                                CancellationToken cancellationToken)
        {
            var command = new ParseCommand(string.Format("classes/{0}/{1}",
                                                         state.ClassName, state.ObjectId),
                                           method: "DELETE",
                                           sessionToken: sessionToken,
                                           data: null);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
예제 #12
0
    public void TestMakeCommand() {
      ParseCommand command = new ParseCommand("endpoint",
          method: "GET",
          sessionToken: "abcd",
          headers: null,
          data: null);

      Assert.AreEqual("/1/endpoint", command.Uri.AbsolutePath);
      Assert.AreEqual("GET", command.Method);
      Assert.IsTrue(command.Headers.Any(pair => pair.Key == "X-Parse-Session-Token" && pair.Value == "abcd"));
      Assert.Greater(command.Headers.Count, 2);
    }
    public Task<IObjectState> FetchAsync(IObjectState state,
        string sessionToken,
        CancellationToken cancellationToken) {
      var command = new ParseCommand(string.Format("/1/classes/{0}/{1}",
              Uri.EscapeDataString(state.ClassName),
              Uri.EscapeDataString(state.ObjectId)),
          method: "GET",
          sessionToken: sessionToken,
          data: null);

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
        return ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
      });
    }
    public Task<ParseConfig> FetchConfigAsync(String sessionToken, CancellationToken cancellationToken) {
      var command = new ParseCommand("config",
          method: "GET",
          sessionToken: sessionToken,
          data: null);

      return ParseClient.ParseCommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(task => {
        cancellationToken.ThrowIfCancellationRequested();
        return new ParseConfig(task.Result.Item2);
      }).OnSuccess(task => {
        cancellationToken.ThrowIfCancellationRequested();
        CurrentConfigController.SetCurrentConfigAsync(task.Result);
        return task;
      }).Unwrap();
    }
예제 #15
0
        public Task <IObjectState> FetchAsync(IObjectState state,
                                              string sessionToken,
                                              CancellationToken cancellationToken)
        {
            var command = new ParseCommand(string.Format("classes/{0}/{1}",
                                                         Uri.EscapeDataString(state.ClassName),
                                                         Uri.EscapeDataString(state.ObjectId)),
                                           method: "GET",
                                           sessionToken: sessionToken,
                                           data: null);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                return ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
            }));
        }
        public Task <ParseConfig> FetchConfigAsync(String sessionToken, CancellationToken cancellationToken)
        {
            var command = new ParseCommand("/1/config",
                                           method: "GET",
                                           sessionToken: sessionToken,
                                           data: null);

            return(ParseClient.ParseCommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(task => {
                cancellationToken.ThrowIfCancellationRequested();
                return new ParseConfig(task.Result.Item2);
            }).OnSuccess(task => {
                cancellationToken.ThrowIfCancellationRequested();
                CurrentConfigController.SetCurrentConfigAsync(task.Result);
                return task;
            }).Unwrap());
        }
예제 #17
0
        private Task <IDictionary <string, object> > FindAsync(string className,
                                                               IDictionary <string, object> parameters,
                                                               string sessionToken,
                                                               CancellationToken cancellationToken)
        {
            var command = new ParseCommand(string.Format("classes/{0}?{1}",
                                                         Uri.EscapeDataString(className),
                                                         ParseClient.BuildQueryString(parameters)),
                                           method: "GET",
                                           sessionToken: sessionToken,
                                           data: null);

            return(ParseClient.ParseCommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                return t.Result.Item2;
            }));
        }
예제 #18
0
        public Task <FileState> SaveAsync(FileState state,
                                          Stream dataStream,
                                          String sessionToken,
                                          IProgress <ParseUploadProgressEventArgs> progress,
                                          CancellationToken cancellationToken = default(CancellationToken))
        {
            if (state.Url != null)
            {
                // !isDirty
                return(Task <FileState> .FromResult(state));
            }

            if (cancellationToken.IsCancellationRequested)
            {
                var tcs = new TaskCompletionSource <FileState>();
                tcs.TrySetCanceled();
                return(tcs.Task);
            }

            var oldPosition = dataStream.Position;
            var command     = new ParseCommand("/1/files/" + state.Name,
                                               method: "POST",
                                               sessionToken: sessionToken,
                                               contentType: state.MimeType,
                                               stream: dataStream);

            return(commandRunner.RunCommandAsync(command,
                                                 uploadProgress: progress,
                                                 cancellationToken: cancellationToken).OnSuccess(uploadTask => {
                var result = uploadTask.Result;
                var jsonData = result.Item2;
                cancellationToken.ThrowIfCancellationRequested();

                return new FileState {
                    Name = jsonData["name"] as string,
                    Url = new Uri(jsonData["url"] as string, UriKind.Absolute),
                    MimeType = state.MimeType
                };
            }).ContinueWith(t => {
                // Rewind the stream on failure or cancellation (if possible)
                if ((t.IsFaulted || t.IsCanceled) && dataStream.CanSeek)
                {
                    dataStream.Seek(oldPosition, SeekOrigin.Begin);
                }
                return t;
            }).Unwrap());
        }
    public Task TrackAppOpenedAsync(string pushHash,
        string sessionToken,
        CancellationToken cancellationToken) {
      IDictionary<string, object> data = new Dictionary<string, object> {
        { "at", DateTime.Now }
      };
      if (pushHash != null) {
        data["push_hash"] = pushHash;
      }

      var command = new ParseCommand("/1/events/AppOpened",
          method: "POST",
          sessionToken: sessionToken,
          data: PointerOrLocalIdEncoder.Instance.Encode(data) as IDictionary<string, object>);

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken);
    }
    public Task<IObjectState> SignUpAsync(IObjectState state,
        IDictionary<string, IParseFieldOperation> operations,
        CancellationToken cancellationToken) {
      var objectJSON = ParseObject.ToJSONObjectForSaving(operations);

      var command = new ParseCommand("classes/_User",
          method: "POST",
          data: objectJSON);

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
        var serverState = ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
        serverState = serverState.MutatedClone(mutableClone => {
          mutableClone.IsNew = true;
        });
        return serverState;
      });
    }
예제 #21
0
    public Task TestRunCommand() {
      var mockHttpClient = new Mock<IHttpClient>();
      var fakeResponse = Task<Tuple<HttpStatusCode, string>>.FromResult(new Tuple<HttpStatusCode, string>(HttpStatusCode.OK, "{}"));
      mockHttpClient.Setup(obj => obj.ExecuteAsync(It.IsAny<HttpRequest>(),
          It.IsAny<IProgress<ParseUploadProgressEventArgs>>(),
          It.IsAny<IProgress<ParseDownloadProgressEventArgs>>(),
          It.IsAny<CancellationToken>())).Returns(fakeResponse);

      ParseCommandRunner commandRunner = new ParseCommandRunner(mockHttpClient.Object);
      var command = new ParseCommand("endpoint", method: "GET", data: null);
      return commandRunner.RunCommandAsync(command).ContinueWith(t => {
        Assert.False(t.IsFaulted);
        Assert.False(t.IsCanceled);
        Assert.IsInstanceOf(typeof(IDictionary<string, object>), t.Result.Item2);
        Assert.AreEqual(0, t.Result.Item2.Count);
      });
    }
예제 #22
0
        public Task <IObjectState> SignUpAsync(IObjectState state,
                                               IDictionary <string, IParseFieldOperation> operations,
                                               CancellationToken cancellationToken)
        {
            var objectJSON = ParseObject.ToJSONObjectForSaving(operations);

            var command = new ParseCommand("classes/_User",
                                           method: "POST",
                                           data: objectJSON);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                var serverState = ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
                serverState = serverState.MutatedClone(mutableClone => {
                    mutableClone.IsNew = true;
                });
                return serverState;
            }));
        }
    public Task TrackEventAsync(string name,
        IDictionary<string, string> dimensions,
        string sessionToken,
        CancellationToken cancellationToken) {
      IDictionary<string, object> data = new Dictionary<string, object> {
        { "at", DateTime.Now },
        { "name", name },
      };
      if (dimensions != null) {
        data["dimensions"] = dimensions;
      }

      var command = new ParseCommand("/1/events/" + name,
          method: "POST",
          sessionToken: sessionToken,
          data: PointerOrLocalIdEncoder.Instance.Encode(data) as IDictionary<string, object>);

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken);
    }
    public Task<FileState> SaveAsync(FileState state,
        Stream dataStream,
        String sessionToken,
        IProgress<ParseUploadProgressEventArgs> progress,
        CancellationToken cancellationToken = default(CancellationToken)) {
      if (state.Url != null) {
        // !isDirty
        return Task<FileState>.FromResult(state);
      }

      if (cancellationToken.IsCancellationRequested) {
        var tcs = new TaskCompletionSource<FileState>();
        tcs.TrySetCanceled();
        return tcs.Task;
      }

      var oldPosition = dataStream.Position;
      var command = new ParseCommand("files/" + state.Name,
          method: "POST",
          sessionToken: sessionToken,
          contentType: state.MimeType,
          stream: dataStream);

      return commandRunner.RunCommandAsync(command,
          uploadProgress: progress,
          cancellationToken: cancellationToken).OnSuccess(uploadTask => {
            var result = uploadTask.Result;
            var jsonData = result.Item2;
            cancellationToken.ThrowIfCancellationRequested();

            return new FileState {
              Name = jsonData["name"] as string,
              Url = new Uri(jsonData["url"] as string, UriKind.Absolute),
              MimeType = state.MimeType
            };
          }).ContinueWith(t => {
            // Rewind the stream on failure or cancellation (if possible)
            if ((t.IsFaulted || t.IsCanceled) && dataStream.CanSeek) {
              dataStream.Seek(oldPosition, SeekOrigin.Begin);
            }
            return t;
          }).Unwrap();
    }
예제 #25
0
        public Task <T> CallFunctionAsync <T>(String name,
                                              IDictionary <string, object> parameters,
                                              string sessionToken,
                                              CancellationToken cancellationToken)
        {
            var command = new ParseCommand(string.Format("functions/{0}", Uri.EscapeUriString(name)),
                                           method: "POST",
                                           sessionToken: sessionToken,
                                           data: NoObjectsEncoder.Instance.Encode(parameters) as IDictionary <string, object>);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                var decoded = ParseDecoder.Instance.Decode(t.Result.Item2) as IDictionary <string, object>;
                if (!decoded.ContainsKey("result"))
                {
                    return default(T);
                }
                return (T)ParseClient.ConvertTo <T>(decoded["result"]);
            }));
        }
        public Task TrackAppOpenedAsync(string pushHash,
                                        string sessionToken,
                                        CancellationToken cancellationToken)
        {
            IDictionary <string, object> data = new Dictionary <string, object> {
                { "at", DateTime.Now }
            };

            if (pushHash != null)
            {
                data["push_hash"] = pushHash;
            }

            var command = new ParseCommand("/1/events/AppOpened",
                                           method: "POST",
                                           sessionToken: sessionToken,
                                           data: PointerOrLocalIdEncoder.Instance.Encode(data) as IDictionary <string, object>);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
    public Task<IObjectState> LogInAsync(string authType,
        IDictionary<string, object> data,
        CancellationToken cancellationToken) {
      var authData = new Dictionary<string, object>();
      authData[authType] = data;

      var command = new ParseCommand("users",
          method: "POST",
          data: new Dictionary<string, object> {
            {"authData", authData}
          });

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
        var serverState = ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
        serverState = serverState.MutatedClone(mutableClone => {
          mutableClone.IsNew = t.Result.Item1 == System.Net.HttpStatusCode.Created;
        });
        return serverState;
      });
    }
    public Task<IObjectState> LogInAsync(string username,
        string password,
        CancellationToken cancellationToken) {
      var data = new Dictionary<string, object>{
        {"username", username},
        {"password", password}
      };

      var command = new ParseCommand(string.Format("login?{0}", ParseClient.BuildQueryString(data)),
          method: "GET",
          data: null);

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
        var serverState = ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
        serverState = serverState.MutatedClone(mutableClone => {
          mutableClone.IsNew = t.Result.Item1 == System.Net.HttpStatusCode.Created;
        });
        return serverState;
      });
    }
    public Task<IObjectState> SaveAsync(IObjectState state,
        IDictionary<string, IParseFieldOperation> operations,
        string sessionToken,
        CancellationToken cancellationToken) {
      var objectJSON = ParseObject.ToJSONObjectForSaving(operations);

      var command = new ParseCommand((state.ObjectId == null ?
              string.Format("/1/classes/{0}", Uri.EscapeDataString(state.ClassName)) :
              string.Format("/1/classes/{0}/{1}", Uri.EscapeDataString(state.ClassName), state.ObjectId)),
          method: (state.ObjectId == null ? "POST" : "PUT"),
          sessionToken: sessionToken,
          data: objectJSON);

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
        var serverState = ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
        serverState = serverState.MutatedClone(mutableClone => {
          mutableClone.IsNew = t.Result.Item1 == System.Net.HttpStatusCode.Created;
        });
        return serverState;
      });
    }
예제 #30
0
        public Task <IObjectState> LogInAsync(string username,
                                              string password,
                                              CancellationToken cancellationToken)
        {
            var data = new Dictionary <string, object> {
                { "username", username },
                { "password", password }
            };

            var command = new ParseCommand(string.Format("login?{0}", ParseClient.BuildQueryString(data)),
                                           method: "GET",
                                           data: null);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                var serverState = ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
                serverState = serverState.MutatedClone(mutableClone => {
                    mutableClone.IsNew = t.Result.Item1 == System.Net.HttpStatusCode.Created;
                });
                return serverState;
            }));
        }
    public Task<Tuple<HttpStatusCode, IDictionary<string, object>>> RunCommandAsync(ParseCommand command,
        IProgress<ParseUploadProgressEventArgs> uploadProgress = null,
        IProgress<ParseDownloadProgressEventArgs> downloadProgress = null,
        CancellationToken cancellationToken = default(CancellationToken)) {
      return httpClient.ExecuteAsync(command, uploadProgress, downloadProgress, cancellationToken).OnSuccess(t => {
        cancellationToken.ThrowIfCancellationRequested();

        var response = t.Result;
        var contentString = response.Item2;
        int responseCode = (int)response.Item1;
        if (responseCode >= 500) {
          // Server error, return InternalServerError.
          throw new ParseException(ParseException.ErrorCode.InternalServerError, response.Item2);
        } else if (contentString != null) {
          IDictionary<string, object> contentJson = null;
          try {
            if (contentString.StartsWith("[")) {
              var arrayJson = Json.Parse(contentString);
              contentJson = new Dictionary<string, object> { { "results", arrayJson } };
            } else {
              contentJson = Json.Parse(contentString) as IDictionary<string, object>;
            }
          } catch (Exception e) {
            throw new ParseException(ParseException.ErrorCode.OtherCause,
                "Invalid response from server", e);
          }
          if (responseCode < 200 || responseCode > 299) {
            int code = (int)(contentJson.ContainsKey("code") ? (long)contentJson["code"] : (int)ParseException.ErrorCode.OtherCause);
            string error = contentJson.ContainsKey("error") ?
                contentJson["error"] as string :
                contentString;
            throw new ParseException((ParseException.ErrorCode)code, error);
          }
          return new Tuple<HttpStatusCode, IDictionary<string, object>>(response.Item1,
              contentJson);
        }
        return new Tuple<HttpStatusCode, IDictionary<string, object>>(response.Item1, null);
      });
    }
        public Task TrackEventAsync(string name,
                                    IDictionary <string, string> dimensions,
                                    string sessionToken,
                                    CancellationToken cancellationToken)
        {
            IDictionary <string, object> data = new Dictionary <string, object> {
                { "at", DateTime.Now },
                { "name", name },
            };

            if (dimensions != null)
            {
                data["dimensions"] = dimensions;
            }

            var command = new ParseCommand("/1/events/" + name,
                                           method: "POST",
                                           sessionToken: sessionToken,
                                           data: PointerOrLocalIdEncoder.Instance.Encode(data) as IDictionary <string, object>);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken));
        }
예제 #33
0
        public Task <IObjectState> SaveAsync(IObjectState state,
                                             IDictionary <string, IParseFieldOperation> operations,
                                             string sessionToken,
                                             CancellationToken cancellationToken)
        {
            var objectJSON = ParseObject.ToJSONObjectForSaving(operations);

            var command = new ParseCommand((state.ObjectId == null ?
                                            string.Format("classes/{0}", Uri.EscapeDataString(state.ClassName)) :
                                            string.Format("classes/{0}/{1}", Uri.EscapeDataString(state.ClassName), state.ObjectId)),
                                           method: (state.ObjectId == null ? "POST" : "PUT"),
                                           sessionToken: sessionToken,
                                           data: objectJSON);

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                var serverState = ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
                serverState = serverState.MutatedClone(mutableClone => {
                    mutableClone.IsNew = t.Result.Item1 == System.Net.HttpStatusCode.Created;
                });
                return serverState;
            }));
        }
예제 #34
0
        public Task <IObjectState> LogInAsync(string authType,
                                              IDictionary <string, object> data,
                                              CancellationToken cancellationToken)
        {
            var authData = new Dictionary <string, object>();

            authData[authType] = data;

            var command = new ParseCommand("users",
                                           method: "POST",
                                           data: new Dictionary <string, object> {
                { "authData", authData }
            });

            return(commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).OnSuccess(t => {
                var serverState = ParseObjectCoder.Instance.Decode(t.Result.Item2, ParseDecoder.Instance);
                serverState = serverState.MutatedClone(mutableClone => {
                    mutableClone.IsNew = t.Result.Item1 == System.Net.HttpStatusCode.Created;
                });
                return serverState;
            }));
        }
예제 #35
0
    public Task TestRunCommandWithInvalidString() {
      var mockHttpClient = new Mock<IHttpClient>();
      var fakeResponse = Task<Tuple<HttpStatusCode, string>>.FromResult(new Tuple<HttpStatusCode, string>(HttpStatusCode.OK, "invalid"));
      mockHttpClient.Setup(obj => obj.ExecuteAsync(It.IsAny<HttpRequest>(),
          It.IsAny<IProgress<ParseUploadProgressEventArgs>>(),
          It.IsAny<IProgress<ParseDownloadProgressEventArgs>>(),
          It.IsAny<CancellationToken>())).Returns(fakeResponse);

      ParseCommandRunner commandRunner = new ParseCommandRunner(mockHttpClient.Object);
      var command = new ParseCommand("endpoint", method: "GET", data: null);
      return commandRunner.RunCommandAsync(command).ContinueWith(t => {
        Assert.True(t.IsFaulted);
        Assert.False(t.IsCanceled);
        Assert.IsInstanceOf<ParseException>(t.Exception.InnerException);
        var parseException = t.Exception.InnerException as ParseException;
        Assert.AreEqual(ParseException.ErrorCode.OtherCause, parseException.Code);
      });
    }
예제 #36
0
        private IList <Task <IDictionary <string, object> > > ExecuteBatchRequest(IList <ParseCommand> requests,
                                                                                  string sessionToken,
                                                                                  CancellationToken cancellationToken)
        {
            var tasks     = new List <Task <IDictionary <string, object> > >();
            int batchSize = requests.Count;
            var tcss      = new List <TaskCompletionSource <IDictionary <string, object> > >();

            for (int i = 0; i < batchSize; ++i)
            {
                var tcs = new TaskCompletionSource <IDictionary <string, object> >();
                tcss.Add(tcs);
                tasks.Add(tcs.Task);
            }

            var encodedRequests = requests.Select(r => {
                var results = new Dictionary <string, object> {
                    { "method", r.Method },
                    { "path", r.Uri.AbsolutePath },
                };

                if (r.DataObject != null)
                {
                    results["body"] = r.DataObject;
                }
                return(results);
            }).Cast <object>().ToList();
            var command = new ParseCommand("batch",
                                           method: "POST",
                                           sessionToken: sessionToken,
                                           data: new Dictionary <string, object> {
                { "requests", encodedRequests }
            });

            commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).ContinueWith(t => {
                if (t.IsFaulted || t.IsCanceled)
                {
                    foreach (var tcs in tcss)
                    {
                        if (t.IsFaulted)
                        {
                            tcs.TrySetException(t.Exception);
                        }
                        else if (t.IsCanceled)
                        {
                            tcs.TrySetCanceled();
                        }
                    }
                    return;
                }

                var resultsArray = Conversion.As <IList <object> >(t.Result.Item2["results"]);
                int resultLength = resultsArray.Count;
                if (resultLength != batchSize)
                {
                    foreach (var tcs in tcss)
                    {
                        tcs.TrySetException(new InvalidOperationException(
                                                "Batch command result count expected: " + batchSize + " but was: " + resultLength + "."));
                    }
                    return;
                }

                for (int i = 0; i < batchSize; ++i)
                {
                    var result = resultsArray[i] as Dictionary <string, object>;
                    var tcs    = tcss[i];

                    if (result.ContainsKey("success"))
                    {
                        tcs.TrySetResult(result["success"] as IDictionary <string, object>);
                    }
                    else if (result.ContainsKey("error"))
                    {
                        var error      = result["error"] as IDictionary <string, object>;
                        long errorCode = (long)error["code"];
                        tcs.TrySetException(new ParseException((ParseException.ErrorCode)errorCode, error["error"] as string));
                    }
                    else
                    {
                        tcs.TrySetException(new InvalidOperationException(
                                                "Invalid batch command response."));
                    }
                }
            });

            return(tasks);
        }
    private IList<Task<IDictionary<string, object>>> ExecuteBatchRequest(IList<object> requests,
        string sessionToken,
        CancellationToken cancellationToken) {
      var tasks = new List<Task<IDictionary<string, object>>>();
      int batchSize = requests.Count;
      var tcss = new List<TaskCompletionSource<IDictionary<string, object>>>();
      for (int i = 0; i < batchSize; ++i) {
        var tcs = new TaskCompletionSource<IDictionary<string, object>>();
        tcss.Add(tcs);
        tasks.Add(tcs.Task);
      }

      var command = new ParseCommand("/1/batch",
        method: "POST",
        sessionToken: sessionToken,
        data: new Dictionary<string, object> { { "requests", requests } });

      commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken).ContinueWith(t => {
        if (t.IsFaulted || t.IsCanceled) {
          foreach (var tcs in tcss) {
            if (t.IsFaulted) {
              tcs.TrySetException(t.Exception);
            } else if (t.IsCanceled) {
              tcs.TrySetCanceled();
            }
          }
          return;
        }

        var resultsArray = ParseClient.As<IList<object>>(t.Result.Item2["results"]);
        int resultLength = resultsArray.Count;
        if (resultLength != batchSize) {
          foreach (var tcs in tcss) {
            tcs.TrySetException(new InvalidOperationException(
                "Batch command result count expected: " + batchSize + " but was: " + resultLength + "."));
          }
          return;
        }

        for (int i = 0; i < batchSize; ++i) {
          var result = resultsArray[i] as Dictionary<string, object>;
          var tcs = tcss[i];

          if (result.ContainsKey("success")) {
            tcs.TrySetResult(result["success"] as IDictionary<string, object>);
          } else if (result.ContainsKey("error")) {
            var error = result["error"] as IDictionary<string, object>;
            long errorCode = (long)error["code"];
            tcs.TrySetException(new ParseException((ParseException.ErrorCode)errorCode, error["error"] as string));
          } else {
            tcs.TrySetException(new InvalidOperationException(
                "Invalid batch command response."));
          }
        }
      });

      return tasks;
    }
    public Task RequestPasswordResetAsync(string email, CancellationToken cancellationToken) {
      var command = new ParseCommand("requestPasswordReset",
          method: "POST",
          data: new Dictionary<string, object> {
            {"email", email}
          });

      return commandRunner.RunCommandAsync(command, cancellationToken: cancellationToken);
    }
        public Task <Tuple <HttpStatusCode, IDictionary <string, object> > > RunCommandAsync(ParseCommand command,
                                                                                             IProgress <ParseUploadProgressEventArgs> uploadProgress     = null,
                                                                                             IProgress <ParseDownloadProgressEventArgs> downloadProgress = null,
                                                                                             CancellationToken cancellationToken = default(CancellationToken))
        {
            return(httpClient.ExecuteAsync(command, uploadProgress, downloadProgress, cancellationToken).OnSuccess(t => {
                cancellationToken.ThrowIfCancellationRequested();

                var response = t.Result;
                var contentString = response.Item2;
                int responseCode = (int)response.Item1;
                if (responseCode >= 500)
                {
                    // Server error, return InternalServerError.
                    throw new ParseException(ParseException.ErrorCode.InternalServerError, response.Item2);
                }
                else if (contentString != null)
                {
                    IDictionary <string, object> contentJson = null;
                    try {
                        if (contentString.StartsWith("["))
                        {
                            var arrayJson = Json.Parse(contentString);
                            contentJson = new Dictionary <string, object> {
                                { "results", arrayJson }
                            };
                        }
                        else
                        {
                            contentJson = Json.Parse(contentString) as IDictionary <string, object>;
                        }
                    } catch (Exception e) {
                        throw new ParseException(ParseException.ErrorCode.OtherCause,
                                                 "Invalid response from server", e);
                    }
                    if (responseCode < 200 || responseCode > 299)
                    {
                        int code = (int)(contentJson.ContainsKey("code") ? (long)contentJson["code"] : (int)ParseException.ErrorCode.OtherCause);
                        string error = contentJson.ContainsKey("error") ?
                                       contentJson["error"] as string :
                                       contentString;
                        throw new ParseException((ParseException.ErrorCode)code, error);
                    }
                    return new Tuple <HttpStatusCode, IDictionary <string, object> >(response.Item1,
                                                                                     contentJson);
                }
                return new Tuple <HttpStatusCode, IDictionary <string, object> >(response.Item1, null);
            }));
        }