public Task TestSave()
        {
            Mock <IParseCommandRunner> mockRunner = CreateMockRunner(new Tuple <HttpStatusCode, IDictionary <string, object> >(HttpStatusCode.Accepted, new Dictionary <string, object> {
                ["__type"] = "Object", ["className"] = "Corgi", ["objectId"] = "st4nl3yW", ["doge"] = "isShibaInu", ["createdAt"] = "2015-09-18T18:11:28.943Z"
            }));

            return(new ParseObjectController(mockRunner.Object).SaveAsync(new MutableObjectState {
                ClassName = "Corgi", ObjectId = "st4nl3yW", ServerData = new Dictionary <string, object> {
                    ["corgi"] = "isNotDoge"
                }
            }, new Dictionary <string, IParseFieldOperation> {
                ["gogo"] = new Mock <IParseFieldOperation> {
                }.Object
            }, null, CancellationToken.None).ContinueWith(t =>
            {
                Assert.IsFalse(t.IsFaulted);
                Assert.IsFalse(t.IsCanceled);

                mockRunner.Verify(obj => obj.RunCommandAsync(It.Is <ParseCommand>(command => command.Uri.AbsolutePath == "/1/classes/Corgi/st4nl3yW"), It.IsAny <IProgress <ParseUploadProgressEventArgs> >(), It.IsAny <IProgress <ParseDownloadProgressEventArgs> >(), It.IsAny <CancellationToken>()), Times.Exactly(1));

                IObjectState newState = t.Result;
                Assert.AreEqual("isShibaInu", newState["doge"]);
                Assert.IsFalse(newState.ContainsKey("corgi"));
                Assert.IsFalse(newState.ContainsKey("gogo"));
                Assert.IsNotNull(newState.CreatedAt);
                Assert.IsNotNull(newState.UpdatedAt);
            }));
        }
Exemplo n.º 2
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.Decode(t.Result.Item2, ParseDecoder.Instance);
                serverState = serverState.MutatedClone(mutableClone =>
                {
                    mutableClone.IsNew = t.Result.Item1 == System.Net.HttpStatusCode.Created;
                });
                return serverState;
            }));
        }
Exemplo n.º 3
0
        public Task TestLogInWithUsernamePassword()
        {
            Dictionary <string, object> responseDict = new Dictionary <string, object>
            {
                ["__type"]       = "Object",
                ["className"]    = "_User",
                ["objectId"]     = "d3ImSh3ki",
                ["sessionToken"] = "s3ss10nt0k3n",
                ["createdAt"]    = "2015-09-18T18:11:28.943Z"
            };

            Mock <IParseCommandRunner> mockRunner = CreateMockRunner(new Tuple <HttpStatusCode, IDictionary <string, object> >(HttpStatusCode.Accepted, responseDict));

            return(new ParseUserController(mockRunner.Object, Client.Decoder).LogInAsync("grantland", "123grantland123", Client, CancellationToken.None).ContinueWith(task =>
            {
                Assert.IsFalse(task.IsFaulted);
                Assert.IsFalse(task.IsCanceled);

                mockRunner.Verify(obj => obj.RunCommandAsync(It.Is <ParseCommand>(command => command.Path == "login?username=grantland&password=123grantland123"), It.IsAny <IProgress <IDataTransferLevel> >(), It.IsAny <IProgress <IDataTransferLevel> >(), It.IsAny <CancellationToken>()), Times.Exactly(1));

                IObjectState newState = task.Result;
                Assert.AreEqual("s3ss10nt0k3n", newState["sessionToken"]);
                Assert.AreEqual("d3ImSh3ki", newState.ObjectId);
                Assert.IsNotNull(newState.CreatedAt);
                Assert.IsNotNull(newState.UpdatedAt);
            }));
        }
        public Task TestLogInWithUsernamePassword()
        {
            Dictionary <string, object> responseDict = new Dictionary <string, object>()
            {
                { "__type", "Object" },
                { "className", "_User" },
                { "objectId", "d3ImSh3ki" },
                { "sessionToken", "s3ss10nt0k3n" },
                { "createdAt", "2015-09-18T18:11:28.943Z" }
            };
            Tuple <HttpStatusCode, IDictionary <string, object> > response = new Tuple <HttpStatusCode, IDictionary <string, object> >(HttpStatusCode.Accepted, responseDict);
            Mock <IParseCommandRunner> mockRunner = CreateMockRunner(response);

            ParseUserController controller = new ParseUserController(mockRunner.Object);

            return(controller.LogInAsync("grantland", "123grantland123", CancellationToken.None).ContinueWith(t =>
            {
                Assert.IsFalse(t.IsFaulted);
                Assert.IsFalse(t.IsCanceled);

                mockRunner.Verify(obj => obj.RunCommandAsync(It.Is <ParseCommand>(command => command.Uri.AbsolutePath == "/1/login"),
                                                             It.IsAny <IProgress <ParseUploadProgressEventArgs> >(),
                                                             It.IsAny <IProgress <ParseDownloadProgressEventArgs> >(),
                                                             It.IsAny <CancellationToken>()), Times.Exactly(1));

                IObjectState newState = t.Result;
                Assert.AreEqual("s3ss10nt0k3n", newState["sessionToken"]);
                Assert.AreEqual("d3ImSh3ki", newState.ObjectId);
                Assert.IsNotNull(newState.CreatedAt);
                Assert.IsNotNull(newState.UpdatedAt);
            }));
        }
Exemplo n.º 5
0
        public Task TestUpgradeToRevocableSession()
        {
            Tuple <HttpStatusCode, IDictionary <string, object> > response = new Tuple <HttpStatusCode, IDictionary <string, object> >(HttpStatusCode.Accepted,
                                                                                                                                       new Dictionary <string, object>()
            {
                { "__type", "Object" },
                { "className", "Session" },
                { "sessionToken", "S0m3Se551on" },
                { "restricted", true }
            });
            Mock <IParseCommandRunner> mockRunner = CreateMockRunner(response);

            ParseSessionController controller = new ParseSessionController(mockRunner.Object);

            return(controller.UpgradeToRevocableSessionAsync("S0m3Se551on", CancellationToken.None).ContinueWith(t =>
            {
                Assert.IsFalse(t.IsFaulted);
                Assert.IsFalse(t.IsCanceled);
                mockRunner.Verify(obj => obj.RunCommandAsync(It.Is <ParseCommand>(command => command.Uri.AbsolutePath == "/1/upgradeToRevocableSession"),
                                                             It.IsAny <IProgress <ParseUploadProgressEventArgs> >(),
                                                             It.IsAny <IProgress <ParseDownloadProgressEventArgs> >(),
                                                             It.IsAny <CancellationToken>()), Times.Exactly(1));

                IObjectState session = t.Result;
                Assert.AreEqual(2, session.Count());
                Assert.IsTrue((bool)session["restricted"]);
                Assert.AreEqual("S0m3Se551on", session["sessionToken"]);
            }));
        }
Exemplo n.º 6
0
 internal void ResetAction()
 {
     _actionChosenState         = null;
     _actionWasChosen           = false;
     _actionShouldStopTraversal = false;
     _creationDate = -1;
 }
Exemplo n.º 7
0
    /// <summary>
    /// 设置对象状态。
    /// </summary>
    /// <param name="state">给定的 <see cref="IObjectState"/>。</param>
    /// <param name="newStatusFactory">给定的新对象状态工厂方法。</param>
    /// <returns>返回状态(兼容不支持枚举类型的实体框架)。</returns>
    public static object SetObjectStatusAsync(this IObjectState state,
                                              Func <object, object> newStatusFactory)
    {
        var currentStatus = state.GetObjectStatus();

        return(state.SetObjectStatus(newStatusFactory(currentStatus)));
    }
Exemplo n.º 8
0
		internal void ResetAction()
		{
			_actionChosenState = null;
			_actionWasChosen = false;
			_actionShouldStopTraversal = false;
			_creationDate = -1;
		}
        public Task TestUpgradeToRevocableSession()
        {
            Tuple <HttpStatusCode, IDictionary <string, object> > response = new Tuple <HttpStatusCode, IDictionary <string, object> >(HttpStatusCode.Accepted,
                                                                                                                                       new Dictionary <string, object>
            {
                ["__type"]       = "Object",
                ["className"]    = "Session",
                ["sessionToken"] = "S0m3Se551on",
                ["restricted"]   = true
            });

            Mock <IParseCommandRunner> mockRunner = CreateMockRunner(response);

            return(new ParseSessionController(mockRunner.Object, Client.Decoder).UpgradeToRevocableSessionAsync("S0m3Se551on", Client, CancellationToken.None).ContinueWith(task =>
            {
                Assert.IsFalse(task.IsFaulted);
                Assert.IsFalse(task.IsCanceled);
                mockRunner.Verify(obj => obj.RunCommandAsync(It.Is <ParseCommand>(command => command.Path == "upgradeToRevocableSession"), It.IsAny <IProgress <IDataTransferLevel> >(), It.IsAny <IProgress <IDataTransferLevel> >(), It.IsAny <CancellationToken>()), Times.Exactly(1));

                IObjectState session = task.Result;
                Assert.AreEqual(2, session.Count());
                Assert.IsTrue((bool)session["restricted"]);
                Assert.AreEqual("S0m3Se551on", session["sessionToken"]);
            }));
        }
Exemplo n.º 10
0
    /// <summary>
    /// 异步设置对象状态。
    /// </summary>
    /// <param name="state">给定的 <see cref="IObjectState"/>。</param>
    /// <param name="newStatusFactory">给定的新对象状态工厂方法。</param>
    /// <param name="cancellationToken">给定的 <see cref="CancellationToken"/>(可选)。</param>
    /// <returns>返回一个包含状态(兼容不支持枚举类型的实体框架)的异步操作。</returns>
    public static async ValueTask <object> SetObjectStatusAsync(this IObjectState state,
                                                                Func <object, object> newStatusFactory, CancellationToken cancellationToken = default)
    {
        var currentStatus = await state.GetObjectStatusAsync(cancellationToken).DisableAwaitContext();

        return(await state.SetObjectStatusAsync(newStatusFactory(currentStatus), cancellationToken)
               .DisableAwaitContext());
    }
Exemplo n.º 11
0
 public void OnReplicate(IReplicationEvent replicationEvent)
 {
     if (replicationEvent.IsConflict())
     {
         IObjectState stateOfTheDesktop = replicationEvent.StateInProviderA();
         replicationEvent.OverrideWith(stateOfTheDesktop);
     }
 }
        /// <summary>
        /// 归还对象
        /// <see cref="RecedeCache"/> 为true时对象不是从pool拿出的会被加入pool
        /// </summary>
        /// <param name="obj"></param>
        public void Recede(object obj)
        {
            var  type = obj.GetType();
            bool hit  = false;

            IObjectState qState = null;

            if (_objectCache.TryGetValue(type, out var oResult))
            {
                if (oResult.Count < MaxCount)
                {
                    foreach (var state in oResult)
                    {
                        if (state.Obj == obj)
                        {
                            qState         = state;
                            hit            = true;
                            state.UseState = false;
                            break;
                        }
                    }
                }
            }

            if (!hit)
            {
                if (_weakObjectCache.TryGetValue(type, out var result))
                {
                    foreach (var state in result)
                    {
                        if (state.Obj == obj)
                        {
                            qState         = state;
                            hit            = true;
                            state.UseState = false;
                            break;
                        }
                    }
                }
            }

            if (hit)
            {
                if (!_objectCacheQueue.TryGetValue(type, out var result))
                {
                    result = new Queue <IObjectState>();
                    _objectCacheQueue.Add(type, result);
                }

                result.Enqueue(qState);
            }

            if (!hit && RecedeCache)
            {
                AddObjectToPool(obj, false);
            }
        }
Exemplo n.º 13
0
        internal override void HandleSave(IObjectState serverState)
        {
            base.HandleSave(serverState);

            SynchronizeAllAuthData();
            CleanupAuthData();

            MutateState(mutableClone => { mutableClone.ServerData.Remove("password"); });
        }
Exemplo n.º 14
0
        /// <summary>
        /// Retrieves at most one ParseObject that satisfies this query.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A single ParseObject that satisfies this query, or else null.</returns>
        public Task <T> FirstOrDefaultAsync(CancellationToken cancellationToken)
        {
            EnsureNotInstallationQuery();
            return(QueryController.FirstAsync <T>(this, ParseUser.CurrentUser, cancellationToken).OnSuccess(t => {
                IObjectState state = t.Result;

                return state == null ? default(T) : ParseObject.FromState <T>(state, ClassName);
            }));
        }
Exemplo n.º 15
0
        private IObjectState ProcessType(IObjectState state, Type type)
        {
            var members = _walker.GetDataMembers(type);

            foreach (var member in members)
            {
                state = ProcessMember(state, member);
            }
            return(state);
        }
Exemplo n.º 16
0
        internal override void DidReceive(object queryObj, Event objEvent, IObjectState objState)
        {
            ParseQuery <T> query = (ParseQuery <T>)queryObj;
            T obj = ParseObjectExtensions.FromState <T>(objState, query.GetClassName());

            foreach (EventsCallback <T> eventsCallback in _eventsCallbacks)
            {
                eventsCallback(query, objEvent, obj);
            }
        }
Exemplo n.º 17
0
        public static object SetObjectStatusAsync(this IObjectState state,
                                                  Func <object, object> newStatusFactory)
        {
            state.NotNull(nameof(state));
            newStatusFactory.NotNull(nameof(newStatusFactory));

            var newStatus = state.GetObjectStatus();

            return(state.SetObjectStatus(newStatusFactory.Invoke(newStatus)));
        }
Exemplo n.º 18
0
 public void OverrideWith(IObjectState chosen)
 {
     if (_actionWasChosen)
     {
         throw new Exception();
     }
     //FIXME Use Db4o's standard exception throwing.
     _actionWasChosen   = true;
     _actionChosenState = chosen;
 }
Exemplo n.º 19
0
		public void OverrideWith(IObjectState chosen)
		{
			if (_actionWasChosen)
			{
				throw new Exception();
			}
			//FIXME Use Db4o's standard exception throwing.
			_actionWasChosen = true;
			_actionChosenState = chosen;
		}
Exemplo n.º 20
0
    internal override void HandleSave(IObjectState serverState) {
      base.HandleSave(serverState);

      SynchronizeAllAuthData();
      CleanupAuthData();

      MutateState(mutableClone => {
        mutableClone.ServerData.Remove("password");
      });
    }
Exemplo n.º 21
0
        /// <summary>
        /// convert the actual node to editable mesh
        /// </summary>
        public void ConvertToMesh()
        {
            if (!this.IsValid)
            {
                return;
            }

            // get the current node world state
            IObjectState state = this.m_node.EvalWorldState(AssemblyFunctions.Core.Time, false);

            // get the object out of the state and check if it's possible to convert to editable mesh
            IObject obj = state.Obj;

            if (obj.CanConvertToType(AssemblyFunctions.GlobalInterface.TriObjectClassID) == 0)
            {
                return;
            }

            // convert the obj to triobject
            // if the node type was editable mesh, tit will return just the current node mesh
            // elsewhere it will return a new triobj instance which is not bound to anything
            ITriObject tri = obj.ConvertToType(AssemblyFunctions.Core.Time, AssemblyFunctions.GlobalInterface.TriObjectClassID) as ITriObject;

            // check if we got something
            if (tri == null)
            {
                return;
            }

            // remeber the obj and mesh for later use
            this.m_triMesh    = tri.Mesh;
            this.m_baseObject = obj;

            // check if the tri is identical with the current object from the node state
            // if the node was already editable mesh we don't need to do anything
            if (this.m_triMesh == null || tri.Equals((INoncopyable)obj))
            {
                return;
            }

            // notfiy all dependents
            // this notfiy was from a max sample. not sure why call first before change and call change afterwards
            this.m_node.NotifyDependents(Globals.FOREVER, Globals.PART_ALL, RefMessage.Change);

            // the the object reference of the node to the new triobj
            // important: if you exchange the object ref ith the same objref
            // like this.m_node.ObjectRef = this.m_node.ObjectRef you will produce a nice crash sometimes
            // the property setter inside max.net will delete the old reference and since the old is the new
            // the reference will be set to null which is illegal
            this.m_node.ObjectRef = tri;

            // notfiy all dependents
            this.m_node.NotifyDependents(Globals.FOREVER, 0, RefMessage.SubanimStructureChanged);
            this.m_node.NotifyDependents(Globals.FOREVER, Globals.PART_ALL, RefMessage.Change);
        }
Exemplo n.º 22
0
    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);
    }
Exemplo n.º 23
0
        public static async ValueTask <object> SetObjectStatusAsync(this IObjectState state,
                                                                    Func <object, object> newStatusFactory, CancellationToken cancellationToken = default)
        {
            state.NotNull(nameof(state));
            newStatusFactory.NotNull(nameof(newStatusFactory));

            var newStatus = await state.GetObjectStatusAsync(cancellationToken).ConfigureAwait();

            return(await state.SetObjectStatusAsync(newStatusFactory.Invoke(newStatus), cancellationToken)
                   .ConfigureAwait());
        }
Exemplo n.º 24
0
 /// <summary>
 /// Retrieves at most one AVObject that satisfies this query.
 /// </summary>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>A single AVObject that satisfies this query, or else null.</returns>
 public override Task <T> FirstOrDefaultAsync(CancellationToken cancellationToken)
 {
     return(AVUser.GetCurrentUserAsync().OnSuccess(t =>
     {
         return QueryController.FirstAsync <T>(this, t.Result, cancellationToken);
     }).Unwrap().OnSuccess(t =>
     {
         IObjectState state = t.Result;
         return state == null ? default(T) : AVObject.FromState <T>(state, ClassName);
     }));
 }
Exemplo n.º 25
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));
        }
            public void OnReplicate(IReplicationEvent @event)
            {
                invoked.SetValue(true);
                IObjectState stateA = @event.StateInProviderA();
                IObjectState stateB = @event.StateInProviderB();

                Assert.IsTrue(stateA.IsNew());
                Assert.IsTrue(!stateB.IsNew());
                Assert.IsNotNull(stateA.GetObject());
                Assert.IsNull(stateB.GetObject());
                @event.OverrideWith(null);
            }
Exemplo n.º 27
0
        private void HandleObjectEvent(Subscription.Event subscriptionEvent, IDictionary <string, object> jsonObject)
        {
            int requestId = Convert.ToInt32(jsonObject["requestId"]);
            IDictionary <string, object> objectData = (IDictionary <string, object>)jsonObject["object"];

            Subscription subscription;

            if (_subscriptions.TryGetValue(requestId, out subscription))
            {
                IObjectState objState = ParseObjectCoder.Instance.Decode(objectData, ParseDecoder.Instance);
                subscription.DidReceive(subscription.QueryObj, subscriptionEvent, objState);
            }
        }
Exemplo n.º 28
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 => ParseObjectCoder.Decode(t.Result.Item2, ParseDecoder.Instance)));
        }
Exemplo n.º 29
0
        private List <string> Validate(IEntityValidator validator, IObjectState entity)
        {
            if (validator == null)
            {
                return(new List <string>());
            }
            ValidationResult validationResult = validator.Validate((object)entity);

            if (validationResult.IsValid)
            {
                return(new List <string>());
            }
            return(validationResult.Errors.Select <ValidationFailure, string>((Func <ValidationFailure, string>)(failure => failure.ErrorMessage)).ToList <string>());
        }
Exemplo n.º 30
0
    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);
      });
    }
Exemplo n.º 31
0
        private HashSet <object> _entitesChecked;   // tracking of all process entities in the object graph when calling SyncObjectGraph

        private void SyncObjectGraph(object entity) // scan object graph for all
        {
            if (_entitesChecked == null)
            {
                _entitesChecked = new HashSet <object>();
            }

            if (_entitesChecked.Contains(entity))
            {
                return;
            }

            _entitesChecked.Add(entity);

            IObjectState objectState = entity as IObjectState;

            if (objectState != null && objectState.ObjectState == ObjectState.Added)
            {
                _context.SyncObjectState(entity as BaseEntity);
            }

            // Set tracking state for child collections
            foreach (PropertyInfo prop in entity.GetType().GetProperties())
            {
                // Apply changes to 1-1 and M-1 properties
                IObjectState trackableRef = prop.GetValue(entity, null) as IObjectState;
                if (trackableRef != null)
                {
                    if (trackableRef.ObjectState == ObjectState.Added)
                    {
                        _context.SyncObjectState(entity as BaseEntity);
                    }

                    SyncObjectGraph(prop.GetValue(entity, null));
                }

                // Apply changes to 1-M properties
                IEnumerable <IObjectState> items = prop.GetValue(entity, null) as IEnumerable <IObjectState>;
                if (items == null)
                {
                    continue;
                }

                foreach (IObjectState item in items)
                {
                    SyncObjectGraph(item);
                }
            }
        }
Exemplo n.º 32
0
            public void OnReplicate(IReplicationEvent replicationEvent)
            {
                IObjectState stateInDesktop = replicationEvent.StateInProviderA();

                if (stateInDesktop.IsNew())
                {
                    Console.WriteLine("Object '{0}' is new on desktop database",
                                      stateInDesktop.GetObject());
                }
                if (stateInDesktop.WasModified())
                {
                    Console.WriteLine("Object '{0}' was modified on desktop database",
                                      stateInDesktop.GetObject());
                }
            }
Exemplo n.º 33
0
    private void OnTriggerExit(Collider other)
    {
        if (!entity.IsOwner)
        {
            return;
        }

        if (other.gameObject.layer.Equals(LayerMask.NameToLayer("GravityField")))
        {
            IObjectState objectState = other.gameObject.GetComponentInParent <IObjectState>();
            if (other.gameObject.layer.Equals(LayerMask.NameToLayer("GravityField")))
            {
                gravityAttractorDictionary.Remove(objectState.GetGuid());
            }
        }
    }
            public void OnReplicate(IReplicationEvent e)
            {
                if (this._enclosing._containerStateToPrevail == null)
                {
                    e.OverrideWith(null);
                    return;
                }
                if (this._enclosing._containerStateToPrevail.IsEmpty())
                {
                    return;
                }
                IObjectState @override = this._enclosing._containerStateToPrevail.Contains(ReplicationFeaturesMain
                                                                                           .AStuff) ? e.StateInProviderA() : e.StateInProviderB();

                e.OverrideWith(@override);
            }
        public Task TestSignUp()
        {
            MutableObjectState state = new MutableObjectState
            {
                ClassName  = "_User",
                ServerData = new Dictionary <string, object>()
                {
                    { "username", "hallucinogen" },
                    { "password", "secret" }
                }
            };
            Dictionary <string, IParseFieldOperation> operations = new Dictionary <string, IParseFieldOperation>()
            {
                { "gogo", new Mock <IParseFieldOperation>().Object }
            };

            Dictionary <string, object> responseDict = new Dictionary <string, object>()
            {
                { "__type", "Object" },
                { "className", "_User" },
                { "objectId", "d3ImSh3ki" },
                { "sessionToken", "s3ss10nt0k3n" },
                { "createdAt", "2015-09-18T18:11:28.943Z" }
            };
            Tuple <HttpStatusCode, IDictionary <string, object> > response = new Tuple <HttpStatusCode, IDictionary <string, object> >(HttpStatusCode.Accepted, responseDict);
            Mock <IParseCommandRunner> mockRunner = CreateMockRunner(response);

            ParseUserController controller = new ParseUserController(mockRunner.Object);

            return(controller.SignUpAsync(state, operations, CancellationToken.None).ContinueWith(t =>
            {
                Assert.IsFalse(t.IsFaulted);
                Assert.IsFalse(t.IsCanceled);

                mockRunner.Verify(obj => obj.RunCommandAsync(It.Is <ParseCommand>(command => command.Uri.AbsolutePath == "/1/classes/_User"),
                                                             It.IsAny <IProgress <ParseUploadProgressEventArgs> >(),
                                                             It.IsAny <IProgress <ParseDownloadProgressEventArgs> >(),
                                                             It.IsAny <CancellationToken>()), Times.Exactly(1));

                IObjectState newState = t.Result;
                Assert.AreEqual("s3ss10nt0k3n", newState["sessionToken"]);
                Assert.AreEqual("d3ImSh3ki", newState.ObjectId);
                Assert.IsNotNull(newState.CreatedAt);
                Assert.IsNotNull(newState.UpdatedAt);
            }));
        }
    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;
      });
    }
Exemplo n.º 37
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("/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;
      });
    }
        //public override bool Equals(object obj)
        //{
        //    ObjectStateChangeArgs o = obj as ObjectStateChangeArgs;
        //    if (obj == null)
        //        return false;

        //    if (_OLf != o._OLf)
        //        return false;

        //    if (_NLf != o._NLf)
        //        return false;

        //    return (_Changed == o._Changed);
        //}

        //public override int GetHashCode()
        //{
        //    return _Changed.GetHashCode() ^  _OLf.GetHashCode();
        //}

        internal ObjectStateChangeArgs(IObjectState changed, ObjectState OLF, ObjectState NLF)
        {
            _OLf = OLF;
            _NLf = NLF;
            _Changed = changed;
        }