Esempio n. 1
0
 // public static Dictionary<string, Dictionary<string, string>> userLocation=new Dictionary<string,Dictionary<string,string>>();
 /// <summary>
 /// 设置自动上发的地址
 /// ygh 2014/3/12
 /// </summary>
 /// <param name="openid"></param>
 /// <param name="location"></param>
 public static void setLocation(string openid,string location)
 {
     JavaScriptSerializer a = new JavaScriptSerializer();
     Dictionary<string, object> o = (Dictionary<string, object>)a.DeserializeObject(location);
     WEC_WZ_LOCATION userLocation = new WEC_WZ_LOCATION();
     userLocation.OPENID = openid;
     userLocation.LATITUDE=(string)o["Latitude"];
     userLocation.LONGITUDE=(string)o["Longitude"];
     userLocation.PRECISION=(string)o["Precision"];
     userLocation.ADDTIME = DateTime.Now;
     BLLTable<WEC_WZ_LOCATION>.Insert(userLocation,WEC_WZ_LOCATION.Attribute.ID);
 }
Esempio n. 2
0
    /// <summary>
    /// 传入appid和secret获取accesstoken
    /// </summary>
    /// <param name="appid"></param>
    /// <param name="secret"></param>
    /// <returns></returns>
    public static string getAccessToken(string appid,string secret)
    {
        string param = "";
        string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        StreamWriter sw = new StreamWriter(@"c:\e.txt");
        sw.Write(""+url);
        sw.Close();
        string content=httpForm(param,url,"GET");

        JavaScriptSerializer a = new JavaScriptSerializer();
        Dictionary<string, object> o = (Dictionary<string, object>)a.DeserializeObject(content);
        string access_token = (string)o["access_token"];
        return access_token;
    }
Esempio n. 3
0
    static void Main()
    {
        var people = new Dictionary<string, object> {{"1", "John"}, {"2", "Susan"}};
        var serializer = new JavaScriptSerializer();

        var json = serializer.Serialize(people);
        Console.WriteLine(json);

        var deserialized = serializer.Deserialize<Dictionary<string, object>>(json);
        Console.WriteLine(deserialized["2"]);

        var jsonObject = serializer.DeserializeObject(@"{ ""foo"": 1, ""bar"": [10, ""apples""] }");
        var data = jsonObject as Dictionary<string, object>;
        var array = data["bar"] as object[];
        Console.WriteLine(array[1]);
    }
		private static ValueDictionary Deserialize (string input)
		{
			try
			{
				ValueDictionary data = new ValueDictionary ();
				
				JavaScriptSerializer serializer = new JavaScriptSerializer ();
				object value = serializer.DeserializeObject (input);

				AppendBindingData (data, String.Empty, value);
				return data;
			}
			catch
			{
				return null;
			}
		}
        public Routes()
        {
            WebSocket["/smschat"] = _ => new WebSocketSmsChatHandler();

              Post["/{userId}/callback", true] = async (c, t) =>
              {
            var userId = (string)c.UserId;
            Debug.Print("Handling Catapult callback for user Id {0}", userId);
            using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
              var json = await reader.ReadToEndAsync();
              Debug.Print("Data from Catapult for {0}: {1}", userId, json);
              var serializer = new JavaScriptSerializer();
              var data = serializer.DeserializeObject(json);
              WebSocketHandler[] sockets;
              lock (WebSocketSmsChatHandler.ActiveSockets)
              {
            sockets = WebSocketSmsChatHandler.ActiveSockets.ToArray();
              }
              foreach (var socket in sockets.Where(s => (string) s.WebSocketContext.Items["userId"] == userId))
              {
            Debug.Print("Sending Catapult data to websocket client");
            socket.EmitEvent("message", data);
              }
              return "";
            }
              };

              Post["/upload", true] = async (c, t) =>
              {
            Debug.Print("Uploading file");
            var file = Request.Files.First();
            var fileName = Guid.NewGuid().ToString("N");
            var serializer = new JavaScriptSerializer();
            var auth = serializer.Deserialize<Dictionary<string, string>>(Request.Headers.Authorization);
            var client = Client.GetInstance(auth["UserId"], auth["ApiToken"], auth["ApiSecret"]);
            await Media.Upload(client, fileName, file.Value, file.ContentType);
            return new Dictionary<string, string>
            {
              {"fileName", fileName}
            };
              };
        }
Esempio n. 6
0
    public void ProcessRequest(HttpContext context)
    {
        try {
            var Request = context.Request;
            var Response = context.Response;
            log.Write( LogEvent.Info, "Processing request: {0}", Request.Url.ToString() );

            string providerName = Request["provider"];
            string operationName = Request["operation"];
            string contextJson = Request["context"];
            string langCode = Request["language"];
            try {
                if (!String.IsNullOrEmpty(langCode))
                    Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(langCode);
            } catch {
                log.Write( LogEvent.Warn, "Cannot apply language settings (language: {0}, request: {1})", langCode, Request.Url.ToString() );
            }

            var json = new JavaScriptSerializer();
            var prvContext = contextJson!=null ? json.DeserializeObject(contextJson) : null;

            if (providerName!=null) {
                var provider = WebManager.GetService<IProvider<object,object>>(providerName);
                if (provider!=null) {
                    var result = provider.Provide(prvContext);
                    if (result!=null)
                        Response.Write( json.Serialize(result) );
                }
            } else if (operationName!=null) {
                // maybe operation?
                var op = WebManager.GetService<IOperation<object>>(operationName);
                if (op!=null) {
                    op.Execute(prvContext);
                }
            }
        } catch (Exception ex) {
            log.Write(LogEvent.Warn, String.Format("exception={0}, url={1}", ex, context.Request.Url) );

            context.Response.Write(ex.Message);
            context.Response.StatusCode = 510; /*custom code:ajax error*/
        }
    }
Esempio n. 7
0
    private static object GetDeserializedObject(ControllerContext controllerContext)
    {
        if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
        {
            // not JSON request
            return(null);
        }
        StreamReader reader   = new StreamReader(controllerContext.HttpContext.Request.InputStream);
        string       bodyText = reader.ReadToEnd();

        if (String.IsNullOrEmpty(bodyText))
        {
            // no JSON data
            return(null);
        }
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        object jsonData = serializer.DeserializeObject(bodyText);

        return(jsonData);
    }
        public JsonResult GetLeaderBoard(string jsonData)
        {
            List <LeaderBoardForMgt> listLeaderBoard = new List <LeaderBoardForMgt>();
            JavaScriptSerializer     json_serializer = new JavaScriptSerializer();

            json_serializer.MaxJsonLength = int.MaxValue;
            object[] objData = (object[])json_serializer.DeserializeObject(jsonData);
            foreach (Dictionary <string, object> item in objData)
            {
                string radio      = Convert.ToString(item["Radiobtnchk"]);
                int    Cluster    = Convert.ToInt32(item["Cluster"]);
                int    SubCluster = Convert.ToInt32(item["SubCluster"]);
                int    City       = Convert.ToInt32(item["City"]);
                listLeaderBoard = MDR.GetLeaderBoardForMgts(radio, Cluster, SubCluster, City);
            }
            return(new JsonResult()
            {
                Data = listLeaderBoard, JsonRequestBehavior = JsonRequestBehavior.AllowGet, MaxJsonLength = Int32.MaxValue
            });
        }
 public ActionResult QuickModifyRZ(string rzRange)
 {
     try
     {
         JavaScriptSerializer serializer = new JavaScriptSerializer();
         object json = serializer.DeserializeObject(rzRange);
         List <Dictionary <string, decimal> > cmDicList = serializer.ConvertToType <List <Dictionary <string, decimal> > >(json);
         foreach (Dictionary <string, decimal> d in cmDicList)
         {
             SysConfig scf = this.service.SysConfig.GetSysConfig(d.First().Key);
             scf.ConfigValue = d.First().Value.ToString();
             this.service.SysConfig.Update(scf, null);
         }
         return(OperateResult(true, Lang.Msg_Operate_Success, ""));
     }
     catch (Exception e)
     {
         return(OperateResult(false, e.Message, ""));
     }
 }
Esempio n. 10
0
        public ActionResult Area()
        {
            string dataJson = this.Request.Form["dataJson"];

            JavaScriptSerializer jss = new JavaScriptSerializer();

            object[] obj = (object[])jss.DeserializeObject(dataJson);

            BLL.DB_Area           bll    = new BLL.DB_Area();
            List <NModel.DB_Area> nmodel = bll.GetList();

            foreach (NModel.DB_Area n in nmodel)
            {
                n.Area_PinYin = Pinyin.GetPinyin(n.Area_Name);

                bll.Edit(n);
            }

            return(View());
        }
Esempio n. 11
0
        public static void ParseValidateFor(this ModelStateDictionary modelState, string expressionText)
        {
            ModelErrorCollection errors;

            if ((modelState.ContainsKey(expressionText)) && ((errors = modelState[expressionText].Errors) != null) && (errors.Count > 0))
            {
                foreach (var error in new List <ModelError>(errors))
                {
                    string errorMessage = error.ErrorMessage;
                    if (!errorMessage.StartsWith("JSER:"))
                    {
                        continue;
                    }
                    errors.Remove(error);
                    var serializer = new JavaScriptSerializer();
                    var data       = serializer.DeserializeObject(errorMessage.Substring(5));
                    ApplyValidateValue(modelState, expressionText, data);
                }
            }
        }
Esempio n. 12
0
        public LatchResponse(String json)
        {
            Dictionary <string, object> response = (Dictionary <string, object>)js.DeserializeObject(json);

            if (response.ContainsKey("data"))
            {
                this.Data = (Dictionary <string, object>)response["data"];
            }

            if (response.ContainsKey("error"))
            {
                Dictionary <string, object> err = (Dictionary <string, object>)response["error"];
                int code;
                if (err.ContainsKey("code") && int.TryParse(err["code"].ToString(), out code))
                {
                    String message = err.ContainsKey("message") ? err["message"].ToString() : string.Empty;
                    this.Error = new Error(code, message);
                }
            }
        }
Esempio n. 13
0
        static public string QueryTestNamesByProductId(string pid)
        {
            QueryData d = new QueryData()
            {
                ProductId = pid
            };

            var json     = new JavaScriptSerializer().Serialize(d);
            var body     = new StringContent(json, Encoding.UTF8, "application/json");
            var response = PostAsync(Url + "/api/QueryResults", body).Result;

            string content = response.Content.ReadAsStringAsync().Result;
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            string        result = (string)jsSerializer.DeserializeObject(content);
            List <double> vals   = jsSerializer.Deserialize <List <double> >(result);

            StringBuilder sb = new StringBuilder();

            return(sb.ToString());
        }
Esempio n. 14
0
        private static void DownloadJsonComplete(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string pageString = e.Result;
                if (pageString == null)
                {
                    return;
                }
                Action <object>      jsonProcessor = e.UserState as Action <object>;
                JavaScriptSerializer serializer    = new JavaScriptSerializer();
                object data = serializer.DeserializeObject(pageString);

                jsonProcessor(data);
            }
            catch (Exception ex)
            {
                ErrorLogger.Log(ex);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// When implemented by a class, enables a server control to process an evePnt raised when a form is posted to the server.
        /// </summary>
        /// <param name="eventArgument">A <see cref="T:System.String"/> that represents an optional event argument to be passed to the event handler.</param>
        public void RaisePostBackEvent(string eventArgument)
        {
            var     ser  = new JavaScriptSerializer();
            dynamic args = ser.DeserializeObject(eventArgument);

            if (args != null)
            {
                string name = args["name"];
                if (args["route"] != null)
                {
                    var e = DirectionsChangedEventArgs.FromScriptData(args["route"]);
                    switch (name)
                    {
                    case "change":
                        this.OnChanged(e);
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// Creates a JSONObject by parsing a string.
        /// This is the only correct way to create a JSONObject.
        /// </summary>
        public static JSONObject CreateFromString(string s)
        {
            object o;
            JavaScriptSerializer js = new JavaScriptSerializer();

            try
            {
                o = js.DeserializeObject(s);
                if (o == null)
                {
                    o = s;  // serialize as scalar data
                }
            }
            catch (ArgumentException)
            {
                o = s;  // serialize as scalar data
            }

            return(Create(o));
        }
Esempio n. 17
0
        /// <summary>
        /// json字符串转换为Xml对象
        /// </summary>
        /// <param name="sJson"></param>
        /// <returns></returns>
        private static XmlDocument Json2Xml(string sJson)
        {
            JavaScriptSerializer        oSerializer = new JavaScriptSerializer();
            Dictionary <string, object> Dic         = (Dictionary <string, object>)oSerializer.DeserializeObject(sJson);
            XmlDocument    doc = new XmlDocument();
            XmlDeclaration xmlDec;

            xmlDec = doc.CreateXmlDeclaration("1.0", "gb2312", "yes");
            doc.InsertBefore(xmlDec, doc.DocumentElement);
            XmlElement nRoot = doc.CreateElement("IQCdata");

            doc.AppendChild(nRoot);
            foreach (KeyValuePair <string, object> item in Dic)
            {
                XmlElement element = doc.CreateElement(item.Key);
                KeyValue2Xml(element, item);
                nRoot.AppendChild(element);
            }
            return(doc);
        }
Esempio n. 18
0
        private string getUserID(string title)
        {
            string json = HTTP.GET("https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername="******"&fields=items%2Fid&key=AIzaSyAa33VM7zG0hnceZEEGdroB6DerP8fRJ6o");
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            var result = jsSerializer.DeserializeObject(json);
            Dictionary <string, object> obj2 = new Dictionary <string, object>();

            obj2 = (Dictionary <string, object>)(result);

            System.Object[] val      = (System.Object[])obj2["items"];
            string          response = null;

            try
            {
                Dictionary <string, object> id = (Dictionary <string, object>)val.GetValue(0);
                response = id["id"].ToString();
            }
            catch { MessageBox.Show("Wystąpił jakiś błąd, lub link do kanału jest niepoprawny", "Powerful YouTube DL", MessageBoxButton.OK, MessageBoxImage.Error); }
            return(response);
        }
Esempio n. 19
0
        public static Node FromJson(string sJson, Deserializer.Options options = null)
        {
            var jss = new JavaScriptSerializer();

            if (options != null)
            {
                if (options.RecursionLimit != Options.DefaultRecursionLimit)
                {
                    jss.RecursionLimit = options.RecursionLimit;
                }
                if (options.MaxJsonLength != Options.DefaultMaxJsonLength)
                {
                    jss.MaxJsonLength = options.MaxJsonLength;
                }
            }

            var jsonObject = jss.DeserializeObject(sJson);

            return(Deserializer.NodeFromJsonObject(jsonObject));
        }
Esempio n. 20
0
        static void JsonTest()
        {
            var json = @"    {
        ""Page"": ""manageBookmarks"",
        ""UserId"": ""0ede3a63-e97a-e911-a979-002248014773"",
        ""Action"": ""add"",
        ""ArticleId"": ""08d8ca0a-fba2-e911-a97b-00224801377b""
    }
";

            var jsSerializer = new JavaScriptSerializer();
            Dictionary <string, object> dict = (Dictionary <string, object>)jsSerializer.DeserializeObject(json);

            foreach (var kvp in dict)
            {
                Console.WriteLine("{0}: {1} ({2}: {3})", kvp.Key, kvp.Value, kvp.Key.GetType().Name, kvp.Value.GetType().Name);
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Esempio n. 21
0
        public async Task <IHttpActionResult> GetMoviesAsync(string userName)
        {
            await Task.Yield();

            var authToken = Request.Headers.Authorization;
            var target    = ConfigurationManager.AppSettings["User"];

            target += $"/{userName}/favoriteMovies";
            var request = new HttpRequestMessage(HttpMethod.Get, target);

            request.Headers.Authorization = authToken;
            var moviesResponse = await client.SendAsync(request);

            var returned = await moviesResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            var contentJson = jsonSerializer.DeserializeObject(returned);

            return(Ok(contentJson));
        }
        public ActionResult GetMeetingMatrixDetailReport(string searchData)
        {
            List <SalesLead>     objLeads        = new List <SalesLead>();
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();

            json_serializer.MaxJsonLength = int.MaxValue;
            object[] objData = (object[])json_serializer.DeserializeObject(searchData);
            foreach (Dictionary <string, object> item in objData)
            {
                var salesManager  = Convert.ToString(item["SalesManager"]);
                var frmDate       = Convert.ToString(item["frmDate"]);
                var toDate        = Convert.ToString(item["toDate"]);
                var MeetingOrCall = Convert.ToString(item["MeetingOrCall"]);
                var type          = Convert.ToString(item["type"]);

                objLeads = LRR.GetDetailMatrixReportData(salesManager, frmDate, toDate, MeetingOrCall, type);
            }

            return(PartialView("_MeetingMatrixDetails", objLeads));
        }
Esempio n. 23
0
        /// <summary>
        /// 获取企业号的accessToken
        /// </summary>
        /// <param name="corpid">企业号ID</param>
        /// <param name="corpsecret">管理组密钥</param>
        /// <returns></returns>
        private string GetAccessToken(string corpid, string corpsecret)
        {
            string          accessToken = "";
            string          respText    = "";
            string          url         = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", corpid, corpsecret);
            HttpWebRequest  request     = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response    = (HttpWebResponse)request.GetResponse();

            using (Stream resStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(resStream, Encoding.Default);
                respText = reader.ReadToEnd();
                resStream.Close();
            }
            JavaScriptSerializer        Jss     = new JavaScriptSerializer();
            Dictionary <string, object> respDic = (Dictionary <string, object>)Jss.DeserializeObject(respText);

            accessToken = respDic["access_token"].ToString();//通过键access_token获取值
            return(accessToken);
        }
Esempio n. 24
0
        private async Task <object> InvokeAsync(string method, string url, object data)
        {
            var request = (HttpWebRequest)HttpWebRequest.Create(url);

            request.UserAgent = "BuildMasterGitHubExtension/" + typeof(GitHubClient).Assembly.GetName().Version.ToString();
            request.Method    = method;
            if (data != null)
            {
                using (var requestStream = await request.GetRequestStreamAsync().ConfigureAwait(false))
                    using (var writer = new StreamWriter(requestStream, InedoLib.UTF8Encoding))
                    {
                        InedoLib.Util.JavaScript.WriteJson(writer, data);
                    }
            }

            if (!string.IsNullOrEmpty(this.UserName))
            {
                request.Headers[HttpRequestHeader.Authorization] = "basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(this.UserName + ":" + this.Password.ToUnsecureString()));
            }

            try
            {
                using (var response = await request.GetResponseAsync().ConfigureAwait(false))
                    using (var responseStream = response.GetResponseStream())
                        using (var reader = new StreamReader(responseStream))
                        {
                            var    js           = new JavaScriptSerializer();
                            string responseText = await reader.ReadToEndAsync().ConfigureAwait(false);

                            return(js.DeserializeObject(responseText));
                        }
            }
            catch (WebException ex) when(ex.Response != null)
            {
                using (var responseStream = ex.Response.GetResponseStream())
                {
                    string message = await new StreamReader(responseStream).ReadToEndAsync().ConfigureAwait(false);
                    throw new Exception(message);
                }
            }
        }
Esempio n. 25
0
        private static IEnumerable <IBook> BookSearch(string bookFile, string searchString)
        {
            // Denna metod listar böcker som matchar den angivna söksträngen.

            // Är bokfilen tom?
            if (bookFile == null)
            {
                return(null);
            }

            // Konvertera json-fil till text
            JavaScriptSerializer js = new JavaScriptSerializer();
            dynamic bookList        = js.DeserializeObject(bookFile);

            // Läs textfilen rad för rad och spara alla matchande rader i boklistan.
            var bookSelection = new List <Book>();
            int counter       = 1;

            if (bookList != null && searchString != null)
            {
                foreach (var item in bookList["books"])
                {
                    // Om bokens titel eller författare matchar söksträngen, så lägg till den i listan.
                    if (item["author"].ToLower().Contains(searchString.ToLower()) ||
                        item["title"].ToLower().Contains(searchString.ToLower()))
                    {
                        // Eftersom jag jobbar med testdata, anser jag att jag inte behöver göra någon try/catch här,
                        // utan litar på att alla priser är skrivna i korrekt decimalformat, och att alla antal är integers.
                        var book = new Book(counter++,
                                            item["title"],
                                            item["author"],
                                            System.Convert.ToDecimal(item["price"]),
                                            System.Convert.ToInt16(item["inStock"])
                                            );
                        bookSelection.Add(book);
                    }
                }
            }

            return(bookSelection);
        }
Esempio n. 26
0
        public static async Task <string> GetSetInfo(string adminId, string set)
        {
            EntitySetType        type;
            JavaScriptSerializer jser = new JavaScriptSerializer();
            dynamic sobj = jser.DeserializeObject(set) as dynamic;

            if (Enum.TryParse <EntitySetType>(sobj["set"], out type))
            {
                string filter = null;
                if (sobj.ContainsKey("setFilter"))
                {
                    filter = sobj["setFilter"];
                }
                switch (type)
                {
                case EntitySetType.User:
                {
                    var p = await GetMaxPriority(adminId);

                    UserServiceProxy svc = new UserServiceProxy();
                    var si = await svc.GetSetInfoAsync(Cntx, filter);

                    RoleServiceProxy rsvc = new RoleServiceProxy();
                    var roles             = await rsvc.QueryDatabaseAsync(Cntx, new RoleSet(), null);

                    List <dynamic> rlist = new List <dynamic>();
                    foreach (var r in roles)
                    {
                        if (r.RolePriority <= p.Major)
                        {
                            rlist.Add(new { id = r.ID, name = r.RoleName, path = r.DistinctString, op = true });
                        }
                    }
                    JavaScriptSerializer ser = new JavaScriptSerializer();
                    string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters, roles = rlist.ToArray() });
                    return(json);
                }
                }
            }
            return(null);
        }
Esempio n. 27
0
        /// <summary>
        /// Method to convert the incoming objects to models
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        private TaskModel Converter(object task)
        {
            TaskModel            taskModel     = new TaskModel();
            string               details       = task.ToString();
            JavaScriptSerializer objJavascript = new JavaScriptSerializer();
            var testModels = objJavascript.DeserializeObject(details);

            if (testModels != null)
            {
                Dictionary <string, object> dic1 = (Dictionary <string, object>)testModels;
                object value;

                if (dic1.TryGetValue("Task", out value))
                {
                    taskModel.Task = value.ToString();
                }
                if (dic1.TryGetValue("ParentId", out value))
                {
                    taskModel.ParentId = string.IsNullOrWhiteSpace(value.ToString()) ? 0 : Convert.ToInt16(value);
                }
                if (dic1.TryGetValue("Priority", out value))
                {
                    taskModel.Priority = string.IsNullOrWhiteSpace(value.ToString()) ? 0 : Convert.ToInt16(value);
                }
                if (dic1.TryGetValue("StartDate", out value))
                {
                    taskModel.StartDateString = value.ToString();
                }
                if (dic1.TryGetValue("EndDate", out value))
                {
                    taskModel.EndDateString = value.ToString();
                }
                if (dic1.TryGetValue("TaskId", out value))
                {
                    taskModel.TaskId = string.IsNullOrWhiteSpace(value.ToString()) ? 0 : Convert.ToInt16(value);
                }
                return(taskModel);
            }

            return(taskModel);
        }
Esempio n. 28
0
        /// <summary>
        /// Method to convert the incoming objects to models
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public UserModel UserConverter(object user)
        {
            UserModel            userModel     = new UserModel();
            string               details       = user.ToString();
            JavaScriptSerializer objJavascript = new JavaScriptSerializer();
            var inputModel = objJavascript.DeserializeObject(details);

            if (inputModel != null)
            {
                Dictionary <string, object> dic1 = (Dictionary <string, object>)inputModel;
                object value;

                if (dic1.TryGetValue("FirstName", out value))
                {
                    userModel.FirstName = value != null?value.ToString() : null;
                }
                if (dic1.TryGetValue("LastName", out value))
                {
                    userModel.LastName = value != null?value.ToString() : null;
                }
                if (dic1.TryGetValue("EmployeeId", out value))
                {
                    userModel.EmployeeId = value != null?value.ToString() : null;
                }
                if (dic1.TryGetValue("UserId", out value))
                {
                    userModel.UserId = string.IsNullOrWhiteSpace(value.ToString()) ? 0 : Convert.ToInt16(value);
                }
                if (dic1.TryGetValue("ProejctId", out value))
                {
                    userModel.ProjectId = string.IsNullOrWhiteSpace(value.ToString()) ? 0 : Convert.ToInt16(value);
                }
                if (dic1.TryGetValue("TaskId", out value))
                {
                    userModel.TaskId = string.IsNullOrWhiteSpace(value.ToString()) ? 0 : Convert.ToInt16(value);
                }
                return(userModel);
            }

            return(userModel);
        }
Esempio n. 29
0
        /// <summary>
        /// Method to convert the incoming objects to models
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public ProjectModel ProjectConverter(object project)
        {
            ProjectModel         projectModel  = new ProjectModel();
            string               details       = project.ToString();
            JavaScriptSerializer objJavascript = new JavaScriptSerializer();
            var testModels = objJavascript.DeserializeObject(details);

            if (testModels != null)
            {
                Dictionary <string, object> dic1 = (Dictionary <string, object>)testModels;
                object value;

                if (dic1.TryGetValue("Project", out value))
                {
                    projectModel.Project = value != null?value.ToString() : null;
                }
                if (dic1.TryGetValue("ProjectId", out value))
                {
                    projectModel.ProjectId = string.IsNullOrWhiteSpace(value.ToString()) ? 0 : Convert.ToInt16(value);
                }
                if (dic1.TryGetValue("StartDate", out value))
                {
                    projectModel.StartDateString = value != null?value.ToString() : null;
                }
                if (dic1.TryGetValue("EndDate", out value))
                {
                    projectModel.EndDateString = value.ToString();
                }
                if (dic1.TryGetValue("ManagerId", out value))
                {
                    projectModel.ManagerId = value != null?value.ToString() : null;
                }
                if (dic1.TryGetValue("Priority", out value))
                {
                    projectModel.Priority = string.IsNullOrWhiteSpace(value.ToString()) ? 0 : Convert.ToInt16(value);
                }
                return(projectModel);
            }

            return(projectModel);
        }
        public JsonResult GetPolicyList(string lang = null, PoliciesRequestType type = PoliciesRequestType.All)
        {
            string outputFormat = _workContext.GetContext().HttpContext.Request.Headers["OutputFormat"];
            IEnumerable <PolicyTextInfoPart> policies = _policyServices.GetPolicies(lang);

            var orchardUsersSettings    = _orchardServices.WorkContext.CurrentSite.As <UserRegistrationSettingsPart>();
            var registrationPoliciesIds = new Int32[0];

            if (orchardUsersSettings.PolicyTextReferences.Contains("{All}"))
            {
                registrationPoliciesIds = policies.Select(x => x.Id).ToArray();
            }
            else
            {
                registrationPoliciesIds = orchardUsersSettings.PolicyTextReferences.Select(x => Convert.ToInt32(x.Replace("{", "").Replace("}", ""))).ToArray();
            }

            if (type == PoliciesRequestType.ForRegistration)
            {
                policies = policies.Where(x => registrationPoliciesIds.Contains(x.Id));
            }
            else if (type == PoliciesRequestType.NotForRegistration)
            {
                policies = policies.Where(x => !registrationPoliciesIds.Contains(x.Id));
            }

            var jsonResult = "";

            if (String.Equals(outputFormat, "LMNV", StringComparison.OrdinalIgnoreCase))
            {
                jsonResult = _policyServices.PoliciesLMNVSerialization(policies);
            }
            else
            {
                jsonResult = _policyServices.PoliciesPureJsonSerialization(policies);
            }

            var serializer = new JavaScriptSerializer();

            return(Json(serializer.DeserializeObject(jsonResult), JsonRequestBehavior.AllowGet));
        }
Esempio n. 31
0
        /// <summary>
        /// Returns a formatted string of the statistics for this particular test
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="group"></param>
        /// <returns></returns>
        static public string QueryStatsByTest(string pid, string testName, string testSession, bool includeLeft, bool includeRight)
        {
            if (includeLeft == false && includeRight == false)
            {
                return("Nothing to do");
            }

            try
            {
                QueryData d = new QueryData()
                {
                    ProductId = pid, TestName = testName, TestSession = testSession, IncludeLeft = includeLeft, IncludeRight = includeRight
                };

                var json     = new JavaScriptSerializer().Serialize(d);
                var body     = new StringContent(json, Encoding.UTF8, "application/json");
                var response = PostAsync(Url + "/api/QueryResults", body).Result;

                string content = response.Content.ReadAsStringAsync().Result;
                JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                string        result = (string)jsSerializer.DeserializeObject(content);
                List <double> vals   = jsSerializer.Deserialize <List <double> >(result);

                StringBuilder sb = new StringBuilder();
                Maths.StdDev(vals, out double avg, out double stdDev);
                sb.AppendFormat("Total Data Points: {0}" + Environment.NewLine, vals.Count());
                sb.AppendFormat("Mean: {0:0.00}" + Environment.NewLine, avg);
                // BUGBUG: Should convert to linear first?
                sb.AppendFormat("StdDev: {0:0.00}" + Environment.NewLine, stdDev);
                sb.AppendFormat("Min: {0:0.00}" + Environment.NewLine, vals.Min());
                sb.AppendFormat("Max: {0:0.00}" + Environment.NewLine, vals.Max());

                return(sb.ToString());
            }
            catch (Exception ex)
            {
                Log.WriteLine(LogType.Database, "QueryStatsByTest() exception: " + ex.Message);
            }

            return("An error occurred. ");
        }
Esempio n. 32
0
        /// <summary>
        ///json字符串转化为键值对
        /// </summary>
        /// <param name="jasonString"></param>
        /// <returns></returns>
        public static Dictionary <string, object> GetJasonItems(string jasonString)
        {
            if (string.IsNullOrEmpty(jasonString))
            {
                return(new Dictionary <string, object>());
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            try
            {
                jasonString = jasonString.EndsWith(",}")?jasonString.Replace(",}", "}"):jasonString;

                Dictionary <string, object> retDic = (Dictionary <string, object>)serializer.DeserializeObject(jasonString);
                return(retDic);
            }
            catch (Exception ex)
            {
                return(new Dictionary <string, object>());
            }
        }
Esempio n. 33
0
        private void button2_Click(object sender, EventArgs e)
        {
            FileInfo fileInfo = new FileInfo(srcFileFullName);

            String replaceJson = tbx_format.Text;
            JavaScriptSerializer        serializer = new JavaScriptSerializer();
            Dictionary <string, object> jsonData   = (Dictionary <string, object>)serializer.DeserializeObject(replaceJson);
            Boolean backupResult = backupOldFile(srcFileFullName);

            if (!backupResult)
            {
                MessageBox.Show("备份文件失败,无法替换字符串");
            }

            Boolean replaceResult = strReplaceByDictionary(srcFileFullName, jsonData);

            if (replaceResult)
            {
                MessageBox.Show("替换完成");
            }
        }
Esempio n. 34
0
        private object queryPaginationYourWereJSON(Parame input)
        {
            string items = db.Database.SqlQuery <string>("EXEC [dbo].[pagination_json] @table_name,@search_text,@yourwhere,@key_where,@page,@limit_page,@sortby,@sort_type",
                                                         new SqlParameter("@table_name", input.table_name),
                                                         new SqlParameter("@search_text", input.search_text),
                                                         new SqlParameter("@yourwhere", input.yourwhere),
                                                         new SqlParameter("@key_where", input.key_where),
                                                         new SqlParameter("@page", input.page),
                                                         new SqlParameter("@limit_page", input.limit_page),
                                                         new SqlParameter("@sortby", input.sortby),
                                                         new SqlParameter("@sort_type", input.sort_type)
                                                         ).FirstOrDefault();

            if (items != null)
            {
                JavaScriptSerializer json_serializer = new JavaScriptSerializer();
                var result = json_serializer.DeserializeObject(items);
                return(result);
            }
            return(new object[] { });
        }
Esempio n. 35
0
        public ActionResult GetFilteredReport(string jsonData)
        {
            FeedbackGetFeedbackViewModel objviewmodel    = new FeedbackGetFeedbackViewModel();
            List <Feedback_Report>       lstreport       = new List <Feedback_Report>();
            JavaScriptSerializer         json_serializer = new JavaScriptSerializer();

            json_serializer.MaxJsonLength = int.MaxValue;
            object[] objData = (object[])json_serializer.DeserializeObject(jsonData);
            foreach (Dictionary <string, object> item in objData)
            {
                DateTime fromDate = Convert.ToDateTime(item["fromDate"]);
                DateTime toDate   = Convert.ToDateTime(item["toDate"]);
                string   Groupid  = Convert.ToString(item["groupId"]);
                string   salesR   = Convert.ToString(item["selectedsalesR"]);
                string   outletId = Convert.ToString(item["selectedoutlet"]);

                lstreport = FMR.GetReportData(Groupid, fromDate, toDate, salesR, outletId);
            }

            return(PartialView("_ReportListing", lstreport));
        }
Esempio n. 36
0
    public static bool BucketExists(this CouchbaseClient client, CouchbaseClientSection section = null)
    {
        section = section ?? (CouchbaseClientSection)ConfigurationManager.GetSection("couchbase");

        var webClient = new WebClient();
        var bucketUri = section.Servers.Urls.ToUriCollection().First().AbsoluteUri;
        var response  = webClient.DownloadString(bucketUri + "/buckets");
        var jss       = new JavaScriptSerializer();
        var jArray    = jss.DeserializeObject(response) as object[];

        foreach (var item in jArray)
        {
            var jDict  = item as Dictionary <string, object>;
            var bucket = jDict.Single(kv => kv.Key == "name").Value as string;
            if (bucket == section.Servers.Bucket)
            {
                return(true);
            }
        }
        return(false);
    }
Esempio n. 37
0
    /// <summary>
    /// 将json数据转换为定义好的对象,数据转换为DataTable
    /// </summary>
    /// <param name="jsonText"></param>
    /// <returns></returns>
    public static GeneralSearchResult GetTransformData(string jsonText)
    {
        GeneralSearchResult gsr = new GeneralSearchResult();
        JavaScriptSerializer s = new JavaScriptSerializer();

        object[] rows = (object[])s.DeserializeObject(jsonText);
        Dictionary<string, object> dicFieldDefine = (Dictionary<string, object>)rows[0];
        foreach (KeyValuePair<string, object> ss in dicFieldDefine)
        {
            gsr.FieldDefine.Columns.Add(ss.Key, typeof(string));
        }
        gsr.RetrunData = gsr.FieldDefine.Clone();
        foreach (object ob in rows)
        {
            Dictionary<string, object> val = (Dictionary<string, object>)ob;
            DataRow dr = gsr.RetrunData.NewRow();
            foreach (KeyValuePair<string, object> sss in val)
            {
                dr[sss.Key] = sss.Value;
            }
            gsr.RetrunData.Rows.Add(dr);
        }
        return gsr;
    }
 public virtual void FromJson(string json)
 {
     JavaScriptSerializer jss = new JavaScriptSerializer();
     IDictionary<string, object> dictionary = jss.DeserializeObject(json) as IDictionary<string, object>;
     FromJsonDictionary(dictionary);
 }
Esempio n. 39
0
    protected void btnOK_Click(object sender, EventArgs e)
    {
        try
        {
            WEC_REQUEST valObj = new WEC_REQUEST();

            if (txtTID.Value != "")
                valObj.TID = Convert.ToDecimal(txtTID.Value);

            //��ӵ����
            if (valObj.TID == 0)
            {
                WEC_REQUEST cond = new WEC_REQUEST();
                cond.KEYWORD = Convert.ToString(txtKEYWORD.Value);
                cond.AID = Convert.ToInt32(userBase2.Curraid);
                if (BLLTable<WEC_REQUEST>.Count(cond) > 0)
                {
                    ScriptManager.RegisterStartupScript(Page, this.GetType(), "goto", "alert('���������ظ��ؼ���')", true);
                    return;
                }
            }

            if(txtAID.Value !="" )
                valObj.AID = Convert.ToDecimal(txtAID.Value);

            if(txtKEYWORD.Value !="" )
                valObj.KEYWORD = Convert.ToString(txtKEYWORD.Value);

            if(txtMATCH_TYPE.Value !="" )
                valObj.MATCH_TYPE = Convert.ToInt32(txtMATCH_TYPE.Value);

            if (txtKIND.Value.Equals("5"))
            {
                valObj.MEMO = hidPICURL.Value; ;

            }
            else
            {
                valObj.MEMO = Convert.ToString(txtMEMO.Value);
            }

            if(txtKIND.Value !="" )
                valObj.KIND = Convert.ToInt32(txtKIND.Value);

            if(txtSTATUS.Value !="" )
                valObj.STATUS = Convert.ToInt32(txtSTATUS.Value);

            if(txtADDTIME.Value !="" )
                valObj.ADDTIME = Convert.ToDateTime(txtADDTIME.Value);

            if (valObj.TID >0)
            {
                //valObj.TID = Convert.ToDecimal(keyid);
                count = BLLTable<WEC_REQUEST>.Update(valObj, WEC_REQUEST.Attribute.TID);
            }
            else
            {
                count = BLLTable<WEC_REQUEST>.Insert(valObj, WEC_REQUEST.Attribute.TID);
                keyid = valObj.TID.ToString();

            }

            //ͼƬ�ظ�
            if (kind.Equals("5"))
            {
                string path=valObj.MEMO;
                path = path.Substring(path.LastIndexOf('/')+1);
                string filepath=Request.PhysicalApplicationPath+path;
                filepath = filepath.Replace('\\', '/');
                string content = HttpUtil.uploadFile(filepath, HttpUtil.getAccessToken("wx69c300b3e390be5b", "3c06a3f6eb8a562b278583dff8b9da1c"), "image");
                JavaScriptSerializer a = new JavaScriptSerializer();
                Dictionary<string, object> o = (Dictionary<string, object>)a.DeserializeObject(content);
                string media_id = (string)o["media_id"];
                WEC_REQUEST_MEDIA media = new WEC_REQUEST_MEDIA();
                media.MEIDAID = media_id;
                media.TID = valObj.TID;
                media.ADDTIME = DateTime.Now;
                media.TYPE = 0;
                media.FILENAME = filepath;
                BLLTable<WEC_REQUEST_MEDIA>.Insert(media,WEC_REQUEST_MEDIA.Attribute.ID);
            }

            if (count > 0)
            {
                StringBuilder sbData = new StringBuilder("{valObj:''");
                List<AttributeItem> lstCol = valObj.af_AttributeItemList;
                for (int i = 0; i < lstCol.Count; i++)
                {
                    object val = valObj.GetValue(lstCol[i]);
                    if (val != null)
                    {
                        sbData.Append(",").Append(lstCol[i].FieldName).Append(":'").Append(val.ToString()).Append("'");
                    }
                }
                sbData.Append("}");
                if (ViewState["sbData"] == null)
                {
                    ViewState["sbData"] = sbData.ToString();
                }
                else {
                    ViewState["sbData"] += ","+sbData.ToString();
                }
                Button btn = (Button)sender;
                if (btn.ID.IndexOf("btnOK")!=-1)
                {
                    if (ViewState["sbData"] == null)
                    {
                        string dataStr = "[" + ViewState["sbData"].ToString() + "]";
                        ScriptManager.RegisterStartupScript(Page, this.GetType(), "goto", "if (window.opener){window.opener.returnValue = '" + dataStr + "';}else{window.returnValue = '" + dataStr + "';}window.close();", true);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(Page, this.GetType(), "goto", "if (window.opener){window.opener.returnValue = 're';}else{window.returnValue = 're';}window.close();", true);
                    }
                }
                else
                {

                    txtTID.Value ="";

                    txtAID.Value ="";

                    txtKEYWORD.Value ="";

                    txtMATCH_TYPE.Value ="";

                    txtMEMO.Value ="";

                    txtKIND.Value ="";

                    txtSTATUS.Value ="";

                    txtADDTIME.Value ="";
                }
            }
        }
        catch (Exception ex)
        {
            litWarn.Text = ex.Message;
        }
    }
Esempio n. 40
0
    /// <summary>
    /// 7天天气预报
    /// </summary>
    /// <param name="futureday">未来天数0-6</param>
    /// <returns></returns>
    public static Dictionary<string, object> WeatherInfo(int futureday)
    {
        Dictionary<string, object> val = new Dictionary<string, object>();
        if (futureday>6)
        {
            val.Add("weaid", "未知");
            val.Add("days", DateTime.Now.Date.AddDays(futureday).ToString("yyyy-MM-dd"));
            val.Add("week", TimeHelper.GetFormatWeek1(DateTime.Now.Date.AddDays(futureday)));
            val.Add("cityno", "未知");
            val.Add("citynm", "未知");
            val.Add("cityid", "未知");
            val.Add("temperature", "未知");
            val.Add("humidity", "未知");
            val.Add("weather", "未知");
            val.Add("weather_icon", "Images/Weather/d/0.png");
            val.Add("weather_icon1", "Images/Weather/n/0.png");
            val.Add("wind", "未知");
            val.Add("winp", "未知");
            val.Add("temp_high", "?");
            val.Add("temp_low", "?");
            val.Add("humi_high", "?");
            val.Add("humi_low", "?");
            val.Add("weatid", "0");
            val.Add("weatid1", "0");
            val.Add("windid", "0");
            val.Add("winpid", "0");
        }
        else
        {
            string path = System.Web.HttpContext.Current.Server.MapPath("~/WeatherJson.txt");
            string jsonData = File.ReadAllText(path, Encoding.Default);

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(jsonData);
            object[] result = (object[])json["result"];
            val = (Dictionary<string, object>)result[futureday];
        }
        return val;
    }
Esempio n. 41
0
    public static string GetQrCodeTicketTemp(string token, long scene)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token);
        req.Method = "post";
        req.ContentType = "raw";
        //Stream streamReq = req.GetRequestStream();
        StreamWriter sw = new StreamWriter(req.GetRequestStream());
        sw.Write("{\"expire_seconds\": 1800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\":" + scene.ToString().PadLeft(32,'0') + "}}}");
        sw.Close();
        sw = null;

        HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        Stream s = res.GetResponseStream();
        StreamReader sr = new StreamReader(s);
        string strTicketJson = sr.ReadToEnd();
        sr.Close();
        s.Close();
        sr = null;
        s = null;
        res.Close();
        res = null;
        req.Abort();
        req = null;

        try
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(strTicketJson);
            object v;
            json.TryGetValue("ticket", out v);
            token = v.ToString();
            return token;
        }
        catch
        {

            return strTicketJson;
        }
    }
Esempio n. 42
0
    /*********************************************************************/
    /* JSON */
    /*********************************************************************/
#if USE_JSON
    /*
     * [Function]
     * convert json string into dictionary object
     * [Input]
     * json string
     * [Output]
     * object, internally is dictionary
     * [Note]
     * 1.you should know the internal structure of the dictionary
     * then converted to specific type of yours
     */
    public Object jsonToDict(string jsonStr)
    {
        JavaScriptSerializer jsonSerializer = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue };
        Object dictObj = jsonSerializer.DeserializeObject(jsonStr);

        return dictObj;
    }
Esempio n. 43
0
 public void SearchSchedule()
 {
     try
     {
     string variableSearch = Request.Params["variableSearch"];
     JavaScriptSerializer json_serializer = new JavaScriptSerializer();
     dynamic variable = json_serializer.DeserializeObject(variableSearch);
     Schedule_Model rs = new Schedule_Model();
     VariableConditionsSchedule_Model vsc = new VariableConditionsSchedule_Model();
     vsc.BranchID = variable["BranchID"];
     vsc.TeacherID = variable["TeacherID"];
     if (variable["StartDate"] != "")
     {
         vsc.StartDate = Convert.ToDateTime(variable["StartDate"]);
     }
     else
     {
         vsc.StartDate = new DateTime(2012, 1 , 1, 0, 0, 0);
     }
     if (variable["EndDate"] != "")
     {
         vsc.EndDate = Convert.ToDateTime(variable["EndDate"]);
     }
     else
     {
         vsc.EndDate = DateTime.MaxValue;
     }
     vsc.Thu2 = Convert.ToInt32(variable["Thu2"]);
     vsc.Thu3 = Convert.ToInt32(variable["Thu3"]);
     vsc.Thu4 = Convert.ToInt32(variable["Thu4"]);
     vsc.Thu5 = Convert.ToInt32(variable["Thu5"]);
     vsc.Thu6 = Convert.ToInt32(variable["Thu6"]);
     vsc.Thu7 = Convert.ToInt32(variable["Thu7"]);
     vsc.ChuNhat = Convert.ToInt32(variable["ChuNhat"]);
     ArrangeSchedule_Controler asController = new ArrangeSchedule_Controler();
     rs = asController.GetSchedule(vsc);
     WriteJsonData(Response, rs);
     }
     catch (Exception ex)
     {
         //Gửi email báo lỗi
         sendEmail.SendMailForTechnical("*****@*****.**", "Lỗi", ex.ToString(), true);
     }
 }
 public static IDictionary<int, string> DeserializeDictionary(string serialized)
 {
     if (string.IsNullOrEmpty(serialized))
         return null;
     JavaScriptSerializer jss = new JavaScriptSerializer();
     IDictionary<string, object> dictionary = jss.DeserializeObject(serialized) as IDictionary<string, object>;
     Dictionary<int, string> dict = new Dictionary<int, string>();
     foreach (var item in dictionary)
     {
         int id;
         if (int.TryParse(item.Key, out id))
         {
             dict.Add(id, item.Value as string);
         }
     }
     return dict;
 }
        public GPConfiguration(string serialized)
        {
            if (!string.IsNullOrWhiteSpace(serialized))
            {
                JavaScriptSerializer jss = new JavaScriptSerializer();
                IDictionary<string, object> dictionary = jss.DeserializeObject(serialized) as IDictionary<string, object>;
                InputParameters = new List<ParameterSupport.ParameterConfig>();
                OutputParameters = new List<ParameterSupport.ParameterConfig>();
                if (dictionary.ContainsKey("inputParameters"))
                {
                    IEnumerable parameters = dictionary["inputParameters"] as IEnumerable;
                    if (parameters != null)
                    {
                        foreach (Dictionary<string, object> item in parameters)
                        {
                            if (item != null)
                                InputParameters.Add(ParameterSupport.ParameterConfig.Create(item));
                        }
                    }
                }
                if (dictionary.ContainsKey("outputParameters"))
                {
                    IEnumerable parameters = dictionary["outputParameters"] as IEnumerable;
                    if (parameters != null)
                    {
                        foreach (Dictionary<string, object> item in parameters)
                        {
                            if (item != null)
                                OutputParameters.Add(ParameterSupport.ParameterConfig.Create(item));
                        }
                    }
                }

                if (dictionary.ContainsKey("layerOrder"))
                {
                    IEnumerable layers = dictionary["layerOrder"] as IEnumerable;
                    LayerOrder = new ObservableCollection<string>();
                    if (layers != null)
                    {
                        foreach (object item in layers)
                        {
                            if (item is string)
                                LayerOrder.Add(item as string);
                        }
                    }
                }

                if (dictionary.ContainsKey("taskEndPoint"))
                {
                    string url = dictionary["taskEndPoint"] as string;
                    if (!string.IsNullOrEmpty(url))
                        TaskEndPoint = new Uri(url);
                }
                if (dictionary.ContainsKey("title"))
                    Title = dictionary["title"] as string;
                if (dictionary.ContainsKey("taskName"))
                    TaskName = dictionary["taskName"] as string;
                if (dictionary.ContainsKey("helpUrl"))
                {
                    string url = dictionary["helpUrl"] as string;
                    if (!string.IsNullOrEmpty(url))
                        HelpUrl = new Uri(url);
                }

                if (dictionary.ContainsKey("useProxy"))
                {
                    string useProxyString = dictionary["useProxy"] as string;
                    if (!string.IsNullOrEmpty(useProxyString))
                    {
                        bool useProxy;
                        bool.TryParse(useProxyString, out useProxy);
                        UseProxy = useProxy;
                    }
                }
            }
        }
        public PersonalDataStructure GeneratePersonalData(UserGenderEnum? gender = null)
        {
            string contactDataUrl = "http://api.randomuser.me/0.4/";

            if (gender != null)
            {
                contactDataUrl = URLHelper.AddParameterToUrl(contactDataUrl, "gender", gender.Value == UserGenderEnum.Female ? "female" : "male");
            }

            var serializer = new JavaScriptSerializer();
            string jsonResponse = new WebClient().DownloadString(contactDataUrl);

            dynamic response = serializer.DeserializeObject(jsonResponse);
            dynamic user = response["results"][0]["user"];

            var capitalizer = new FirstLetterCapitalizer();

            var personalData = new PersonalDataStructure
            {
                Gender = user["gender"] == "male" ? UserGenderEnum.Male : UserGenderEnum.Female,
                FirstName = capitalizer.CapitalizeFirstLetters((string)user["name"]["first"]),
                LastName = capitalizer.CapitalizeFirstLetters((string)user["name"]["last"]),
                Address = capitalizer.CapitalizeFirstLetters((string)user["location"]["street"]),
                City = capitalizer.CapitalizeFirstLetters((string)user["location"]["city"]),
                MobilePhone = user["cell"],
                HomePhone = user["phone"],
                ZIP = user["location"]["zip"],
            };

            personalData.Email = personalData.FirstName + "." + personalData.LastName + "@" + StaticRandomCompanies.NextCompanyName() + ".com";

            return personalData;
        }
 protected override IEnumerable GetControlSelectedIds()
 {
     var json = new JavaScriptSerializer();
     var selectedList = json.DeserializeObject(selectedValues.Value ) as IEnumerable;
     var res = new ArrayList();
     foreach (string fileName in selectedList)
         res.Add( fileName );
     return res.ToArray();
 }
        public static PopupInfo FromJson(String json)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            IDictionary<string, object> dict = jss.DeserializeObject(json) as IDictionary<string, object>;

            if (dict != null && dict.Count > 0)
            {
                var popupInfo = PopupInfo.FromDictionary(dict);
                return popupInfo;
            }
            return null;
        }
 protected override IEnumerable GetControlSelectedIds()
 {
     var json = new JavaScriptSerializer();
     var selectedList = json.DeserializeObject(selectedValues.Value ) as IEnumerable;
     var res = new ArrayList();
     foreach (IDictionary<string,object> i in selectedList)
         res.Add( i[ValueFieldName] );
     return res.ToArray();
 }
Esempio n. 50
0
    public static string GetAccessToken(string appId, string appSecret)
    {
        string token = "";
        string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId.Trim() +"&secret=" + appSecret.Trim() ;
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        Stream s = res.GetResponseStream();
        string ret = (new StreamReader(s)).ReadToEnd();
        s.Close();
        res.Close();
        req.Abort();

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(ret);
        object v;
        json.TryGetValue("access_token", out v);
        token = v.ToString();

        return token;
    }
 public static Dictionary<string, PopupInfo> DictionaryFromJson(string json)
 {
     JavaScriptSerializer jss = new JavaScriptSerializer();
     IDictionary<string, object> dictionary = jss.DeserializeObject(json) as IDictionary<string, object>;
     Dictionary<string, PopupInfo> dict = new Dictionary<string, PopupInfo>();
     foreach (var item in dictionary)
     {
         IDictionary<string, object> popupDict = item.Value as IDictionary<string, object>;
         if (popupDict != null)
         {
             PopupInfo info = PopupInfo.FromDictionary(popupDict);
             if (info != null)
                 dict.Add(item.Key, info);
         }
     }
     return dict;
 }
Esempio n. 52
0
 public static string GetSimpleJsonValueByKey(string jsonStr, string key)
 {
     JavaScriptSerializer serializer = new JavaScriptSerializer();
     Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(jsonStr);
     object v;
     json.TryGetValue(key, out v);
     return v.ToString();
 }
Esempio n. 53
0
        public DashingModule()
            : base()
        {
            Settings.DefaultDashboard = "sample";
            Settings.Views = "dashboards";

            Get["/"] = x =>
            {
                return Response.AsRedirect("/" + Settings.DefaultDashboard);
            };

            Get["/{dashboard}"] = p =>
            {
                return View["dashboards/" + p.dashboard];
            };

            Get["/views/{widget}.html"] = param =>
            {
                string widget = param.widget;
                return Response.AsFile(string.Format("widgets/{0}/{0}.html", widget));
            };

            Get["/events"] = param =>
            {
                var @event = new { id = "Open", data = "Open" };
                var streamResponse = new EventStreamWriterResponse(Response, null, @event);
                ClientBus.Register(streamResponse);
                return streamResponse;
            };

            Post["/widgets/{id}"] = p =>
                {
                    Request.Body.Position = 0;
                    var s = new JavaScriptSerializer();
                    var body = s.DeserializeObject(new StreamReader(Request.Body).ReadToEnd()).ToExpando();
                    ClientBus.SendEvent(new Event
                    {
                        Id = p.id,
                        Data = body,
                        UpdatedAt = SystemTime.Now()
                    });
                    return 200;
                };
        }