Пример #1
0
        public Task <AVUser> GetAsync(CancellationToken cancellationToken)
        {
            AVUser cachedCurrent;

            lock (mutex) {
                cachedCurrent = CurrentUser;
            }

            if (cachedCurrent != null)
            {
                return(Task <AVUser> .FromResult(cachedCurrent));
            }

            return(taskQueue.Enqueue(toAwait => {
                return toAwait.ContinueWith(t => {
                    object temp;
                    AVClient.ApplicationSettings.TryGetValue("CurrentUser", out temp);
                    var userDataString = temp as string;
                    AVUser user = null;
                    if (userDataString != null)
                    {
                        var userData = Json.Parse(userDataString) as IDictionary <string, object>;
                        user = AVObject.CreateWithoutData <AVUser>(null);
                        user.HandleFetchResult(AVObjectCoder.Instance.Decode(userData, AVDecoder.Instance));
                    }

                    CurrentUser = user;
                    return user;
                });
            }, cancellationToken));
        }
        public Task <AVInstallation> GetAsync(CancellationToken cancellationToken)
        {
            AVInstallation cachedCurrent;

            cachedCurrent = CurrentInstallation;

            if (cachedCurrent != null)
            {
                return(Task <AVInstallation> .FromResult(cachedCurrent));
            }

            return(taskQueue.Enqueue(toAwait => {
                return toAwait.ContinueWith(t => {
                    object temp;
                    AVClient.ApplicationSettings.TryGetValue("CurrentInstallation", out temp);
                    var installationDataString = temp as string;
                    AVInstallation installation = null;
                    if (installationDataString != null)
                    {
                        var installationData = AVClient.DeserializeJsonString(installationDataString);
                        installation = AVObject.CreateWithoutData <AVInstallation>(null);
                        installation.HandleFetchResult(AVObjectCoder.Instance.Decode(installationData, AVDecoder.Instance));
                    }
                    else
                    {
                        installation = AVObject.Create <AVInstallation>();
                        installation.SetIfDifferent("installationId", installationIdController.Get().ToString());
                    }

                    CurrentInstallation = installation;
                    return installation;
                });
            }, cancellationToken));
        }
        public async void SaveFile(byte[] data, string name)
        {
            AVFile file = new AVFile(name, data, new Dictionary <string, object>()
            {
                { "author", "AVOSCloud" }
            });


            AVObject photo = AVObject.CreateWithoutData("photo", "55acdce0e4b044ac283609af");
            await photo.SaveAsync().ContinueWith(t =>
            {
                // 保存成功之后,修改一个已经在服务端生效的数据,这里我们修改age
                // LeanCloud 只会针对指定的属性进行覆盖操作,本例中的name不会被修改
                photo["ss"] = file;
                photo.SaveAsync();
            });


            /*await photo.SaveAsync().ContinueWith(t =>
             * {
             *  // 保存成功之后,修改一个已经在服务端生效的数据,这里我们修改age
             *  // LeanCloud 只会针对指定的属性进行覆盖操作,本例中的name不会被修改\
             *
             *  photo["ss"] = file;
             *  photo.SaveAsync();
             *
             *  MessageBox.Show("ok");
             * });*/
        }
Пример #4
0
        public Task TestCurrentSessionToken()
        {
            var storageController = new Mock <IStorageController>();
            var mockedStorage     = new Mock <IStorageDictionary <string, object> >();
            var controller        = new AVCurrentUserController(storageController.Object);

            storageController.Setup(c => c.LoadAsync()).Returns(Task.FromResult(mockedStorage.Object));

            return(controller.GetCurrentSessionTokenAsync(CancellationToken.None).OnSuccess(t => {
                Assert.IsNull(t.Result);

                // We should probably mock this.
                var userState = new MutableObjectState {
                    ServerData = new Dictionary <string, object>()
                    {
                        { "sessionToken", "randomString" }
                    }
                };
                var user = AVObject.CreateWithoutData <AVUser>(null);
                user.HandleFetchResult(userState);

                return controller.SetAsync(user, CancellationToken.None);
            }).Unwrap()
                   .OnSuccess(_ => controller.GetCurrentSessionTokenAsync(CancellationToken.None)).Unwrap()
                   .OnSuccess(t => {
                Assert.AreEqual("randomString", t.Result);
            }));
        }
Пример #5
0
        public object Encode()
        {
            var adds = this.adds
                       .Select(id => PointerOrLocalIdEncoder.Instance.Encode(
                                   AVObject.CreateWithoutData(targetClassName, id)))
                       .ToList();
            var removes = this.removes
                          .Select(id => PointerOrLocalIdEncoder.Instance.Encode(
                                      AVObject.CreateWithoutData(targetClassName, id)))
                          .ToList();
            var addDict = adds.Count == 0 ? null : new Dictionary <string, object> {
                { "__op", "AddRelation" },
                { "objects", adds }
            };
            var removeDict = removes.Count == 0 ? null : new Dictionary <string, object> {
                { "__op", "RemoveRelation" },
                { "objects", removes }
            };

            if (addDict != null && removeDict != null)
            {
                return(new Dictionary <string, object> {
                    { "__op", "Batch" },
                    { "ops", new[] { addDict, removeDict } }
                });
            }
            return(addDict ?? removeDict);
        }
Пример #6
0
 protected virtual object DecodePointer(string className, string objectId)
 {
     if (className == "_File")
     {
         return(AVFile.CreateWithoutData(objectId));
     }
     return(AVObject.CreateWithoutData(className, objectId));
 }
Пример #7
0
 /// <summary>
 /// Logs in a user with a username and password. On success, this saves the session to disk so you
 /// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
 /// </summary>
 /// <param name="sessionToken">The session token to authorize with</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The user if authorization was successful</returns>
 public static Task <AVUser> BecomeAsync(string sessionToken, CancellationToken cancellationToken)
 {
     return(UserController.GetUserAsync(sessionToken, cancellationToken).OnSuccess(t => {
         var user = (AVUser)AVObject.CreateWithoutData <AVUser>(null);
         user.HandleFetchResult(t.Result);
         return SaveCurrentUserAsync(user).OnSuccess(_ => user);
     }).Unwrap());
 }
Пример #8
0
        internal static Task <AVUser> LoginWithParametersAsync(Dictionary <string, object> strs, CancellationToken cancellationToken)
        {
            AVUser avUser = AVObject.CreateWithoutData <AVUser>(null);

            return(UserController.LogInWithParametersAsync("login", strs, cancellationToken).OnSuccess(t => {
                var user = (AVUser)AVObject.CreateWithoutData <AVUser>(null);
                user.HandleFetchResult(t.Result);
                return SaveCurrentUserAsync(user).OnSuccess(_ => user);
            }).Unwrap());
        }
Пример #9
0
 /// <summary>
 /// Logs in a user with a username and password. On success, this saves the session to disk so you
 /// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
 /// </summary>
 /// <param name="username">The username to httpDebugLog in with.</param>
 /// <param name="password">The password to httpDebugLog in with.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The newly logged-in user.</returns>
 public static Task <AVUser> LogInAsync(string username,
                                        string password,
                                        CancellationToken cancellationToken)
 {
     return(UserController.LogInAsync(username, password, cancellationToken).OnSuccess(t => {
         var user = (AVUser)AVObject.CreateWithoutData <AVUser>(null);
         user.HandleFetchResult(t.Result);
         return SaveCurrentUserAsync(user).OnSuccess(_ => user);
     }).Unwrap());
 }
Пример #10
0
 /// <summary>
 /// 上云传温湿度
 /// </summary>
 public async void saveToCloud(string name, string data)
 {
     AVObject Temperature = AVObject.CreateWithoutData("Temperature", "5575072de4b0f22726a105b0");
     await Temperature.SaveAsync().ContinueWith(t =>
     {
         // 保存成功之后,修改一个已经在服务端生效的数据,这里我们修改age
         // LeanCloud 只会针对指定的属性进行覆盖操作,本例中的name不会被修改
         Temperature["temperature"] = data;
         Temperature.SaveAsync();
     });
 }
Пример #11
0
 public async void saveToCloud2(string name, string data)
 {
     AVObject Humidity = AVObject.CreateWithoutData("Humidity", "5575072de4b0f22726a105af");
     await Humidity.SaveAsync().ContinueWith(t =>
     {
         // 保存成功之后,修改一个已经在服务端生效的数据,这里我们修改age
         // LeanCloud 只会针对指定的属性进行覆盖操作,本例中的name不会被修改
         Humidity["humidity"] = data;
         Humidity.SaveAsync();
     });
 }
Пример #12
0
        /// <summary>
        /// 删除
        /// </summary>
        public async void DeleteObjWithId()
        {
            AVObject character = AVObject.CreateWithoutData("Sport", "5b44644aee920a003b2eb726");
            await character.DeleteAsync().ContinueWith(t =>
            {
                Console.WriteLine("Delete:ID:" + t.Id);
                Console.WriteLine("character:ID:" + character.ObjectId);

                character.Remove("grage");
                character.SaveAsync();
            });
        }
Пример #13
0
        /// <summary>
        /// 删除属性
        /// </summary>
        public async void DeletePropertiesWithId()
        {
            AVObject character = AVObject.CreateWithoutData("Sport", "5b446160fe88c20035fd9dcc");
            await character.FetchAsync().ContinueWith(t =>
            {
                Console.WriteLine("FetchAsync:ID:" + t.Id);
                Console.WriteLine("character:ID:" + character.ObjectId);

                character.Remove("grade");
                character.SaveAsync();
            });
        }
Пример #14
0
        internal static Task <string> UpgradeToRevocableSessionAsync(string sessionToken, CancellationToken cancellationToken)
        {
            if (sessionToken == null || IsRevocableSessionToken(sessionToken))
            {
                return(Task <string> .FromResult(sessionToken));
            }

            return(SessionController.UpgradeToRevocableSessionAsync(sessionToken, cancellationToken).OnSuccess(t => {
                var session = (AVSession)AVObject.CreateWithoutData <AVSession>(null);
                session.HandleFetchResult(t.Result);
                return session.SessionToken;
            }));
        }
Пример #15
0
        /// <summary>
        /// 手机号一键登录
        /// </summary>
        /// <param name="mobilePhoneNumber">手机号</param>
        /// <param name="smsCode">短信验证码</param>
        /// <returns></returns>
        public static Task <AVUser> SignUpOrLoginByMobilePhoneAsync(string mobilePhoneNumber, string smsCode, CancellationToken cancellationToken)
        {
            Dictionary <string, object> strs = new Dictionary <string, object>()
            {
                { "mobilePhoneNumber", mobilePhoneNumber },
                { "smsCode", smsCode }
            };

            return(UserController.LogInWithParametersAsync("/usersByMobilePhone", strs, cancellationToken).OnSuccess(t => {
                var user = (AVUser)AVObject.CreateWithoutData <AVUser>(null);
                user.HandleFetchResult(t.Result);
                return SaveCurrentUserAsync(user).OnSuccess(_ => user);
            }).Unwrap());
        }
Пример #16
0
        public void TestRelationQuery()
        {
            AVObject parent = AVObject.CreateWithoutData("Foo", "abcxyz");

            AVRelation <AVObject> relation = parent.GetRelation <AVObject>("child");
            AVQuery <AVObject>    query    = relation.Query;

            // Client side, the query will appear to be for the wrong class.
            // When the server recieves it, the class name will be redirected using the 'redirectClassNameForKey' option.
            Assert.AreEqual("Foo", query.GetClassName());

            IDictionary <string, object> encoded = query.BuildParameters();

            Assert.AreEqual("child", encoded["redirectClassNameForKey"]);
        }
Пример #17
0
 public async void GetObjWithId()
 {
     AVObject character = AVObject.CreateWithoutData("Sport", "5b4464a49f5454003b178628");
     await character.FetchAsync().ContinueWith(t =>
     {
         if (character.IsKeyDirty("totalTime"))
         {
             character.FetchAsync();
         }
         Console.WriteLine("name:" + character.Get <string>("name"));
         Console.WriteLine("totalTime:" + character.Get <double>("totalTime")); //此处用int取小数的话,不会报错,会自动被转化为int
         Console.WriteLine("grade:" + character.Get <string>("grade"));
         //if(character.is)
         // Console.WriteLine("noExist:" + character.Get<string>("noExist")); //报异常
     });
 }
Пример #18
0
        public void TestParseObjectCreate()
        {
            AVObject obj = AVObject.Create("Corgi");

            Assert.AreEqual("Corgi", obj.ClassName);
            Assert.Null(obj.CreatedAt);
            Assert.True(obj.IsDataAvailable);
            Assert.True(obj.IsDirty);

            AVObject obj2 = AVObject.CreateWithoutData("Corgi", "waGiManPutr4Pet1r");

            Assert.AreEqual("Corgi", obj2.ClassName);
            Assert.AreEqual("waGiManPutr4Pet1r", obj2.ObjectId);
            Assert.Null(obj2.CreatedAt);
            Assert.False(obj2.IsDataAvailable);
            Assert.False(obj2.IsDirty);
        }
Пример #19
0
        public void TestParseObjectCreateWithGeneric()
        {
            AVObject.RegisterSubclass <SubClass>();

            AVObject obj = AVObject.Create <SubClass>();

            Assert.AreEqual("SubClass", obj.ClassName);
            Assert.Null(obj.CreatedAt);
            Assert.True(obj.IsDataAvailable);
            Assert.True(obj.IsDirty);

            AVObject obj2 = AVObject.CreateWithoutData <SubClass>("waGiManPutr4Pet1r");

            Assert.AreEqual("SubClass", obj2.ClassName);
            Assert.AreEqual("waGiManPutr4Pet1r", obj2.ObjectId);
            Assert.Null(obj2.CreatedAt);
            Assert.False(obj2.IsDataAvailable);
            Assert.False(obj2.IsDirty);
        }
Пример #20
0
        /// <summary>
        /// Gets the current <see cref="AVSession"/> object related to the current user.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token</param>
        public static Task <AVSession> GetCurrentSessionAsync(CancellationToken cancellationToken)
        {
            return(AVUser.GetCurrentUserAsync().OnSuccess(t1 => {
                AVUser user = t1.Result;
                if (user == null)
                {
                    return Task <AVSession> .FromResult((AVSession)null);
                }

                string sessionToken = user.SessionToken;
                if (sessionToken == null)
                {
                    return Task <AVSession> .FromResult((AVSession)null);
                }

                return SessionController.GetSessionAsync(sessionToken, cancellationToken).OnSuccess(t => {
                    AVSession session = (AVSession)AVObject.CreateWithoutData <AVSession>(null);
                    session.HandleFetchResult(t.Result);
                    return session;
                });
            }).Unwrap());
        }
Пример #21
0
        internal static Task <AVUser> LogInWithAsync(string authType,
                                                     IDictionary <string, object> data,
                                                     CancellationToken cancellationToken)
        {
            AVUser user = null;

            return(UserController.LogInAsync(authType, data, cancellationToken).OnSuccess(t => {
                user = (AVUser)AVObject.CreateWithoutData <AVUser>(null);
                user.HandleFetchResult(t.Result);

                lock (user.mutex) {
                    if (user.AuthData == null)
                    {
                        user.AuthData = new Dictionary <string, IDictionary <string, object> >();
                    }
                    user.AuthData[authType] = data;
                    user.SynchronizeAllAuthData();
                }

                return SaveCurrentUserAsync(user);
            }).Unwrap().OnSuccess(t => user));
        }
Пример #22
0
        private async void FromShareCode_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new InputDialog()
            {
                Title       = "请输入在线分享码",
                Placeholder = "在线分享码"
            };

            if ((await dialog.ShowAsyncQueue()) == ContentDialogResult.Primary)
            {
                try
                {
                    var code = dialog.Result;

                    if (code.Contains(":"))
                    {
                        code = code.Substring(code.IndexOf(":") + 1).Trim();
                    }

                    var content = AVObject.CreateWithoutData("TimeTable", code);
                    await content.FetchAsync();

                    var tableCourses = JsonConvert.DeserializeObject <TableCourses>(Convert.ToString(content["Content"]));
                    Models.Add(await TimeTableHelper.GenerateTimeTableModel(tableCourses));

                    app.TimeTables.Add(tableCourses);
                    SaveTimeTables();
                }
                catch (Exception err)
                {
                    var msgDialog = new CommonDialog("分享码格式错误:\n" + err.Message)
                    {
                        Title = "错误",
                    };
                    await msgDialog.ShowAsyncQueue();
                }
            }
        }
Пример #23
0
        public Task TestObjectFetchIncludeKeys()
        {
            var todo = new AVObject("Todo");

            todo["title"] = "test todo";

            var todoFolder = new AVObject("TodoFolder");

            todoFolder["name"] = "test todo folder";

            todo["folder"] = todoFolder;

            return(todo.SaveAsync().ContinueWith(t =>
            {
                var localTodo = AVObject.CreateWithoutData("Todo", todo.ObjectId);
                return localTodo.FetchAsync(new string[] { "folder" });
            }).Unwrap().ContinueWith(s =>
            {
                var localTodoFolder = s.Result.Get <AVObject>("folder");
                Assert.IsNotNull(localTodoFolder["name"]);
                return Task.FromResult(0);
            }));
        }
        public VideoMessage()
        {
            InitializeComponent();
            photo = AVObject.CreateWithoutData("photo", "557283c3e4b0cfb2055d389b");
            if (MultimediaUtil.VideoInputNames.Length > 0)
            {
                vce.VideoCaptureSource = MultimediaUtil.VideoInputNames[0];
            }
            else
            {
                MessageBox.Show("未检测到任何可用摄像头!");
            }


            dTimer.Tick    += new EventHandler(dTimer_Tick);
            dTimer.Interval = new TimeSpan(0, 0, 3);

            dTimer.Start();


            // Button_Click(this,e);
            // Cream();
        }
Пример #25
0
        public static void UseLambda(this Cloud cloud)
        {
            // case 1. use EngineObjectHookContext
            cloud.UseHook("Todo", EngineHookType.BeforeSave, (context) =>
            {
                var todo = context.TheObject;
                var by   = context.By;
                return(Task.FromResult(context.TheObject));
            });

            cloud.BeforeSave("Todo", (context) =>
            {
                return(Task.FromResult(context.TheObject));
            });

            // case 2. use TheObject
            cloud.UseHook("Todo", EngineHookType.BeforeSave, (AVObject todoObj) =>
            {
                return(Task.FromResult(todoObj));
            });

            cloud.BeforeSave("Todo", (AVObject todoObj) =>
            {
                return(Task.FromResult(todoObj));
            });

            // case 3. use TheObject and user
            cloud.UseHook("Todo", EngineHookType.BeforeSave, (AVObject todoObj, AVUser by) =>
            {
                return(Task.FromResult(todoObj));
            });

            cloud.BeforeSave("Todo", (AVObject todoObj, AVUser by) =>
            {
                return(Task.FromResult(todoObj));
            });

            // case 3. use sub-class
            AVObject.RegisterSubclass <Todo>();

            cloud.UseHook <Todo>(EngineHookType.BeforeSave, (Todo theTodoObj) =>
            {
                // theTodoObj is an Todo instance.
                return(Task.FromResult(theTodoObj));
            });

            cloud.UseHook <Todo>(EngineHookType.BeforeSave, (Todo theTodoObj, AVUser by) =>
            {
                return(Task.FromResult(theTodoObj));
            });

            cloud.BeforeSave <Todo>((todo) =>
            {
                // todo is an Todo instance.
                return(Task.FromResult(todo));
            });

            cloud.BeforeSave <Todo>((todo, by) =>
            {
                // todo is an Todo instance.
                return(Task.FromResult(todo));
            });

            cloud.BeforeUpdate("Todo", review =>
            {
                var updatedKeys = review.GetUpdatedKeys();
                if (updatedKeys.Contains("comment"))
                {
                    var comment = review.Get <string>("comment");
                    if (comment.Length > 140)
                    {
                        throw new EngineException(400, "comment 长度不得超过 140 字符");
                    }
                }
                return(Task.FromResult(true));
            });

            EngineHookDelegateSynchronous afterPostHook = (post) =>
            {
            };

            cloud.AfterSave("Post", (EngineObjectHookDeltegateSynchronous)(async post =>
            {
                // 直接修改并保存对象不会再次触发 after update hook 函数
                post["foo"] = "bar";
                await post.SaveAsync();
                // 如果有 FetchAsync 操作,则需要在新获得的对象上调用相关的 disable 方法
                // 来确保不会再次触发 Hook 函数
                await post.FetchAsync();
                post.DisableAfterHook();
                post["foo"] = "bar";

                // 如果是其他方式构建对象,则需要在新构建的对象上调用相关的 disable 方法
                // 来确保不会再次触发 Hook 函数
                post = AVObject.CreateWithoutData <AVObject>(post.ObjectId);
                post.DisableAfterHook();
                await post.SaveAsync();
            }));
        }
Пример #26
0
        public object Decode(object data)
        {
            if (data == null)
            {
                return(null);
            }

            var dict = data as IDictionary <string, object>;

            if (dict != null)
            {
                if (dict.ContainsKey("__op"))
                {
                    return(AVFieldOperations.Decode(dict));
                }

                object type;
                dict.TryGetValue("__type", out type);
                var typeString = type as string;

                if (typeString == null)
                {
                    var newDict = new Dictionary <string, object>();
                    foreach (var pair in dict)
                    {
                        newDict[pair.Key] = Decode(pair.Value);
                    }
                    return(newDict);
                }

                if (typeString == "Date")
                {
                    return(AVDate(dict["iso"] as string));
                }

                if (typeString == "Bytes")
                {
                    return(Convert.FromBase64String(dict["base64"] as string));
                }

                if (typeString == "Pointer")
                {
                    return(DecodePointer(dict["className"] as string, dict["objectId"] as string));
                }

                if (typeString == "File")
                {
                    return(new AVFile(dict["name"] as string, new Uri(dict["url"] as string)));
                }

                if (typeString == "GeoPoint")
                {
                    return(new AVGeoPoint((double)AVClient.ConvertTo <double>(dict["latitude"]),
                                          (double)AVClient.ConvertTo <double>(dict["longitude"])));
                }

                if (typeString == "Object")
                {
                    var output = AVObject.CreateWithoutData(dict["className"] as string, null);
                    output.HandleFetchResult(AVObjectCoder.Instance.Decode(dict, this));
                    return(output);
                }

                if (typeString == "Relation")
                {
                    return(AVRelationBase.CreateRelation(null, null, dict["className"] as string));
                }

                var converted = new Dictionary <string, object>();
                foreach (var pair in dict)
                {
                    converted[pair.Key] = Decode(pair.Value);
                }
                return(converted);
            }

            var list = data as IList <object>;

            if (list != null)
            {
                return((from item in list
                        select Decode(item)).ToList());
            }

            return(data);
        }