Esempio n. 1
0
        public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            var group = new WebAssetGroup("", false);

            SetIfPresent <bool>(dictionary, CompressKey, compress => group.Compress = compress);
            SetIfPresent <float>(dictionary, CacheDurationKey, cacheDuration => group.CacheDurationInDays = cacheDuration);
            SetIfPresent <string>(dictionary, VersionKey, version => group.Version             = version);
            SetIfPresent <string>(dictionary, ContentTypeKey, contentType => group.ContentType = contentType);
            SetIfPresent <IEnumerable <IDictionary <string, object> > >(dictionary, DirectoriesKey, directories =>
            {
                var orderedFiles = directories.SelectMany(directory =>
                {
                    var path  = serializer.ConvertToType <string>(directory[PathKey]);
                    var files = serializer.ConvertToType <IEnumerable <IDictionary <string, object> > >(directory[FilesKey]);
                    return(files.Select(file => new
                    {
                        Source = "~/" + path + "/" + serializer.ConvertToType <string>(file[NameKey]),
                        Order = serializer.ConvertToType <int>(file[OrderKey])
                    }));
                });

                orderedFiles.OrderBy(file => file.Order)
                .Select(file => new WebAsset(file.Source))
                .Each(group.Items.Add);
            });

            return(group);
        }
Esempio n. 2
0
        public void getewdata(string jsonData)
        {
            try
            {
                Dictionary <string, object> json = (Dictionary <string, object>)serializer.DeserializeObject(jsonData);
                InputPars parse = null;
                if (!string.IsNullOrEmpty(json["data"].ToString()))
                {
                    parse = serializer.ConvertToType <InputPars>(json["data"]);
                }

                List <EWData> datalist = new List <EWData>();
                for (var i = 0; i < parse.citems.Count; i++)
                {
                    datalist.Add(GetData(parse.citems, i, parse.ctype, parse.cvalue, InputType.DA452));
                }

                string returnstr = "";
                //returnstr=ObjToJson.ToJson(datalist);
                returnstr = serializer.Serialize(datalist);
                Comm.OutPutjson("{ \"result\" : \"true\",\"message\":\"执行成功\",\"groupdata\":" + returnstr + " }");
            }
            catch (Exception ex)
            {
                Comm.ResultError(ex.Message);
            }
        }
Esempio n. 3
0
 public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
 {
     if (Attribute.IsDefined(type, typeof(DataContractAttribute)))
     {
         try
         {
             object instance = Activator.CreateInstance(type);
             IEnumerable <MemberInfo> members = ((IEnumerable <MemberInfo>)type.GetFields())
                                                .Concat(type.GetProperties().Where(property => property.CanWrite && property.GetIndexParameters().Length == 0))
                                                .Where((member) => Attribute.IsDefined(member, typeof(DataMemberAttribute)));
             foreach (MemberInfo member in members)
             {
                 DataMemberAttribute attribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute));
                 object value;
                 if (dictionary.TryGetValue(attribute.Name, out value) == false)
                 {
                     if (attribute.IsRequired)
                     {
                         throw new SerializationException(String.Format("Required DataMember with name {0} not found", attribute.Name));
                     }
                     continue;
                 }
                 if (member.MemberType == MemberTypes.Field)
                 {
                     FieldInfo field = (FieldInfo)member;
                     object    fieldValue;
                     if (ConvertEnumToString && field.FieldType.IsEnum)
                     {
                         fieldValue = Enum.Parse(field.FieldType, value.ToString());
                     }
                     else
                     {
                         fieldValue = serializer.ConvertToType(value, field.FieldType);
                     }
                     field.SetValue(instance, fieldValue);
                 }
                 else if (member.MemberType == MemberTypes.Property)
                 {
                     PropertyInfo property = (PropertyInfo)member;
                     object       propertyValue;
                     if (ConvertEnumToString && property.PropertyType.IsEnum)
                     {
                         propertyValue = Enum.Parse(property.PropertyType, value.ToString());
                     }
                     else
                     {
                         propertyValue = serializer.ConvertToType(value, property.PropertyType);
                     }
                     property.SetValue(instance, propertyValue);
                 }
             }
             return(instance);
         }
         catch (Exception)
         {
             return(null);
         }
     }
     return(null);
 }
Esempio n. 4
0
        public static void Init(Data data)
        {
            Data = data;
            String text = T("Quests");

            if (text != null)
            {
                var obj   = jss.Deserialize <Object[]>(text);
                var cates = jss.ConvertToType <ObservableCollection <String> >(obj[0]);
                AddAll(D.Data.Category, cates.Select(s => new Category(s)));
                var quests = jss.ConvertToType <ObservableCollection <Quest> >(obj.Skip(1).ToArray());
                AddAll(D.Data.Quests, quests.Select(q => q.Init()));
            }
            else
            {
                Data.Category.Add("category1");
                Data.Category.Add("category2");
            }
            Items   = jss.Deserialize <IdNamePair[]>(T("Items")).Select(v => v == null ? N_A : v).Skip(1).ToArray();
            Weapons = jss.Deserialize <IdNamePair[]>(T("Weapons")).Select(v => v == null ? N_A : v).Skip(1).ToArray();
            Armors  = jss.Deserialize <IdNamePair[]>(T("Armors")).Select(v => v == null ? N_A : v).Skip(1).ToArray();

            SystemFile sf = jss.Deserialize <SystemFile>(T("System"));

            Variables = sf.variables.Select((v, i) => v == null ? N_A : new IdNamePair {
                id = i, name = v
            }).Skip(1).ToArray();
            Switches = sf.switches.Select((v, i) => v == null ? N_A : new IdNamePair {
                id = i, name = v
            }).Skip(1).ToArray();
            IconSetFile = App.Path + "img/system/IconSet.png";
            IconSet     = new BitmapImage(new Uri(IconSetFile));
        }
Esempio n. 5
0
        public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (type == typeof(UserInfo))
            {
                return(new UserInfo(Email.Parse(serializer.ConvertToType <String>(dictionary["Email"]))));
            }

            if (type == typeof(ItemId))
            {
                return(new ItemId(Email.Parse(serializer.ConvertToType <String>(dictionary["Seller"])),
                                  serializer.ConvertToType <String>(dictionary["ItemName"])));
            }

            if (type == typeof(ItemInfo))
            {
                return(new ItemInfo(
                           serializer.ConvertToType <ItemId>(dictionary["ItemId"]),
                           serializer.ConvertToType <String>(dictionary["ImageUrl"]),
                           serializer.ConvertToType <DateTime>(dictionary["Expiration"]),
                           serializer.ConvertToType <Bid[]>(dictionary["Bids"])));
            }

            if (type == typeof(Bid))
            {
                return(new Bid(Email.Parse(serializer.ConvertToType <String>(dictionary["Bidder"])),
                               serializer.ConvertToType <Decimal>(dictionary["Amount"]),
                               serializer.ConvertToType <DateTime>(dictionary["Time"])));
            }

            return(null);
        }
Esempio n. 6
0
                //Uses reflection to invoke and populate the target type
                //conditionally converts Unix Timestamps to DateTime objects which otherwise would have thrown exceptions
                public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
                {
                    object target = type.InvokeMember(null,
                                                      System.Reflection.BindingFlags.DeclaredOnly |
                                                      System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |
                                                      System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.CreateInstance, null, null, null);

                    foreach (var kv in dictionary)
                    {
                        if (kv.Value != null)
                        {
                            var prop = type.GetProperties().First(o => o.Name.ToLower() == kv.Key.ToLower());
                            if (prop.PropertyType == typeof(DateTime) && kv.Value.GetType() == typeof(Int64))
                            {
                                prop.SetValue(target, new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds((Int64)kv.Value));
                            }
                            else if (prop.PropertyType.BaseType == typeof(Enum))
                            {
                                if (prop.PropertyType.GetFields().Any(o => o.Name == (string)kv.Value))
                                {
                                    prop.SetValue(target, serializer.ConvertToType(kv.Value, prop.PropertyType));
                                }
                                else
                                {
                                    throw new KeyNotFoundException("Invalid enum: " + kv.Value);
                                }
                            }
                            else
                            {
                                prop.SetValue(target, serializer.ConvertToType(kv.Value, prop.PropertyType));
                            }
                        }
                    }
                    return(target);
                }
        public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (type != typeof(PostBackHash) && type != typeof(List <PostBackHash>))
            {
                return(null);
            }

            PostBackHash hash = new PostBackHash();

            if (dictionary.ContainsKey("id"))
            {
                hash.ControlID = serializer.ConvertToType <String>(dictionary["id"]);
            }

            if (dictionary.ContainsKey("widgetName"))
            {
                hash.WidgetName = serializer.ConvertToType <String>(dictionary["widgetName"]);
            }

            if (dictionary.ContainsKey("options"))
            {
                hash.Options = serializer.ConvertToType <Dictionary <String, object> >(dictionary["options"]);
            }

            return(hash);
        }
        /// <summary>
        /// For Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dictionary"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static List <T> GetValueAsCollection <T>(this IDictionary <string, object> dictionary, string key) where T : new()
        {
            object val;

            if (!dictionary.TryGetValue(key, out val))
            {
                return(null);
            }

            var ser = new JavaScriptSerializer();

            ser.RegisterConverters(new[] { RedmineSerialization.Converters[typeof(T)] });

            List <T> list = new List <T>();

            var arrayList = val as ArrayList;

            if (arrayList != null)
            {
                list.AddRange(from object item in arrayList select ser.ConvertToType <T>(item));
            }
            else
            {
                var dict = val as Dictionary <string, object>;
                if (dict != null)
                {
                    list.AddRange(dict.Select(pair => ser.ConvertToType <T>(pair.Value)));
                }
            }
            return(list);
        }
        public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
            {
                throw new ArgumentNullException("dictionary");
            }

            if (type == typeof(UpBandDataItem))
            {
                // Create the instance to deserialize into.
                UpBandDataItem dataItem = null;

                if (dictionary.ContainsKey("action"))
                {
                    dataItem = new UpBandEvent();
                    UpBandEvent dataItemCasted = (UpBandEvent)dataItem;
                    dataItemCasted.action       = serializer.ConvertToType <string>(dictionary["action"]);
                    dataItemCasted.tz           = serializer.ConvertToType <string>(dictionary["tz"]);
                    dataItemCasted.date         = serializer.ConvertToType <int>(dictionary["date"]);
                    dataItemCasted.time_created = serializer.ConvertToType <int>(dictionary["time_created"]);
                }

                return(dataItem);
            }
            return(null);
        }
Esempio n. 10
0
        public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
            {
                throw new ArgumentNullException("dictionary");
            }

            if (type == typeof(DataTable))
            {   //将Dictionary转成Datatable完成反序列化
                foreach (KeyValuePair <string, object> table in dictionary)
                {
                    DataTable dt   = new DataTable(table.Key);//表名
                    ArrayList rows = (ArrayList)table.Value;
                    //列名
                    Dictionary <string, object> row = serializer.ConvertToType <Dictionary <string, object> >(rows[0]);
                    foreach (string item in row.Keys)
                    {
                        dt.Columns.Add(item);
                    }
                    //每行数据
                    for (int i = 0; i < rows.Count; i++)
                    {
                        DataRow dr = dt.NewRow();
                        Dictionary <string, object> dic = serializer.ConvertToType <Dictionary <string, object> >(rows[i]);
                        foreach (KeyValuePair <string, object> item in dic)
                        {
                            dr[item.Key] = item.Value;
                        }
                        dt.Rows.Add(dr);
                    }
                    return(dt);
                }
            }
            return(null);
        }
Esempio n. 11
0
        public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (type == typeof(Device))
            {
                var obj = new Device();
                if (dictionary.ContainsKey("publishDir"))
                {
                    obj.Publish = serializer.ConvertToType <string>(dictionary["publishDir"]);
                }
                if (dictionary.ContainsKey("root"))
                {
                    obj.Root = serializer.ConvertToType <string>(dictionary["root"]);
                }
                if (dictionary.ContainsKey("application"))
                {
                    obj.Application = serializer.ConvertToType <string>(dictionary["application"]);
                }
                if (dictionary.ContainsKey("outputDir"))
                {
                    obj.Output_Dir = serializer.ConvertToType <string>(dictionary["outputDir"]);
                }
                if (dictionary.ContainsKey("tempDir"))
                {
                    obj.Temp = serializer.ConvertToType <string>(dictionary["tempDir"]);
                }

                if (dictionary.ContainsKey("facebookAppID"))
                {
                    obj.FacebookAppID = serializer.ConvertToType <string>(dictionary["facebookAppID"]);
                }

                if (dictionary.ContainsKey("outputName"))
                {
                    obj.Output_Name = serializer.ConvertToType <string>(dictionary["outputName"]);
                }

                if (dictionary.ContainsKey("log"))
                {
                    obj.LogDebug = serializer.ConvertToType <bool>(dictionary["log"]);
                }

                if (dictionary.ContainsKey("applicationType"))
                {
                    obj.ApplicationType = serializer.ConvertToType <string>(dictionary["applicationType"]);
                }

                if (dictionary.ContainsKey("includes"))
                {
                    obj.Includes = serializer.ConvertToType <Includes>(dictionary["includes"]);
                }
                //if( dictionary.ContainsKey( "publish" ) )
                //  obj.PublishPropertisFull = serializer.ConvertToType<Moscrif.IDE.Devices.PublishProperty>(dictionary["publish"] );
                //if( dictionary.ContainsKey( "conditions" ) )
                //  obj.PublishPropertisFull = serializer.ConvertToType<Moscrif.IDE.Devices.PublishProperty>(dictionary["conditions"] );
                return(obj);
            }

            return(null);
        }
        /// <summary>
        /// Deserializes the specified dictionary.
        /// </summary>
        /// <param name="dictionary">The <see cref="IDictionary{String,Object}" />.</param>
        /// <param name="serializer">The <see cref="JavaScriptSerializer" />.</param>
        public void Deserialize(IDictionary <string, object> dictionary, JavaScriptSerializer serializer)
        {
            foreach (string key in dictionary.Keys)
            {
                switch (key)
                {
                case "error":
                    ApiUtil.ThrowIfError(dictionary, key, serializer);
                    break;

                case "accountId":
                    AccountId = Convert.ToInt64(dictionary[key]);
                    break;

                case "filterTags":
                    FilterTags = serializer.ConvertToType <List <string> >(dictionary[key]);
                    break;

                case "id":
                    Id = Convert.ToInt64(dictionary[key]);
                    break;

                case "name":
                    Name = (string)dictionary[key];
                    break;

                case "playlistType":
                    PlaylistType = ((string)dictionary[key]).ToBrightcoveEnum <PlaylistType>();
                    break;

                case "referenceId":
                    ReferenceId = (string)dictionary[key];
                    break;

                case "shortDescription":
                    ShortDescription = (string)dictionary[key];
                    break;

                case "tagInclusionRule":
                    TagInclusionRule = ((string)dictionary[key]).ToBrightcoveEnum <TagInclusionRule>();
                    break;

                case "thumbnailURL":
                    ThumbnailUrl = (string)dictionary[key];
                    break;

                case "videos":
                    Videos = serializer.ConvertToType <List <BrightcoveVideo> >(dictionary[key]);
                    break;

                case "videoIds":
                    VideoIds = serializer.ConvertToType <List <long> >(dictionary[key]);
                    break;
                }
            }
        }
 public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
 {
     return(new Game
     {
         name = serializer.ConvertToType <string>(LookupKeys(dictionary, "name", "game")),
         autostart = serializer.ConvertToType <Autostart>(LookupKeys(dictionary, "autostart")),
         alias = serializer.ConvertToType <Dictionary <string, string> >(LookupKeys(dictionary, "alias")),
         definitions = serializer.ConvertToType <List <Split> >(LookupKeys(dictionary, "definitions")),
     });
 }
Esempio n. 14
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="dictionary"></param>
            /// <param name="type"></param>
            /// <param name="serializer"></param>
            /// <returns></returns>
            public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                MergedAssetFile mergedAssetFile = new MergedAssetFile
                {
                    Order = serializer.ConvertToType <int>(dictionary["o"]),
                    Name  = serializer.ConvertToType <string>(dictionary["n"])
                };

                return(mergedAssetFile);
            }
Esempio n. 15
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="dictionary"></param>
            /// <param name="type"></param>
            /// <param name="serializer"></param>
            /// <returns></returns>
            public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                MergedAssetDirectory mergedAssetDirectory = new MergedAssetDirectory
                {
                    Path = serializer.ConvertToType <string>(dictionary["p"])
                };

                mergedAssetDirectory.Files.AddRange(serializer.ConvertToType <IList <MergedAssetFile> >(dictionary["f"]));

                return(mergedAssetDirectory);
            }
Esempio n. 16
0
        /// <summary>
        /// Converts the provided dictionary into an object of the specified type.
        /// </summary>
        /// <remarks>Only <see cref="Money"/> instances can be handled.</remarks>
        /// <returns>
        /// The deserialized object.
        /// </returns>
        /// <param name="dictionary">An <see cref="T:System.Collections.Generic.IDictionary`2"/> instance of property data stored as name/value pairs.</param>
        /// <param name="type">The type of the resulting object.</param>
        /// <param name="serializer">The <see cref="T:System.Web.Script.Serialization.JavaScriptSerializer"/> instance.</param>
        public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (type != typeof(Money))
            {
                throw new NotSupportedException();
            }

            Currency currency = serializer.ConvertToType <Currency>(dictionary[Data.Money.CURRENCY]);
            decimal  amount   = serializer.ConvertToType <decimal>(dictionary[Data.Money.AMOUNT]);

            return(new Money(amount, currency, ObsoleteCurrencyEventBehavior.Ignore));
        }
Esempio n. 17
0
 private void SetMemberValue(JavaScriptSerializer serializer, MemberInfo member, object obj, object value)
 {
     if (member is PropertyInfo)
     {
         PropertyInfo property = (PropertyInfo)member;
         property.SetValue(obj, serializer.ConvertToType(value, property.PropertyType), null);
     }
     else if (member is FieldInfo)
     {
         FieldInfo field = (FieldInfo)member;
         field.SetValue(obj, serializer.ConvertToType(value, field.FieldType));
     }
 }
Esempio n. 18
0
        /// <summary>
        /// 传入参数服务名称,
        /// 返回对应的请求地址
        /// </summary>
        public static string get_url(string service_name)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();

            if (js.ConvertToType <List <string> >(sinapay_config.get_trade_Interface_service()).Contains(service_name))
            {
                wpay_url = "https://testgate.pay.sina.com.cn/mas/gateway.do";// 网管地址 此处为测试交易类接口地址,请根据实际情况填写
            }
            else if (js.ConvertToType <List <string> >(sinapay_config.get_member_Interface_service()).Contains(service_name))
            {
                wpay_url = "https://testgate.pay.sina.com.cn/mgs/gateway.do";// 网管地址 此处为测试会员类接口地址,请根据实际情况填写
            }
            return(wpay_url);
        }
Esempio n. 19
0
 public ActionResult SaveAll(string DirtyDatas)
 {
     try
     {
         JavaScriptSerializer serializer = new JavaScriptSerializer();
         object             json         = serializer.DeserializeObject(DirtyDatas);
         List <ConsMixprop> listCms      = serializer.ConvertToType <List <ConsMixprop> >(json);
         List <Dictionary <string, string> > cmDicList = serializer.ConvertToType <List <Dictionary <string, string> > >(json);
         IList <string> allErrorList = new List <string>();
         Dictionary <string, string> failedConsMixID = new Dictionary <string, string>();
         foreach (Dictionary <string, string> cmDic in cmDicList)
         {
             string id = cmDic["id"];
             foreach (ConsMixprop cm in listCms)
             {
                 if (cm.ID == id)
                 {
                     Dictionary <string, string> .KeyCollection allKeys = cmDic.Keys;
                     NameValueCollection updateKeys = new NameValueCollection();
                     foreach (string key in allKeys)
                     {
                         updateKeys.Add(key, "");
                     }
                     //更新主表和子表
                     IList <string> returnError = this.service.ConsMixprop.UpdatePrimaryAndItems(cm, updateKeys);
                     if (returnError.Count != 0)   //说明该条配比修改失败,记录编号以便标记
                     {
                         failedConsMixID.Add(cm.ID, cm.ID);
                     }
                     //更新容重
                     SqlServerHelper helper = new SqlServerHelper();
                     int             val    = helper.ExecuteNonQuery(System.Data.CommandType.StoredProcedure, "sp_calculate_cons_rz", new System.Data.SqlClient.SqlParameter("@FormulaID", cm.ID));
                     allErrorList = allErrorList.Concat(returnError).ToList <string>();
                     break;
                 }
             }
         }
         if (allErrorList.Count > 0)
         {//部分修改成功但有错误
             return(OperateResult(false, string.Join("<br/>", allErrorList), failedConsMixID));
         }
         else  //完全成功
         {
             return(OperateResult(true, Lang.Msg_Operate_Success, ""));
         }
     }
     catch (Exception e) {
         return(OperateResult(false, e.Message, ""));
     }
 }
Esempio n. 20
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="dictionary"></param>
            /// <param name="type"></param>
            /// <param name="serializer"></param>
            /// <returns></returns>
            public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                MergedAsset mergedAsset = new MergedAsset
                {
                    ContentType         = serializer.ConvertToType <string>(dictionary["ct"]),
                    Version             = serializer.ConvertToType <string>(dictionary["v"]),
                    Compress            = serializer.ConvertToType <bool>(dictionary["c"]),
                    CacheDurationInDays = serializer.ConvertToType <float>(dictionary["cd"])
                };

                mergedAsset.Directories.AddRange(serializer.ConvertToType <IList <MergedAssetDirectory> >(dictionary["d"]));

                return(mergedAsset);
            }
Esempio n. 21
0
            public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                UProject result      = new UProject();
                string   ustxVersion = dictionary["ustxversion"] as string;

                USTx.Project      = result;
                result.Name       = dictionary["name"] as string;
                result.Comment    = dictionary["comment"] as string;
                result.OutputDir  = dictionary["output"] as string;
                result.CacheDir   = dictionary["cache"] as string;
                result.BPM        = Convert.ToDouble(dictionary["bpm"]);
                result.BeatPerBar = Convert.ToInt32(dictionary["bpbar"]);
                result.BeatUnit   = Convert.ToInt32(dictionary["bunit"]);
                result.Resolution = Convert.ToInt32(dictionary["res"]);

                foreach (var pair in (Dictionary <string, object>)(dictionary["exptable"]))
                {
                    var exp  = serializer.ConvertToType(pair.Value, typeof(IntExpression)) as IntExpression;
                    var _exp = new IntExpression(null, pair.Key, exp.Abbr)
                    {
                        Data = exp.Data,
                        Min  = exp.Min,
                        Max  = exp.Max,
                    };
                    result.ExpressionTable.Add(pair.Key, _exp);
                }

                var singers = dictionary["singers"] as ArrayList;

                foreach (var singer in singers)
                {
                    result.Singers.Add(serializer.ConvertToType(singer, typeof(USinger)) as USinger);
                }

                foreach (var track in dictionary["tracks"] as ArrayList)
                {
                    var _tarck = serializer.ConvertToType(track, typeof(UTrack)) as UTrack;
                    result.Tracks.Add(_tarck);
                }

                foreach (var part in dictionary["parts"] as ArrayList)
                {
                    result.Parts.Add(serializer.ConvertToType(part, typeof(UPart)) as UPart);
                }

                USTx.Project = null;
                return(result);
            }
        public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
            {
                throw new ArgumentNullException("dictionary");
            }

            if (type == typeof(ListItemCollection))
            {
                // Create the instance to deserialize into.
                ListItemCollection list = new ListItemCollection();

                // Deserialize the ListItemCollection's items.
                // <Snippet5>
                ArrayList itemsList = (ArrayList)dictionary["List"];
                for (int i = 0; i < itemsList.Count; i++)
                {
                    list.Add(serializer.ConvertToType <ListItem>(itemsList[i]));
                }
                // </Snippet5>

                return(list);
            }
            return(null);
        }
Esempio n. 23
0
        /// <summary>
        /// Attemps to read the solutions from a file.
        /// If the file doesn't exist it is created, or if the file is empty the function exists.
        /// </summary>
        private void CreateDataFromFile()
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            SolveAnswer          solved;

            if (!File.Exists(@solutions_path))
            {
                return;
            }

            foreach (string line in File.ReadLines(@solutions_path))
            {
                if (line.Length > 0)
                {
                    Answer ans = serializer.Deserialize <Answer>(line);
                    solved = serializer.ConvertToType <SolveAnswer>(ans.Content);
                    try
                    {
                        mazeSolutions.Add(solved.Name, line);
                    }
                    catch (Exception)
                    {
                        // Unexpected description of solution, or a solution by that name already exists.
                    }
                }
            }
        }
Esempio n. 24
0
        public virtual void SetDerializedProperty(object obj, PropertyInfo property, IDictionary <string, object> dictionary, JavaScriptSerializer serializer)
        {
            if (obj == null || property == null || !property.CanWrite || dictionary == null || serializer == null)
            {
                return;
            }

            JsonNameAttribute jsonPropertyAttribute = GetJsonPropertyAttribute(property);

            if (jsonPropertyAttribute == null || jsonPropertyAttribute.Ignored)
            {
                return;
            }

            string name = jsonPropertyAttribute.PropertyName;

            if (!dictionary.ContainsKey(name))
            {
                return;
            }

            object value = dictionary[name];

            // Important! Use JavaScriptSerializer.ConvertToType so that V3JsonConvert of properties of this class are called recursively.
            object convertedValue = serializer.ConvertToType(value, property.PropertyType);

            property.SetValue(obj, convertedValue);
        }
Esempio n. 25
0
    public static string Prueba(object Arr)
    {
        JavaScriptSerializer obj = new JavaScriptSerializer();
        Pojo PObject             = obj.ConvertToType <Pojo>(Arr);

        return(PObject.Encabezado.Nombre);
    }
Esempio n. 26
0
            public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                UPart result = null;

                if (dictionary.ContainsKey("notes"))
                {
                    result = new UVoicePart();
                    var _result = result as UVoicePart;

                    var notes = dictionary["notes"] as ArrayList;
                    foreach (var note in notes)
                    {
                        _result.Notes.Add(serializer.ConvertToType <UNote>(note));
                    }
                }
                else if (dictionary.ContainsKey("path"))
                {
                    result = Wave.CreatePart(dictionary["path"] as string);
                }

                if (result != null)
                {
                    result.Name    = dictionary["name"] as string;
                    result.Comment = dictionary["comment"] as string;
                    result.TrackNo = Convert.ToInt32(dictionary["trackno"]);
                    result.PosTick = Convert.ToInt32(dictionary["pos"]);
                    result.DurTick = Convert.ToInt32(dictionary["dur"]);
                }

                return(result);
            }
        /// <summary>
        /// Deserializes the specified dictionary.
        /// </summary>
        /// <param name="dictionary">The <see cref="IDictionary{String,Object}" />.</param>
        /// <param name="serializer">The <see cref="JavaScriptSerializer" />.</param>
        public void Deserialize(IDictionary <string, object> dictionary, JavaScriptSerializer serializer)
        {
            foreach (string key in dictionary.Keys)
            {
                switch (key)
                {
                case "error":
                    ApiUtil.ThrowIfError(dictionary, key, serializer);
                    break;

                case "items":
                    Clear();
                    AddRange(serializer.ConvertToType <T[]>(dictionary[key]));
                    break;

                case "page_number":
                    PageNumber = (int)dictionary[key];
                    break;

                case "page_size":
                    PageSize = (int)dictionary[key];
                    break;

                case "total_count":
                    TotalCount = (int)dictionary[key];
                    break;
                }
            }
        }
Esempio n. 28
0
        private async Task <ChangesResult> GetChanges(string accessToken, string requestUri, string cursor)
        {
            string rootUri = GetOneDriveRootUri(requestUri);

            requestUri = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", await GetItemUri(accessToken, requestUri, rootUri), "view.changes");

            ChangesResult result = new ChangesResult();

            using (var client = CreateHttpClient(accessToken))
            {
                var next = cursor;
                var ids  = new Dictionary <string, OneDriveModel.ItemInfo>();
                Dictionary <string, object> changes = null;
                var serializer = new JavaScriptSerializer();
                do
                {
                    var uri = requestUri;
                    if (!string.IsNullOrWhiteSpace(next))
                    {
                        uri = string.Format(CultureInfo.InvariantCulture, "{0}?token={1}", requestUri, next);
                    }

                    using (var response = await client.GetAsync(uri))
                    {
                        changes = await ProcessResponse <Dictionary <string, object> >("GetChanges", response);
                    }

                    if (changes.ContainsKey("@changes.resync"))
                    {
                        if (string.IsNullOrEmpty(next))
                        {
                            throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.OneDriveUnableToSync, changes["@changes.resync"]));
                        }

                        // resync
                        next = null;
                        changes["@changes.hasMoreChanges"] = true;
                        result = new ChangesResult();
                        continue;
                    }

                    var items = serializer.ConvertToType <OneDriveModel.OneDriveItemCollection>(changes);

                    // changes
                    if (items != null && items.value != null && items.value.Count > 0)
                    {
                        var subResults = GetChanges(items, ids, rootUri);
                        result.DeletionChanges.AddRange(subResults.DeletionChanges);
                        result.DirectoryChanges.AddRange(subResults.DirectoryChanges);
                        result.FileChanges.AddRange(subResults.FileChanges);
                    }

                    // set next token
                    next = (string)changes["@changes.token"];
                } while ((bool)changes["@changes.hasMoreChanges"]);

                result.Cursor = next;
                return(result);
            }
        }
Esempio n. 29
0
        private void btnFromBlockchain_Click(object sender, EventArgs e)
        {
            try
            {
                WebClient            wc   = new WebClient();
                string               json = wc.DownloadString("http://blockchain.info/unspent?active=" + txtAddress.Text);
                JavaScriptSerializer jss  = new JavaScriptSerializer();

                Dictionary <string, object>   jso     = jss.Deserialize <Dictionary <string, object> >(json);
                Dictionary <string, object>[] outputs = jss.ConvertToType <Dictionary <string, object>[]>(jso["unspent_outputs"]);
                foreach (Dictionary <string, object> txo in outputs)
                {
                    string tx_hash     = (string)txo["tx_hash"];
                    int    tx_output_n = (int)txo["tx_output_n"];
                    ulong  value       = Convert.ToUInt64((string)txo["value_hex"], 16);
                    string script      = (string)txo["script"];

                    UTXO.Add(new TxOutId(HexString.ToByteArray(tx_hash), (uint)tx_output_n), new TxOut(value, HexString.ToByteArray(script)));
                }
                updateUTXOList();
            }
            catch (Exception)
            {
                MessageBox.Show("Error downloading unspent outputs.");
                return;
            }
        }
        public static object JsonDeserialize(string jsonString, Type type, string root)
        {
            if (string.IsNullOrEmpty(jsonString))
            {
                return(null);
            }

            var serializer = new JavaScriptSerializer();

            serializer.RegisterConverters(new[] { jsonConverters[type] });

            var dic = serializer.Deserialize <Dictionary <string, object> >(jsonString);

            if (dic == null)
            {
                return(null);
            }

            object obj;

            if (dic.TryGetValue(root ?? type.Name.ToLowerInvariant(), out obj))
            {
                var deserializedObject = serializer.ConvertToType(obj, type);

                return(deserializedObject);
            }
            return(null);
        }
Esempio n. 31
0
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");

            if (type == typeof(ListItemCollection))
            {
                // Create the instance to deserialize into.
                ListItemCollection list = new ListItemCollection();

                // Deserialize the ListItemCollection's items.
                ArrayList itemsList = (ArrayList)dictionary["List"];
                for (int i=0; i<itemsList.Count; i++)
                    list.Add(serializer.ConvertToType<ListItem>(itemsList[i]));

                return list;
            }
            return null;
        }