Beispiel #1
0
        public virtual object Invoke(string method, params object[] args)
        {
            WebRequest request = GetWebRequest(new Uri(Url));
            request.Method = "POST";

            using (Stream stream = request.GetRequestStream())
            using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
            {
                JsonObject call = new JsonObject();
                call["id"] = ++_id;
                call["method"] = method;
                call["params"] = args;
                call.Export(new JsonTextWriter(writer));
            }

            using (WebResponse response = GetWebResponse(request))
            using (Stream stream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                JsonObject answer = new JsonObject();
                answer.Import(new JsonTextReader(reader));

                object errorObject = answer["error"];

                if (errorObject != null)
                    OnError(errorObject);

                return answer["result"];
            }
        }
Beispiel #2
0
 /// <summary>
 /// 输入string
 /// 输出json
 /// </summary>
 /// <param name="strJsonText">要输出的json串</param>
 public static void writeStringtoJson(String strJsonText)
 {
     JsonReader reader = new JsonTextReader(new StringReader(strJsonText));
     JsonObject jsonObj = new JsonObject();
     jsonObj.Import(reader);
     HttpContext.Current.Response.Write(jsonObj);
     HttpContext.Current.Response.End();
 }
Beispiel #3
0
 public void ContentsClearedBeforeImporting()
 {
     JsonObject o = new JsonObject();
     o.Put("foo", "bar");
     Assert.AreEqual(1, o.Count);
     o.Import(new JsonTextReader(new StringReader("{}")));
     Assert.AreEqual(0, o.Count);
 }
        public void ContentsClearedBeforeImporting()
        {
            var o = new JsonObject();

            o.Put("foo", "bar");
            Assert.AreEqual(1, o.Count);
            o.Import(new JsonTextReader(new StringReader("{}")));
            Assert.AreEqual(0, o.Count);
        }
        public virtual object Invoke(string method, params object[] args)
        {
            string action = method + "(" + Util.ArrayToStringGeneric(args, ", ") + ") ";
            //Console.WriteLine(action);

            return Util.RetryAction<object>(() =>
                {
                    WebRequest request = GetWebRequest(new Uri(Url));
                    request.Method = "POST";
                    request.Timeout = 45000;

                    using (Stream stream = request.GetRequestStream())
                    using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                    {
                        JsonObject call = new JsonObject();
                        call["id"] = ++_id;
                        call["method"] = method;
                        call["params"] = args;
                        call.Export(new JsonTextWriter(writer));
                    }

                    using (HttpWebResponse response = (HttpWebResponse)GetWebResponse(request))
                    using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        JsonObject answer = new JsonObject();

                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            throw new Exception(action + "got Bad HTTP response: " + response.StatusCode);
                        }
                        else
                        {
                            answer.Import(new JsonTextReader(reader));
                        }

                        object errorObject = answer["error"];

                        if (errorObject != null)
                            OnError(errorObject);

                        return answer["result"];
                    }
                }, action, 20, 100); // retry with delay

            throw new Exception(action + "failed, too many retries");
        }
        public void Import()
        {
            var article = new JsonObject();

            article.Import(new JsonTextReader(new StringReader(@"
                /* Article */ {
                    Title : 'Introduction to JSON',
                    Rating : 2,
                    Abstract : null,
                    Author : {
                        Name : 'John Doe',
                        'E-Mail Address' : '*****@*****.**'
                    },
                    References : [
                        { Title : 'JSON RPC', Link : 'http://www.json-rpc.org/' }
                    ]
                }")));

            Assert.IsNotNull(article);
            Assert.AreEqual(5, article.Count);
            Assert.AreEqual("Introduction to JSON", article["Title"]);
            Assert.AreEqual(2, (int)(JsonNumber)article["Rating"]);
            Assert.AreEqual(null, article["Abstract"]);

            var author = (IDictionary)article["Author"];

            Assert.IsNotNull(author);
            Assert.AreEqual(2, author.Count);
            Assert.AreEqual("John Doe", author["Name"]);
            Assert.AreEqual("*****@*****.**", author["E-Mail Address"]);

            var references = (JsonArray)article["References"];

            Assert.IsNotNull(references);
            Assert.AreEqual(1, references.Length);

            var reference = (IDictionary)references[0];

            Assert.IsNotNull(reference);
            Assert.AreEqual(2, reference.Count);
            Assert.AreEqual("JSON RPC", reference["Title"]);
            Assert.AreEqual("http://www.json-rpc.org/", reference["Link"]);
        }
        /// <summary>
        /// ������еĸ�������
        /// </summary>
        public static void AddGridViewPropoter(GridView gridList, string josinString)
        {
            if (gridList.Rows.Count > 0)
            {
                Jayrock.Json.JsonReader reader = new Jayrock.Json.JsonTextReader(new System.IO.StringReader(@josinString));
                JsonObject jsonObj = new JsonObject();
                jsonObj.Import(reader);

                JsonArray rowPro = (JsonArray)jsonObj["RowPro"];
                JsonArray colPro = (JsonArray)jsonObj["ColPro"];

                JsonObject item = null;

                for (int i = 0; i < gridList.Rows.Count; i++)
                {

                    gridList.Rows[i].Attributes.Add("id", "div" + i);

                    //���������
                    item = rowPro.GetObject(0);
                    for (int k = 0; k < item.GetNamesArray().Count; k++)
                    {
                        string n = item.GetNamesArray()[k].ToString();
                        gridList.Rows[i].Attributes.Add(n, string.Format(item[n].ToString(),i));
                    }

                    for (int j = 0; j < gridList.Rows[i].Cells.Count; j++)
                    {
                        gridList.Rows[i].Cells[j].Attributes.Add("id", "div_" + i + "_" + j);

                        //��ӵ�Ԫ������
                        item = null;
                        item = colPro.GetObject(0);
                        for (int k = 0; k < item.GetNamesArray().Count; k++)
                        {
                            string n = item.GetNamesArray()[k].ToString();
                            gridList.Rows[i].Cells[j].Attributes.Add(n,string.Format(item[n].ToString(),i,j));
                        }
                    }
                }

            }
        }
Beispiel #8
0
        public void Import()
        {
            JsonObject article = new JsonObject();

            article.Import(new JsonTextReader(new StringReader(@"
                /* Article */ {
                    Title : 'Introduction to JSON',
                    Rating : 2,
                    Abstract : null,
                    Author : {
                        Name : 'John Doe',
                        'E-Mail Address' : '*****@*****.**'
                    },
                    References : [
                        { Title : 'JSON RPC', Link : 'http://www.json-rpc.org/' }
                    ]
                }")));

            Assert.IsNotNull(article);
            Assert.AreEqual(5, article.Count);
            Assert.AreEqual("Introduction to JSON", article["Title"]);
            Assert.AreEqual(2, (int) (JsonNumber) article["Rating"]);
            Assert.AreEqual(null, article["Abstract"]);

            IDictionary author = (IDictionary) article["Author"];
            Assert.IsNotNull(author);
            Assert.AreEqual(2, author.Count);
            Assert.AreEqual("John Doe", author["Name"]);
            Assert.AreEqual("*****@*****.**", author["E-Mail Address"]);

            JsonArray references = (JsonArray) article["References"];
            Assert.IsNotNull(references);
            Assert.AreEqual(1, references.Length);

            IDictionary reference = (IDictionary) references[0];
            Assert.IsNotNull(reference);
            Assert.AreEqual(2, reference.Count);
            Assert.AreEqual("JSON RPC", reference["Title"]);
            Assert.AreEqual("http://www.json-rpc.org/", reference["Link"]);
        }
Beispiel #9
0
 public void CannotUseNullReaderWithImport()
 {
     IJsonImportable o = new JsonObject();
     o.Import(new ImportContext(), null);
 }
Beispiel #10
0
 public void CannotUseNullContextWithImport()
 {
     IJsonImportable o = new JsonObject();
     o.Import(null, (new JsonRecorder()).CreatePlayer());
 }
        /// <summary>
        /// Gets the FriendConnect user corresponding to fcAuth or userId. If fcAuth
        /// is set, then it will use FriendConnect API calls to retrieve the FriendConnect
        /// user, otherwise it will fetch the user from database using userId, and
        /// then use its fcid along with 2-legged OAuth to fetch the FriendConnect
        /// user.
        /// </summary>
        /// <param name="fcAuthToken">The FriendConnect token.</param>
        /// <param name="userId">The local user id.</param>
        /// <param name="addIfMissing">Should a new user be created in local database if
        ///  there is no such user in the database? Default value of this param is True.
        ///  </param>
        /// <returns>The FriendConnect user.</returns>
        public static User getFCUser(string fcAuthToken, string userId, bool addIfMissing)
        {
            HttpProvider httpProvider =
                (HttpProvider)ObjectFactory.getInstance(StringConstants.HttpProvider);

            string url = "";
            // try to retrieve the user using fcAuth
            if (!string.IsNullOrEmpty(fcAuthToken))
            {
                url = string.Format("{0}/people/{1}/@self?fcauth={2}",
                    ApplicationConfiguration.FriendConnectApiUrl, userId, fcAuthToken);
            }
            else
            {
                // use 2 legged OAuth to fetch the user.
                url = string.Format("{0}/people/{1}/@self",
                    ApplicationConfiguration.FriendConnectApiUrl, userId);

                url = OAuthUtil.signRequest(url, ApplicationConfiguration.FriendConnectOAuthKey,
                    ApplicationConfiguration.FriendConnectOAuthSecret, "",
                    ApplicationConfiguration.FriendConnectSiteId, new Hashtable());
            }

            string response = httpProvider.send(url, "GET", "", null);
            User retVal = null;

            if (!string.IsNullOrEmpty(response))
            {
                JsonTextReader reader = new JsonTextReader(new StringReader(response));
                JsonObject data = new JsonObject();
                data.Import(reader);

                retVal = new User();
                JsonObject entry = (JsonObject)data["entry"];
                retVal.FCId = entry["id"].ToString();
                retVal.Image = entry["thumbnailUrl"].ToString();
                retVal.Name = entry["displayName"].ToString();

                UserDBContext UserDBContext = new Models.UserDBContext();
                string entryId = entry["id"].ToString();
                var users = UserDBContext.Users.Where(u => u.FCId == entryId);
                if (users.Count() == 0)
                {
                    // this is a friendconnect user who isn't part of our site. Add him
                    // as a new user. Store only the fcid.
                    if (addIfMissing == true)
                    {
                        User newUser = new User();
                        newUser.FCId = entry["id"].ToString();
                        UserDBContext.Users.Add(newUser);
                        UserDBContext.SaveChanges();
                        retVal.Id = UserDBContext.Users.Where(u=> u.FCId ==  newUser.FCId).First().Id;
                    }
                }
                else
                {
                    var localUser = users.First();
                    // this is a registered user, but he has signed up as a FC user. We
                    // could identify him as a local user, or a FC user, based on the
                    // context.
                    retVal.Id = localUser.Id;
                    retVal.Password = localUser.Password;
                }
            }
            return retVal;
        }
        /// <summary>
        /// Gets the list of viewer friends.
        /// </summary>
        /// <param name="fcAuthToken">The FriendConnect token.</param>
        /// <param name="start">Start index for friend list.</param>
        /// <param name="count">Number of friends to be retrieved.</param>
        /// <returns>An array holding startIndex, count, totalResults, and the
        /// list of friends.</returns>
        public static Hashtable getViewerFriends(string fcAuthToken, int start, int count)
        {
            HttpProvider httpProvider =
                (HttpProvider)ObjectFactory.getInstance(StringConstants.HttpProvider);
            string url = string.Format("{0}/people/@viewer/@friends?fcauth={1}&startIndex={2}" +
              "&count={3}", ApplicationConfiguration.FriendConnectApiUrl, fcAuthToken, start, count);

            string response = httpProvider.send(url, "GET", "", null);

            Hashtable retVal = new Hashtable();

            if (!string.IsNullOrEmpty(response))
            {
                JsonTextReader reader = new JsonTextReader(new StringReader(response));
                JsonObject data = new JsonObject();
                data.Import(reader);

                retVal["startIndex"] = int.Parse(data["startIndex"].ToString());
                retVal["count"] = ((JsonArray)data["entry"]).Length;
                retVal["totalResults"] = int.Parse(data["totalResults"].ToString());

                List<User> users = new List<User>();
                JsonArray entry = (JsonArray)data["entry"];
                for (int i = 0; i < (int)retVal["count"]; i++)
                {
                    JsonObject jUser = (JsonObject)entry[i];
                    User user = new User();
                    user.FCId = jUser["id"].ToString();
                    user.Image = jUser["thumbnailUrl"].ToString();
                    user.Name = jUser["displayName"].ToString();

                    {
                        UserDBContext UserDBContext = new Models.UserDBContext();
                        var localUsers = UserDBContext.Users.Where(u => u.FCId == user.FCId);
                        if (localUsers.Count() > 0)
                        {
                            // return as a friend only if this user is registered on our
                            // site as well.
                            user.Id = localUsers.First().Id;
                        }
                        else
                        {
                            // our database is out of sync with the fc database. This should
                            // not happen normally, but syncing itself is simple.

                            User newUser = new User();
                            newUser.FCId = jUser["id"].ToString();
                            UserDBContext.Users.Add(newUser);
                            UserDBContext.SaveChanges();
                            user.Id = UserDBContext.Users.Where(u => u.FCId == newUser.FCId).First().Id;
                        }
                    }

                    {
                        UserDBContext UserDBContext = new Models.UserDBContext();
                        var localUsers = UserDBContext.Users.Where(u => u.FCId == user.FCId);

                        if (localUsers.Count() > 0)
                        {
                            // return as a friend only if this user is registered on our
                            // site as well.
                            user.Id = localUsers.First().Id;
                        }
                        else
                        {
                            // our database is out of sync with the fc database. This should
                            // not happen normally, but syncing itself is simple.

                            User newUser = new User();
                            newUser.FCId = jUser["id"].ToString();

                            UserDBContext.Users.Add(newUser);
                            UserDBContext.SaveChanges();
                            user.Id = UserDBContext.Users.Where(u => u.FCId == newUser.FCId).First().Id;
                        }
                        users.Add(user);
                    }
                }
                retVal["friends"] = users.ToArray();
            }
            return retVal;
        }
Beispiel #13
0
        public void CannotUseNullContextWithImport()
        {
            IJsonImportable o = new JsonObject();

            o.Import(null, (new JsonRecorder()).CreatePlayer());
        }
Beispiel #14
0
        public void CannotUseNullReaderWithImport()
        {
            IJsonImportable o = new JsonObject();

            o.Import(new ImportContext(), null);
        }