コード例 #1
0
        public static RaiserInfo GetValueFromJson(TextReader jsonStream, string language)
        {
            RaiserInfo result = null;

            using (Newtonsoft.Json.JsonTextReader jtr = new Newtonsoft.Json.JsonTextReader(jsonStream))
            {
                bool?  enable = true;
                int?   count = 0;
                string md5 = string.Empty, url = string.Empty, tmp;
                while (jtr.Read())
                {
                    if (jtr.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                    {
                        if (((string)jtr.Value).ToLower() == language.ToLower())
                        {
                            while (jtr.Read())
                            {
                                if (jtr.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                                {
                                    tmp = ((string)jtr.Value).ToLower();
                                    if (tmp == "enabled")
                                    {
                                        enable = jtr.ReadAsBoolean();
                                    }
                                    else if (tmp == "filecount")
                                    {
                                        count = jtr.ReadAsInt32();
                                    }
                                    else if (tmp == "patchmd5")
                                    {
                                        md5 = jtr.ReadAsString();
                                    }
                                    else if (tmp == "patchurl")
                                    {
                                        url = jtr.ReadAsString();
                                    }
                                    else
                                    {
                                        jtr.Skip();
                                    }
                                }
                            }
                        }
                        else
                        {
                            jtr.Skip();
                        }
                    }
                }
                if (enable.HasValue && !enable.Value)
                {
                    result = new RaiserInfo(false, count.HasValue ? count.Value : 0, md5, url);
                }
                else
                {
                    result = new RaiserInfo(true, count.HasValue ? count.Value : 0, md5, url);
                }
            }
            return(result);
        }
コード例 #2
0
ファイル: JsonSerializer.cs プロジェクト: gocheap/ShokoServer
        public void Deserialize(OperationDescription operation, Dictionary <string, int> parameterNames, Message message, object[] parameters)
        {
            object bodyFormatProperty;

            if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) ||
                (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw)
            {
                throw new InvalidOperationException(
                          "Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?");
            }

            var bodyReader = message.GetReaderAtBodyContents();

            bodyReader.ReadStartElement("Binary");
            byte[] rawBody = bodyReader.ReadContentAsBase64();
            using (var ms = new MemoryStream(rawBody))
                using (var sr = new StreamReader(ms))
                {
                    var serializer = new Newtonsoft.Json.JsonSerializer();
                    if (parameters.Length == 1)
                    {
                        // single parameter, assuming bare
                        parameters[0] = serializer.Deserialize(sr, operation.Messages[0].Body.Parts[0].Type);
                    }
                    else
                    {
                        // multiple parameter, needs to be wrapped
                        Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(sr);
                        reader.Read();
                        if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject)
                        {
                            throw new InvalidOperationException("Input needs to be wrapped in an object");
                        }

                        reader.Read();
                        while (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                        {
                            var parameterName = reader.Value as string;
                            reader.Read();
                            if (parameterNames.ContainsKey(parameterName))
                            {
                                int parameterIndex = parameterNames[parameterName];
                                parameters[parameterIndex] = serializer.Deserialize(reader,
                                                                                    operation.Messages[0].Body.Parts[parameterIndex].Type);
                            }
                            else
                            {
                                reader.Skip();
                            }

                            reader.Read();
                        }

                        reader.Close();
                    }
                    sr.Close();
                    ms.Close();
                }
        }
コード例 #3
0
        public void Deserialize(OperationDescription operation, Dictionary<string, int> parameterNames, Message message, object[] parameters)
        {
            object bodyFormatProperty;
            if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) ||
                (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw)
            {
                throw new InvalidOperationException(
                    "Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?");
            }

            var bodyReader = message.GetReaderAtBodyContents();
            bodyReader.ReadStartElement("Binary");
            byte[] rawBody = bodyReader.ReadContentAsBase64();
            using (var ms = new MemoryStream(rawBody))
            using (var sr = new StreamReader(ms))
            {
                var serializer = new Newtonsoft.Json.JsonSerializer();
                if (parameters.Length == 1)
                {
                    // single parameter, assuming bare
                    parameters[0] = serializer.Deserialize(sr, operation.Messages[0].Body.Parts[0].Type);
                }
                else
                {
                    // multiple parameter, needs to be wrapped
                    Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(sr);
                    reader.Read();
                    if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject)
                    {
                        throw new InvalidOperationException("Input needs to be wrapped in an object");
                    }

                    reader.Read();
                    while (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                    {
                        var parameterName = reader.Value as string;
                        reader.Read();
                        if (parameterNames.ContainsKey(parameterName))
                        {
                            int parameterIndex = parameterNames[parameterName];
                            parameters[parameterIndex] = serializer.Deserialize(reader,
                                operation.Messages[0].Body.Parts[parameterIndex].Type);
                        }
                        else
                        {
                            reader.Skip();
                        }

                        reader.Read();
                    }

                    reader.Close();
                }
                sr.Close();
                ms.Close();
            }
        }
コード例 #4
0
        public static void PostgresInsert(String filename)
        {
            String        jsonDoc = "";
            List <String> batch   = new List <string>();
            int           i       = 0;

            using (var streamReader = new StreamReader(filename))
            {
                using (var reader = new Newtonsoft.Json.JsonTextReader(streamReader))
                {
                    while (reader.Read())
                    {
                        if (reader.TokenType == Newtonsoft.Json.JsonToken.StartArray)
                        {
                            //Console.WriteLine(reader.TokenType);
                            while (reader.Read())
                            {
                                if (reader.TokenType == Newtonsoft.Json.JsonToken.StartObject)
                                {
                                    Object obj = new Newtonsoft.Json.JsonSerializer().Deserialize(reader);
                                    jsonDoc = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
                                }

                                batch.Add(jsonDoc);
                                //Console.WriteLine(batch.Count);
                                if (batch.Count >= 10000)
                                {
                                    i += 10000;
                                    MD5 md5Hash = MD5.Create();

                                    // Insert some data
                                    using (var writer = conn.BeginBinaryImport("COPY geo (data,id,hash) FROM STDIN (FORMAT BINARY)"))
                                    {
                                        foreach (var document in batch)
                                        {
                                            writer.StartRow();
                                            writer.Write(document, NpgsqlDbType.Json);

                                            var jo = JObject.Parse(document);
                                            var id = jo["properties"]["gml_id"].ToString();
                                            writer.Write(id);

                                            var hash = GetMd5Hash(md5Hash, document);
                                            writer.Write(hash);
                                        }

                                        writer.Complete();
                                        batch.Clear();
                                        Console.WriteLine(i);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #5
0
        List<Show> Grab(GrabParametersBase p,ILogger logger)
        {
            var pp = (CyfraPlus.GrabParameters)p;
            var shows = new List<Show>();
            var wr = WebRequest.Create(string.Format(urlFormat, pp.Date.ToString(DateFormat)));
            logger.WriteEntry(string.Format("Grabbing Cyfra+ date {0} ...", pp.Date.ToString(DateFormat)), LogType.Info);
            var res = (HttpWebResponse)wr.GetResponse();
            const int ChannelDepth = 2;

            using (var sr = new StreamReader(res.GetResponseStream()))
            {
                var startDownloadTime = DateTime.Now;
                var data = new StringBuilder();
                int blockSize = 16384;
                while (!sr.EndOfStream)
                {
                    var buf = new char[blockSize];
                    var totalRead = sr.ReadBlock(buf, 0, blockSize);
                    data.Append(buf);
                    if (DateTime.Now - startDownloadTime > TimeSpan.FromSeconds(1))
                    {
                        startDownloadTime = DateTime.Now;
                        logger.WriteEntry(string.Format("Downloaded {0:#,##0} bytes so far", data.Length), LogType.Info);
                    }
                }

                var r = new Newtonsoft.Json.JsonTextReader(new StringReader(data.ToString()));

                while (r.Read())
                {
                    r.Read();
                    var channelNumber = r.ReadAsInt32();
                    var channelName = r.ReadAsString();
                    r.Read();
                    r.Read();
                    while (r.Depth > ChannelDepth)
                    {
                        var show = new Show();
                        show.Channel = channelName.Trim();
                        var programId = r.ReadAsInt32();
                        show.Title = Tools.CleanupText(r.ReadAsString());

                        show.StartTime = new DateTime(1970, 1, 1).Add(TimeSpan.FromSeconds(r.ReadAsInt32().Value));
                        show.EndTime = show.StartTime.Add(TimeSpan.FromSeconds(Convert.ToDouble(r.ReadAsInt32())));
                        var num = r.ReadAsInt32();
                        shows.Add(show);
                        var depth = r.Depth;
                        while (r.Depth == depth)
                            r.Read();
                        r.Read();
                    }
                }

            }
            return shows;
        }
コード例 #6
0
        GetJsonObjectAsParameterList(Microsoft.AspNetCore.Http.HttpContext context)
        {
            System.Collections.Generic.List <System.Collections.Generic.Dictionary <string, object> > lss = new System.Collections.Generic.List <System.Collections.Generic.Dictionary <string, object> >();

            // Contenct can be JSON, and content type is wrong ...
            //if (string.Equals(context.Request.ContentType, "application/json", System.StringComparison.InvariantCultureIgnoreCase))
            //{
            Newtonsoft.Json.Linq.JToken jsonData = null;


            // Can only be read ONCE !
            using (System.IO.StreamReader reader = new System.IO.StreamReader(context.Request.Body, System.Text.Encoding.UTF8, false, 4096, true))
            {
                using (Newtonsoft.Json.JsonTextReader jsonReader = new Newtonsoft.Json.JsonTextReader(reader))
                {
                    // https://github.com/JamesNK/Newtonsoft.Json/issues/1773
                    if (jsonReader.Read())
                    {
                        jsonData = Newtonsoft.Json.Linq.JToken.Load(jsonReader);

                        if (jsonData != null)
                        {
                            lss = Json2List(jsonData);
                        } // End if (jsonData == null)
                    }     // End if (jsonReader.Read())
                }         // End Using jsonReader
            }             // End Using reader

            // } // End if (string.Equals(context.Request.ContentType, "application/json",

            return(lss);
        } // End Function GetParameters
コード例 #7
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        public MainWindowViewModel()
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(JSON_FILE_NAME, Encoding.GetEncoding("utf-8"));
            string allLine            = sr.ReadToEnd();

            sr.Close();

            ObservableCollection <Data> datas = new ObservableCollection <Data>();

            Newtonsoft.Json.JsonReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(allLine));
            jsonTextReader.SupportMultipleContent = true;

            while (true)
            {
                if (!jsonTextReader.Read())
                {
                    break;
                }
                Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                Data data = serializer.Deserialize <Data>(jsonTextReader);
                data.IsCheckedAction += CalcCredit;

                datas.Add(data);
            }
            DataList = datas;
        }
コード例 #8
0
            public Guid?MoveToNextId()
            {
                bool shouldContinue = true;

                while (shouldContinue)
                {
                    shouldContinue = reader.Read();

                    if (reader.Value?.ToString() == "Id")
                    {
                        var id = reader.ReadAsString();
                        return(new Guid(id));
                    }
                }
                //A null id means we have reached EOF
                return(null);
            }
コード例 #9
0
 static void TestReaderNewtonsoft(StreamReader reader)
 {
     using (var json = new Newtonsoft.Json.JsonTextReader(reader))
         while (json.Read())
         {
             ;
         }
 }
コード例 #10
0
 public void ReaderNewtonsoft()
 {
     _stream.Seek(0, SeekOrigin.Begin);
     using (var json = new Newtonsoft.Json.JsonTextReader(_reader))
         while (json.Read())
         {
             ;
         }
 }
コード例 #11
0
            private static VideoInfo[] ParseVideos(string input)
            {
                Newtonsoft.Json.JsonTextReader jtr  = new Newtonsoft.Json.JsonTextReader(new StringReader(input));
                Dictionary <string, string>    list = new Dictionary <string, string>();
                List <VideoInfo> videos             = new List <VideoInfo>();
                bool             hasFound           = false;

                while (jtr.Read())
                {
                    if (jtr.Value != null)
                    {
                        string nme = (string)jtr.Value;
                        if (jtr.Read() && jtr.Value != null)
                        {
                            if (jtr.ValueType == typeof(string))
                            {
                                string val = (string)jtr.Value;
                                if (val == "youtube#searchResult")
                                {
                                    if (hasFound)
                                    {
                                        videos.Add(new VideoInfo(list));
                                        // Console.WriteLine();
                                        list.Clear();
                                    }
                                    else
                                    {
                                        hasFound = true;
                                    }
                                }
                                else if (hasFound)
                                {
                                    //Console.WriteLine(nme + ": " + jtr.Value);
                                    if (!list.ContainsKey(nme))
                                    {
                                        list.Add(nme, (string)jtr.Value);
                                    }
                                }
                            }
                        }
                    }
                }
                return(videos.ToArray());
            }
コード例 #12
0
ファイル: Form1.cs プロジェクト: BrianWarris/Quiz
        public Form1()
        {
            InitializeComponent();
            string            jsonFilePath = "";
            AppSettingsReader asr          = new AppSettingsReader();
            string            previousName = "";

            getConfigValue <string>(asr, "DefinitionFile", ref jsonFilePath, string.Empty);
            if (!string.IsNullOrEmpty(jsonFilePath) && File.Exists(jsonFilePath))
            {
                this.lblCurrentFile.Text = jsonFilePath;
                using (TextReader tr = new StreamReader(jsonFilePath))
                {
                    Newtonsoft.Json.JsonTextReader rdr = new Newtonsoft.Json.JsonTextReader(tr);
                    while (rdr.Read())
                    {
                        //   Debug.WriteLine($"{rdr.ReadAsString()}");
                        // reference:  https://www.newtonsoft.com/json/help/html/ReadJsonWithJsonTextReader.htm
                        if (rdr.Value != null)
                        {
                            Debug.WriteLine("Token: {0}, Value: {1}", rdr.TokenType, rdr.Value);
                            if (rdr.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                            {
                                if (rdr.Value.ToString().CompareTo("title") == 0)
                                {
                                    previousName = "title";
                                }
                                else if (rdr.Value.ToString().CompareTo("questions") == 0)
                                {
                                    previousName = "questions";
                                }
                                else
                                {
                                    // save the setting
                                    if (previousName.CompareTo("title") == 0)
                                    {
                                        this.Text = rdr.Value.ToString();
                                    }
                                    else
                                    {
                                        questions.Add(rdr.Value.ToString());
                                    }
                                }
                            }
                            else if (rdr.TokenType == Newtonsoft.Json.JsonToken.String)
                            {
                                answers.Add(rdr.Value.ToString());
                            }
                        }
                    }
                    rdr.Close();
                    ShowQuestion(1);
                }
            }
        }
コード例 #13
0
        public void ReaderNewtonsoftReaderEmptyLoop()
        {
            _stream.Seek(0, SeekOrigin.Begin);
            TextReader reader = _reader;
            var        json   = new Newtonsoft.Json.JsonTextReader(reader);

            while (json.Read())
            {
                ;
            }
        }
コード例 #14
0
        public string GetCurrentUserId()
        {
            string       idStr   = "";
            StringReader jsonStr = new StringReader(CurrentUser);

            Newtonsoft.Json.JsonTextReader reader = new Newtonsoft.Json.JsonTextReader(jsonStr);

            while (reader.Read())
            {
                if (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                {
                    if (reader.Value.ToString() == "_id")
                    {
                        reader.Read();
                        idStr = reader.Value.ToString();
                        break;
                    }
                }
            }
            return(idStr);
        }
コード例 #15
0
        List <Show> Grab(GrabParametersBase p, ILogger logger)
        {
            var pp    = (CyfraPlus.GrabParameters)p;
            var shows = new List <Show>();
            var wr    = WebRequest.Create(string.Format(urlFormat, pp.Date.ToString(DateFormat)));

            logger.WriteEntry(string.Format("Grabbing Cyfra+ date {0} ...", pp.Date.ToString(DateFormat)), LogType.Info);
            var       res          = (HttpWebResponse)wr.GetResponse();
            const int ChannelDepth = 2;

            using (var sr = new StreamReader(res.GetResponseStream()))
            {
                var startDownloadTime = DateTime.Now;
                var data      = new StringBuilder();
                int blockSize = 16384;
                while (!sr.EndOfStream)
                {
                    var buf       = new char[blockSize];
                    var totalRead = sr.ReadBlock(buf, 0, blockSize);
                    data.Append(buf);
                    if (DateTime.Now - startDownloadTime > TimeSpan.FromSeconds(1))
                    {
                        startDownloadTime = DateTime.Now;
                        logger.WriteEntry(string.Format("Downloaded {0:#,##0} bytes so far", data.Length), LogType.Info);
                    }
                }

                var r = new Newtonsoft.Json.JsonTextReader(new StringReader(data.ToString()));

                while (r.Read())
                {
                    r.Read();
                    var channelNumber = r.ReadAsInt32();
                    var channelName   = r.ReadAsString();
                    r.Read();
                    r.Read();
                    while (r.Depth > ChannelDepth)
                    {
                        var show = new Show();
                        show.Channel = channelName.Trim();
                        var programId = r.ReadAsInt32();
                        show.Title = Tools.CleanupText(r.ReadAsString());

                        show.StartTime = new DateTime(1970, 1, 1).Add(TimeSpan.FromSeconds(r.ReadAsInt32().Value));
                        show.EndTime   = show.StartTime.Add(TimeSpan.FromSeconds(Convert.ToDouble(r.ReadAsInt32())));
                        var num = r.ReadAsInt32();
                        shows.Add(show);
                        var depth = r.Depth;
                        while (r.Depth == depth)
                        {
                            r.Read();
                        }
                        r.Read();
                    }
                }
            }
            return(shows);
        }
コード例 #16
0
        public string GetDefaultBadges()
        {
            string       badgeStr = "";
            StringReader jsonStr  = new StringReader(CurrentUser);

            Newtonsoft.Json.JsonTextReader reader = new Newtonsoft.Json.JsonTextReader(jsonStr);

            while (reader.Read())
            {
                System.Console.WriteLine(reader.TokenType);
                if (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                {
                    System.Console.WriteLine(" ==> " + reader.Value.ToString());
                    if (reader.Value.ToString() == "B")
                    {
                        reader.Read();
                        if (reader.TokenType == Newtonsoft.Json.JsonToken.StartArray)
                        {
                            reader.Read();

                            while (reader.TokenType != Newtonsoft.Json.JsonToken.EndArray)
                            {
                                if (badgeStr != "")
                                {
                                    badgeStr += ", ";
                                }
                                badgeStr += "\"" + reader.Value.ToString() + "\"";
                                reader.Read();
                            }

                            break;
                        }
                    }
                }
            }

            return(badgeStr);
        }
コード例 #17
0
ファイル: JsonTestHelper.cs プロジェクト: ryalanms/corefxlab
        public static string NewtonsoftReturnStringHelper(TextReader reader)
        {
            var sb   = new StringBuilder();
            var json = new Newtonsoft.Json.JsonTextReader(reader);

            while (json.Read())
            {
                if (json.Value != null)
                {
                    sb.Append(json.Value).Append(", ");
                }
            }
            return(sb.ToString());
        }
コード例 #18
0
 private static string Get_JSON_Value(string input, string type)
 {
     Newtonsoft.Json.JsonTextReader jtr = new Newtonsoft.Json.JsonTextReader(new StringReader(input));
     while (jtr.Read())
     {
         if (jtr.Value != null)
         {
             if (jtr.ValueType == typeof(string))
             {
                 if ((string)jtr.Value == type)
                 {
                     // Console.WriteLine(jtr.Value);
                     if (jtr.Read() && jtr.Value != null)
                     {
                         //Console.WriteLine(jtr.Value);
                         return((string)jtr.Value);
                     }
                 }
             }
         }
     }
     return("");
 }
コード例 #19
0
ファイル: Program.cs プロジェクト: OSRS/Oncor_OsrsLegacy
        static JObject LoadConfig()
        {
            string config = Path.Combine(AppContext.BaseDirectory, "ServerConfig.json"); //we're using this for our config file -- wouldn't do this for production

            if (File.Exists(config))
            {
                Newtonsoft.Json.JsonTextReader rdr = new Newtonsoft.Json.JsonTextReader(File.OpenText(config)); //read it in for use
                if (rdr.Read())
                {
                    JObject o = JToken.Load(rdr) as JObject;
                    rdr.Close();
                    return(o);
                }
            }
            return(null);
        }
コード例 #20
0
        public string ReaderNewtonsoftReaderReturnString()
        {
            _stream.Seek(0, SeekOrigin.Begin);
            TextReader reader = _reader;

            StringBuilder sb   = new StringBuilder();
            var           json = new Newtonsoft.Json.JsonTextReader(reader);

            while (json.Read())
            {
                if (json.Value != null)
                {
                    sb.Append(json.Value).Append(", ");
                }
            }

            return(sb.ToString());
        }
コード例 #21
0
        protected override void WriteRawJsonToken(
            JsonTokenType jsonTokenType,
            ReadOnlySpan <byte> rawJsonToken)
        {
            string rawJson = Encoding.UTF8.GetString(rawJsonToken);

            Newtonsoft.Json.JsonTextReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(new StringReader(rawJson));
            while (jsonTextReader.Read())
            {
                if (jsonTokenType == JsonTokenType.FieldName)
                {
                    this.writer.WritePropertyName(jsonTextReader.Value as string);
                }
                else
                {
                    this.writer.WriteValue(jsonTextReader.Value);
                }
            }
        }
コード例 #22
0
        public void ReaderNewtonsoftReaderEmptyLoop()
        {
            TextReader reader;

            if (IsUTF8Encoded)
            {
                _stream.Seek(0, SeekOrigin.Begin);
                reader = _reader;
            }
            else
            {
                reader = new StringReader(_jsonString);
            }
            var json = new Newtonsoft.Json.JsonTextReader(reader);

            while (json.Read())
            {
                ;
            }
        }
コード例 #23
0
ファイル: Page.cs プロジェクト: wannanproject/IEMS
        protected Dictionary <string, object> getDetailParam(string ss)
        {
            Dictionary <string, object> result = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            if (string.IsNullOrWhiteSpace(ss))
            {
                return(result);
            }
            Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(ss));
            while (reader.Read())
            {
                if (reader.ValueType == null || reader.Value == null)
                {
                    continue;
                }
                if (reader.TokenType != Newtonsoft.Json.JsonToken.PropertyName)
                {
                    result.Add(reader.Path, reader.Value);
                }
            }
            return(result);
        }
コード例 #24
0
        public object MtJsonParse(ScriptThread thread, object[] arguments)
        {
            var ret  = new MtResult();
            var arg0 = arguments[0] as MtResult;

            arg0.GetValue((o) =>
            {
                var s      = o.Value == null ? "null" : o.Value.ToString();
                var reader = new Newtonsoft.Json.JsonTextReader(new StringReader(s));

                Action readStuff = null;

                readStuff = () =>
                {
                    var hasStuff = reader.Read();
                    if (hasStuff)
                    {
#if DEBUG && !SILVERLIGHT
                        Debug.Print("Token: {0}", reader.Value);
                        Debug.Print("Value Type: {0}", reader.ValueType);
                        Debug.Print("Token Type: {0}", reader.TokenType);
#endif
                        readStuff();
                    }
                    else
                    {
                        reader.Close();
                        ret.SetValue(MtObject.True);
                    }
                };

                readStuff();
            });

            return(ret);
        }
コード例 #25
0
        private async Task <List <AppInfo> > GetAppList()
        {
            var appList = new List <AppInfo>();
            var client  = new System.Net.Http.HttpClient();

            var response = await client.GetAsync(_serviceURI + "Apps");

            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsStringAsync();

                var reader   = new Newtonsoft.Json.JsonTextReader(new StringReader(data));
                var info     = new List <Dictionary <string, string> >();
                var infoItem = new Dictionary <string, string>();
                try
                {
                    while (reader.Read())
                    {
                        if (reader.TokenType == Newtonsoft.Json.JsonToken.EndObject)
                        {
                            info.Add(infoItem);
                            infoItem = new Dictionary <string, string>();
                        }
                        else if (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName && reader.Value != null)
                        {
                            var key = reader.Value.ToString();
                            reader.Read();
                            if (reader.Value != null)
                            {
                                infoItem.Add(key, reader.Value.ToString());
                            }
                            else
                            {
                                infoItem.Add(key, string.Empty);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.Output.AppendText(ex.ToString());
                }
                foreach (var obj in info)
                {
                    var app = new AppInfo();
                    app.Name = obj["Name"];
                    app.PackageFamilyName = obj["PackageFamilyName"];
                    app.AppxUrl           = obj["AppxUrl"];
                    app.Version           = obj["Version"];
                    app.Description       = obj["Description"];
                    app.ImageUrl          = obj["LogoUrl"];
                    if (string.IsNullOrEmpty(app.ImageUrl))
                    {
                        app.ImageUrl = "Assets/DarkGray.png";
                    }
                    app.InstallMode = obj["InstallMode"];
                    appList.Add(app);
                }
            }
            return(appList);
        }
コード例 #26
0
        private void recv(string msg)
        {
            if (State == WebSockState.Connecting)
            {
                if (ci.cii == null)
                {
                    ci.cii = new Dictionary<string, string>();
                    ci.cii.Add("nick", ci.nick);
                    ci.cii.Add("room", ci.room);
                }

                Send(make_msg("join", ci.cii));
                State = WebSockState.Connected;
            }
            else if (msg == "2::")
            {
                Send("2::");
            }
            else
            {
                msg = msg.Substring(4);
                Newtonsoft.Json.JsonTextReader JTR = new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(msg));

                char name_type = '\0';
                Dictionary<string, string> args = new Dictionary<string, string>(5);

                while (JTR.Read())
                {
                    switch (JTR.ValueType == typeof(string) ? (string)JTR.Value : "")
                    {
                        case "name":
                            name_type = JTR.ReadAsString()[0];
                            break;
                        case "args":
                            switch (name_type)
                            {
                                case 'u':
                                    JTR.Read();
                                    JTR.Read();
                                    JTR.Read();

                                    switch (JTR.ReadAsString())
                                    {
                                        case "l":
                                            Dictionary<string, user_info> ui = new Dictionary<string,user_info>(8);
                                            JTR.Read();
                                            JTR.Read();
                                            while (JTR.Read())
                                            {
                                                string nick = (string)JTR.Value;
                                                user_info lui = new user_info();
                                                JTR.Read();
                                                while (JTR.Read() && JTR.Value != null && JTR.ValueType.ToString() != "EndObject")
                                                {
                                                    switch ((string)JTR.Value)
                                                    {
                                                        case "a":
                                                            lui.admin = JTR.ReadAsInt32() == 0 ? false : true;
                                                            break;
                                                        case "t":
                                                            lui.conn = (DateTime)JTR.ReadAsDateTime();
                                                            break;
                                                        case "m":
                                                            lui.mb_id = JTR.ReadAsString();
                                                            break;
                                                        case "l":
                                                            lui.login = JTR.ReadAsInt32() == 1 ? false : true;
                                                            break;

                                                        default:
                                                            JTR.Read();
                                                            break;
                                                    }
                                                }

                                                if(nick != null) ui.Add(nick, lui);
                                            }
                                            break;
                                        default:
                                            break;
                                    }

                                    break;

                                case 'c':
                                    JTR.Skip();
                                    JTR.Skip();

                                    while (JTR.Read())
                                    {
                                        args.Add((string)JTR.Value, JTR.ReadAsString());
                                    }
                                    break;

                                default:
                                    break;
                            }

                            break;

                        default:
                            break;
                    }
                }
            }
        }
コード例 #27
0
        public static Madingley.Common.Configuration Deserialize(TextReader sr)
        {
            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.FunctionalGroupDefinition> JsonReadFunctionalGroupDefinition = (reader) =>
            {
                var ret = new Madingley.Common.FunctionalGroupDefinition();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                        case "Definitions": ret.Definitions = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadString); break;
                        case "Properties": ret.Properties = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadDouble); break;
                        default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return ret;
            };

            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.FunctionalGroupDefinitions> JsonReadFunctionalGroupDefinitions = (reader) =>
                {
                    var ret = new Madingley.Common.FunctionalGroupDefinitions();

                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                    while (reader.Read() &&
                        reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                    {
                        Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                        Debug.Assert(reader.ValueType == typeof(string));

                        var property = Convert.ToString(reader.Value);
                        reader.Read();

                        switch (property)
                        {
                            case "Data": ret.Data = Common.Reader.ReadArray(reader, JsonReadFunctionalGroupDefinition); break;
                            case "Definitions": ret.Definitions = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;
                            case "Properties": ret.Properties = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;
                            default: throw new Exception(string.Format("Unexpected property: {0}", property));
                        }
                    }

                    return ret;
                };

            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.ScenarioParameter> JsonReadScenarioParameter = (reader) =>
            {
                var ret = new Madingley.Common.ScenarioParameter();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                        case "ParamString": ret.ParamString = Common.Reader.ReadString(reader); break;
                        case "ParamDouble1": ret.ParamDouble1 = Common.Reader.ReadDouble(reader); break;
                        case "ParamDouble2": ret.ParamDouble2 = Common.Reader.ReadDouble(reader); break;
                        default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return ret;
            };

            Func<Newtonsoft.Json.JsonTextReader, IDictionary<string, Madingley.Common.ScenarioParameter>> JsonReadKVPScenarioParameter = (reader) =>
            {
                var ret = new Dictionary<string, Madingley.Common.ScenarioParameter>();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var key = Convert.ToString(reader.Value);
                    reader.Read();
                    var value = JsonReadScenarioParameter(reader);

                    ret.Add(key, value);
                }

                return ret;
            };

            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.ScenarioParameters> JsonReadScenarioParameters = (reader) =>
                {
                    var ret = new Madingley.Common.ScenarioParameters();

                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                    while (reader.Read() &&
                        reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                    {
                        Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                        Debug.Assert(reader.ValueType == typeof(string));

                        var property = Convert.ToString(reader.Value);
                        reader.Read();

                        switch (property)
                        {
                            case "Label": ret.Label = Common.Reader.ReadString(reader); break;
                            case "SimulationNumber": ret.SimulationNumber = Common.Reader.ReadInt(reader); break;
                            case "Parameters": ret.Parameters = JsonReadKVPScenarioParameter(reader); break;
                            default: throw new Exception(string.Format("Unexpected property: {0}", property));
                        }
                    }

                    return ret;
                };

            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.EcologicalParameters> JsonReadEcologicalParameters = (reader) =>
                {
                    var ret = new Madingley.Common.EcologicalParameters();

                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                    while (reader.Read() &&
                        reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                    {
                        Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                        Debug.Assert(reader.ValueType == typeof(string));

                        var property = Convert.ToString(reader.Value);
                        reader.Read();

                        switch (property)
                        {
                            case "Parameters": ret.Parameters = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadDouble); break;
                            case "TimeUnits": ret.TimeUnits = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;
                            default: throw new Exception(string.Format("Unexpected property: {0}", property));
                        }
                    }

                    return ret;
                };

            var configuration = new Madingley.Common.Configuration();

            using (var reader = new Newtonsoft.Json.JsonTextReader(sr))
            {
                reader.Read();
                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                        case "GlobalModelTimeStepUnit": configuration.GlobalModelTimeStepUnit = Common.Reader.ReadString(reader); break;
                        case "NumTimeSteps": configuration.NumTimeSteps = Common.Reader.ReadInt(reader); break;
                        case "BurninTimeSteps": configuration.BurninTimeSteps = Common.Reader.ReadInt(reader); break;
                        case "ImpactTimeSteps": configuration.ImpactTimeSteps = Common.Reader.ReadInt(reader); break;
                        case "RecoveryTimeSteps": configuration.RecoveryTimeSteps = Common.Reader.ReadInt(reader); break;
                        case "RunCellsInParallel": configuration.RunCellsInParallel = Common.Reader.ReadBoolean(reader); break;
                        case "RunSimulationsInParallel": configuration.RunSimulationsInParallel = Common.Reader.ReadBoolean(reader); break;
                        case "RunRealm": configuration.RunRealm = Common.Reader.ReadString(reader); break;
                        case "DrawRandomly": configuration.DrawRandomly = Common.Reader.ReadBoolean(reader); break;
                        case "ExtinctionThreshold": configuration.ExtinctionThreshold = Common.Reader.ReadDouble(reader); break;
                        case "MaxNumberOfCohorts": configuration.MaxNumberOfCohorts = Common.Reader.ReadInt(reader); break;
                        case "DispersalOnly": configuration.DispersalOnly = Common.Reader.ReadBoolean(reader); break;
                        case "DispersalOnlyType": configuration.DispersalOnlyType = Common.Reader.ReadString(reader); break;
                        case "PlanktonDispersalThreshold": configuration.PlanktonDispersalThreshold = Common.Reader.ReadDouble(reader); break;
                        case "CohortFunctionalGroupDefinitions": configuration.CohortFunctionalGroupDefinitions = JsonReadFunctionalGroupDefinitions(reader); break;
                        case "StockFunctionalGroupDefinitions": configuration.StockFunctionalGroupDefinitions = JsonReadFunctionalGroupDefinitions(reader); break;
                        case "ImpactCellIndices": configuration.ImpactCellIndices = Common.Reader.ReadArray(reader, Common.Reader.ReadInt); break;
                        case "ImpactAll": configuration.ImpactAll = Common.Reader.ReadBoolean(reader); break;
                        case "ScenarioParameters": configuration.ScenarioParameters = Common.Reader.ReadArray(reader, JsonReadScenarioParameters).ToList(); break;
                        case "ScenarioIndex": configuration.ScenarioIndex = Common.Reader.ReadInt(reader); break;
                        case "Simulation": configuration.Simulation = Common.Reader.ReadInt(reader); break;
                        case "EcologicalParameters": configuration.EcologicalParameters = JsonReadEcologicalParameters(reader); break;
                        case "FileNames": configuration.FileNames = Common.Reader.ReadArray(reader, Common.Reader.ReadString).ToList(); break;
                        default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }
            }

            return configuration;
        }
コード例 #28
0
        public void DeserializeRequest(Message message, object[] parameters)
        {
            //如果是上传的content-type,则不作json处理
            var    headers       = ((HttpRequestMessageProperty)(message.Properties[HttpRequestMessageProperty.Name])).Headers;
            string contenttype   = headers["Content-type"];
            string contentLength = headers["Content-Length"];

            if (contenttype != null && contenttype.StartsWith("multipart/form-data"))
            {
                //获得附件分割边界字符串
                string boundary = contenttype.Substring(contenttype.IndexOf("boundary=") + "boundary=".Length);
                int    len      = int.Parse(contentLength);
                //获得方法的参数
                var paramts        = operation.SyncMethod.GetParameters();
                int streamtypeIndx = -1;
                int bodyheaderlen  = 0;
                //找到Stream类型的参数
                for (streamtypeIndx = 0; streamtypeIndx < paramts.Length && streamtypeIndx < parameters.Length; streamtypeIndx++)
                {
                    if (paramts[streamtypeIndx].ParameterType == typeof(Stream))
                    {
                        var stream = message.GetBody <Stream>();
                        //定位到第一个0D0A0D0A)
                        //sb= new StringBuilder(512);
                        int datimes = 0;//回车换行次数
                        int c       = 0;
                        while (datimes != 4)
                        {
                            c = stream.ReadByte();
                            if (c == -1)
                            {
                                break;
                            }
                            if (c == 0x0d && (datimes == 0 || datimes == 2))
                            {
                                datimes++;
                            }
                            else if (c == 0x0a && (datimes == 1 || datimes == 3))
                            {
                                datimes++;
                            }
                            else
                            {
                                datimes = 0;
                            }

                            bodyheaderlen++;
                        }
                        if (c == -1)
                        {
                            continue;
                        }
                        //计算实际附件大小
                        int          fileLength = len - bodyheaderlen - boundary.Length - 6;
                        int          remain     = fileLength;
                        MemoryStream filestream = new MemoryStream(fileLength);
                        byte[]       buffer     = new byte[8192];
                        int          readed     = 0;
                        while (remain > 0)
                        {
                            readed  = stream.Read(buffer, 0, remain > 8192 ? 8192 : remain);
                            remain -= readed;
                            filestream.Write(buffer, 0, readed);
                        }
                        stream.Close();
                        filestream.Seek(0, SeekOrigin.Begin);
                        //MemoryStream stream = new MemoryStream(message.GetReaderAtBodyContents().ReadElementContentAsBinHex());
                        parameters[streamtypeIndx] = filestream;
                    }
                    else
                    {
                        parameters[streamtypeIndx] = headers[paramts[streamtypeIndx].Name];
                    }
                }

                return;
            }

            object bodyFormatProperty;

            if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) ||
                (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw)
            {
                throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?");
            }

            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            //begin 张辽阔 2017-01-06 添加
            bodyReader.Quotas.MaxArrayLength = 163840 * 2;
            //end 张辽阔 2017-01-06 添加
            bodyReader.ReadStartElement("Binary");
            byte[]       rawBody = bodyReader.ReadContentAsBase64();
            MemoryStream ms      = new MemoryStream(rawBody);

            StreamReader sr = new StreamReader(ms);

            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer()
            {
                DateFormatString = "yyyy-MM-dd HH:mm:ss"
            };
            if (parameters.Length == 1)
            {
                // single parameter, assuming bare
                parameters[0] = serializer.Deserialize(sr, operation.Messages[0].Body.Parts[0].Type);
            }
            else
            {
                // multiple parameter, needs to be wrapped
                Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(sr);
                reader.Read();
                if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject)
                {
                    throw new InvalidOperationException("Input needs to be wrapped in an object");
                }

                reader.Read();
                while (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                {
                    string parameterName = reader.Value as string;
                    reader.Read();
                    if (this.parameterNames.ContainsKey(parameterName))
                    {
                        int parameterIndex = this.parameterNames[parameterName];
                        parameters[parameterIndex] = serializer.Deserialize(reader, this.operation.Messages[0].Body.Parts[parameterIndex].Type);
                    }
                    else
                    {
                        reader.Skip();
                    }

                    reader.Read();
                }

                reader.Close();
            }

            sr.Close();
            ms.Close();
        }
コード例 #29
0
        public static void updateDb(String filename)
        {
            Console.WriteLine(idList.Count);
            Console.WriteLine(hashList.Count);


            string        jsonDoc = "";
            List <String> batch   = new List <string>();
            int           i       = 0;

            lookUpTable = idList.ToDictionary(x => x, x => x);
            var hashListDictionary = hashList.ToDictionary(x => x, x => x);

            using (var streamReader = new StreamReader(filename))
            {
                using (var reader = new Newtonsoft.Json.JsonTextReader(streamReader))
                {
                    while (reader.Read())
                    {
                        if (reader.TokenType == Newtonsoft.Json.JsonToken.StartArray)
                        {
                            //Console.WriteLine(reader.TokenType);
                            while (reader.Read())
                            {
                                if (reader.TokenType == Newtonsoft.Json.JsonToken.StartObject)
                                {
                                    Object obj = new Newtonsoft.Json.JsonSerializer().Deserialize(reader);
                                    jsonDoc = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
                                }

                                batch.Add(jsonDoc);
                                //Console.WriteLine(batch.Count);
                                if (batch.Count >= 10000)
                                {
                                    i += 10000;
                                    MD5 md5Hash = MD5.Create();

                                    // Insert some data

                                    foreach (var document in batch)
                                    {
                                        var jo   = JObject.Parse(document);
                                        var id   = jo["properties"]["gml_id"].ToString();
                                        var hash = GetMd5Hash(md5Hash, document);
                                        //Compare data
                                        //bool matchingId = idList.AsParallel().Any(s => s.Contains(id));

                                        bool matchingId = lookUpTable.ContainsKey(id);

                                        if (matchingId)
                                        {
                                            // bool matchingHash = hashList.AsParallel().Any(s => s.Contains(hash));
                                            var matchingHash = hashListDictionary.ContainsKey(hash);
                                            if (!matchingHash)
                                            {
                                                using (var cmd = new NpgsqlCommand("UPDATE geo SET data = :userdata, hash = :userhash WHERE id = :userid ", conn))
                                                {
                                                    cmd.Parameters.Add(new NpgsqlParameter("userdata", NpgsqlDbType.Json));
                                                    cmd.Parameters.Add(new NpgsqlParameter("userid", NpgsqlDbType.Text));
                                                    cmd.Parameters.Add(new NpgsqlParameter("userhash", NpgsqlDbType.Text));

                                                    cmd.Parameters[0].Value = document;
                                                    cmd.Parameters[1].Value = id;
                                                    cmd.Parameters[2].Value = hash;

                                                    cmd.Prepare();
                                                    cmd.ExecuteNonQuery();

                                                    Console.WriteLine("Object updated " + id);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            using (var cmd = new NpgsqlCommand("INSERT INTO geo(data,id,hash) VALUES (:userdata,:userid,:userhash) ", conn))
                                            {
                                                cmd.Parameters.Add(new NpgsqlParameter("userdata", NpgsqlDbType.Json));
                                                cmd.Parameters.Add(new NpgsqlParameter("userid", NpgsqlDbType.Text));
                                                cmd.Parameters.Add(new NpgsqlParameter("userhash", NpgsqlDbType.Text));

                                                cmd.Parameters[0].Value = document;
                                                cmd.Parameters[1].Value = id;
                                                cmd.Parameters[2].Value = hash;

                                                cmd.Prepare();
                                                cmd.ExecuteNonQuery();

                                                Console.WriteLine("Object inserted " + id);
                                            }
                                        }
                                    }
                                    batch.Clear();
                                    Console.WriteLine(i);
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #30
0
        public void DeserializeRequest(Message message, object[] parameters)
        {
            object bodyFormatProperty;

            if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) ||
                (bodyFormatProperty as WebBodyFormatMessageProperty) == null ||
                (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw)
            {
                throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?");
            }

            var bodyReader = message.GetReaderAtBodyContents();

            bodyReader.ReadStartElement("Binary");

            var rawBody = bodyReader.ReadContentAsBase64();

            using (var ms = new MemoryStream(rawBody))
            {
                using (var sr = new StreamReader(ms))
                {
                    var serializer = NewtonsoftJsonSettings.GetSerializer();

                    if (parameters.Length == 1)
                    {
                        if (m_operation.Messages[0].Body.Parts[0].Type == typeof(string))
                        {
                            var str         = sr.ReadToEnd();
                            var queryString = HttpUtility.ParseQueryString(str);
                            if (queryString.AllKeys.Contains(m_operation.Messages[0].Body.Parts[0].Name))
                            {
                                parameters[0] = Convert.ChangeType(queryString[m_operation.Messages[0].Body.Parts[0].Name], m_operation.Messages[0].Body.Parts[0].Type);
                            }
                        }
                        else
                        {
                            parameters[0] = serializer.Deserialize(sr, m_operation.Messages[0].Body.Parts[0].Type);
                        }
                    }
                    else
                    {
                        // multiple parameter, needs to be wrapped
                        Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(sr);
                        reader.Read();
                        if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject)
                        {
                            throw new InvalidOperationException("Input needs to be wrapped in an object");
                        }

                        reader.Read();
                        while (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                        {
                            var parameterName = reader.Value as string;

                            if (parameterName == null)
                            {
                                throw new InvalidOperationException("The object contained a parameter, however the value was null.");
                            }

                            reader.Read();
                            if (this.m_parameterNames.ContainsKey(parameterName))
                            {
                                int parameterIndex = this.m_parameterNames[parameterName];
                                parameters[parameterIndex] = serializer.Deserialize(reader,
                                                                                    this.m_operation.Messages[0].Body.Parts[parameterIndex].Type);
                            }
                            else
                            {
                                reader.Skip();
                            }

                            reader.Read();
                        }

                        reader.Close();
                    }
                }
            }
        }
コード例 #31
0
ファイル: ModelState.cs プロジェクト: mikeharfoot/Madingley
        public static Madingley.Common.ModelState Deserialize(TextReader sr)
        {
            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.Cohort> JsonReadCohort = (reader) =>
            {
                var ret = new Madingley.Common.Cohort();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                        case "FunctionalGroupIndex": ret.FunctionalGroupIndex = Common.Reader.ReadInt(reader); break;
                        case "BirthTimeStep": ret.BirthTimeStep = Common.Reader.ReadInt(reader); break;
                        case "MaturityTimeStep": ret.MaturityTimeStep = Common.Reader.ReadInt(reader); break;
                        case "IDs": ret.IDs = Common.Reader.ReadArray(reader, Common.Reader.ReadInt).ToList(); break;
                        case "JuvenileMass": ret.JuvenileMass = Common.Reader.ReadDouble(reader); break;
                        case "AdultMass": ret.AdultMass = Common.Reader.ReadDouble(reader); break;
                        case "IndividualBodyMass": ret.IndividualBodyMass = Common.Reader.ReadDouble(reader); break;
                        case "IndividualReproductivePotentialMass": ret.IndividualReproductivePotentialMass = Common.Reader.ReadDouble(reader); break;
                        case "MaximumAchievedBodyMass": ret.MaximumAchievedBodyMass = Common.Reader.ReadDouble(reader); break;
                        case "Abundance": ret.Abundance = Common.Reader.ReadDouble(reader); break;
                        case "Merged": ret.Merged = Common.Reader.ReadBoolean(reader); break;
                        case "ProportionTimeActive": ret.ProportionTimeActive = Common.Reader.ReadDouble(reader); break;
                        case "TrophicIndex": ret.TrophicIndex = Common.Reader.ReadDouble(reader); break;
                        case "LogOptimalPreyBodySizeRatio": ret.LogOptimalPreyBodySizeRatio = Common.Reader.ReadDouble(reader); break;
                        default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return ret;
            };

            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.Stock> JsonReadStock = (reader) =>
            {
                var ret = new Madingley.Common.Stock();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                        case "FunctionalGroupIndex": ret.FunctionalGroupIndex = Common.Reader.ReadInt(reader); break;
                        case "IndividualBodyMass": ret.IndividualBodyMass = Common.Reader.ReadDouble(reader); break;
                        case "TotalBiomass": ret.TotalBiomass = Common.Reader.ReadDouble(reader); break;
                        default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return ret;
            };

            Func<Newtonsoft.Json.JsonTextReader, IDictionary<string, double[]>> JsonReadCellEnvironment = (reader) =>
            {
                var ret = new Dictionary<string, double[]>();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var key = Convert.ToString(reader.Value);
                    reader.Read();
                    var value = Common.Reader.ReadArray(reader, Common.Reader.ReadDouble);

                    ret.Add(key, value.ToArray());
                }

                return ret;
            };

            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.GridCell> JsonReadGridCell = (reader) =>
            {
                var ret = new Madingley.Common.GridCell();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                        case "Latitude": ret.Latitude = Common.Reader.ReadDouble(reader); break;
                        case "Longitude": ret.Longitude = Common.Reader.ReadDouble(reader); break;
                        case "Cohorts": ret.Cohorts = Common.Reader.ReadArray(reader, r => Common.Reader.ReadArray(r, JsonReadCohort)).ToList(); break;
                        case "Stocks": ret.Stocks = Common.Reader.ReadArray(reader, r => Common.Reader.ReadArray(r, JsonReadStock)).ToList(); break;
                        case "Environment": ret.Environment = JsonReadCellEnvironment(reader); break;
                        default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return ret;
            };

            var modelState = new Madingley.Common.ModelState();

            using (var reader = new Newtonsoft.Json.JsonTextReader(sr))
            {
                reader.Read();
                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                        case "TimestepsComplete": modelState.TimestepsComplete = Common.Reader.ReadInt(reader); break;
                        case "GlobalDiagnosticVariables": modelState.GlobalDiagnosticVariables = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadDouble); break;
                        case "GridCells": modelState.GridCells = Common.Reader.ReadArray(reader, JsonReadGridCell).ToList(); break;
                        case "NextCohortID": modelState.NextCohortID = Common.Reader.ReadLong(reader); break;
                        default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }
            }

            return modelState;
        }
コード例 #32
0
        public static Madingley.Common.Configuration Deserialize(TextReader sr)
        {
            Func <Newtonsoft.Json.JsonTextReader, Madingley.Common.FunctionalGroupDefinition> JsonReadFunctionalGroupDefinition = (reader) =>
            {
                var ret = new Madingley.Common.FunctionalGroupDefinition();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "Definitions": ret.Definitions = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadString); break;

                    case "Properties": ret.Properties = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadDouble); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return(ret);
            };

            Func <Newtonsoft.Json.JsonTextReader, Madingley.Common.FunctionalGroupDefinitions> JsonReadFunctionalGroupDefinitions = (reader) =>
            {
                var ret = new Madingley.Common.FunctionalGroupDefinitions();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "Data": ret.Data = Common.Reader.ReadArray(reader, JsonReadFunctionalGroupDefinition); break;

                    case "Definitions": ret.Definitions = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;

                    case "Properties": ret.Properties = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return(ret);
            };

            Func <Newtonsoft.Json.JsonTextReader, Madingley.Common.ScenarioParameter> JsonReadScenarioParameter = (reader) =>
            {
                var ret = new Madingley.Common.ScenarioParameter();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "ParamString": ret.ParamString = Common.Reader.ReadString(reader); break;

                    case "ParamDouble1": ret.ParamDouble1 = Common.Reader.ReadDouble(reader); break;

                    case "ParamDouble2": ret.ParamDouble2 = Common.Reader.ReadDouble(reader); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return(ret);
            };

            Func <Newtonsoft.Json.JsonTextReader, IDictionary <string, Madingley.Common.ScenarioParameter> > JsonReadKVPScenarioParameter = (reader) =>
            {
                var ret = new Dictionary <string, Madingley.Common.ScenarioParameter>();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var key = Convert.ToString(reader.Value);
                    reader.Read();
                    var value = JsonReadScenarioParameter(reader);

                    ret.Add(key, value);
                }

                return(ret);
            };

            Func <Newtonsoft.Json.JsonTextReader, Madingley.Common.ScenarioParameters> JsonReadScenarioParameters = (reader) =>
            {
                var ret = new Madingley.Common.ScenarioParameters();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "Label": ret.Label = Common.Reader.ReadString(reader); break;

                    case "SimulationNumber": ret.SimulationNumber = Common.Reader.ReadInt(reader); break;

                    case "Parameters": ret.Parameters = JsonReadKVPScenarioParameter(reader); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return(ret);
            };

            Func <Newtonsoft.Json.JsonTextReader, Madingley.Common.EcologicalParameters> JsonReadEcologicalParameters = (reader) =>
            {
                var ret = new Madingley.Common.EcologicalParameters();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "Parameters": ret.Parameters = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadDouble); break;

                    case "TimeUnits": ret.TimeUnits = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return(ret);
            };

            var configuration = new Madingley.Common.Configuration();

            using (var reader = new Newtonsoft.Json.JsonTextReader(sr))
            {
                reader.Read();
                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "GlobalModelTimeStepUnit": configuration.GlobalModelTimeStepUnit = Common.Reader.ReadString(reader); break;

                    case "NumTimeSteps": configuration.NumTimeSteps = Common.Reader.ReadInt(reader); break;

                    case "BurninTimeSteps": configuration.BurninTimeSteps = Common.Reader.ReadInt(reader); break;

                    case "ImpactTimeSteps": configuration.ImpactTimeSteps = Common.Reader.ReadInt(reader); break;

                    case "RecoveryTimeSteps": configuration.RecoveryTimeSteps = Common.Reader.ReadInt(reader); break;

                    case "RunCellsInParallel": configuration.RunCellsInParallel = Common.Reader.ReadBoolean(reader); break;

                    case "RunSimulationsInParallel": configuration.RunSimulationsInParallel = Common.Reader.ReadBoolean(reader); break;

                    case "RunRealm": configuration.RunRealm = Common.Reader.ReadString(reader); break;

                    case "DrawRandomly": configuration.DrawRandomly = Common.Reader.ReadBoolean(reader); break;

                    case "ExtinctionThreshold": configuration.ExtinctionThreshold = Common.Reader.ReadDouble(reader); break;

                    case "MaxNumberOfCohorts": configuration.MaxNumberOfCohorts = Common.Reader.ReadInt(reader); break;

                    case "DispersalOnly": configuration.DispersalOnly = Common.Reader.ReadBoolean(reader); break;

                    case "DispersalOnlyType": configuration.DispersalOnlyType = Common.Reader.ReadString(reader); break;

                    case "PlanktonDispersalThreshold": configuration.PlanktonDispersalThreshold = Common.Reader.ReadDouble(reader); break;

                    case "CohortFunctionalGroupDefinitions": configuration.CohortFunctionalGroupDefinitions = JsonReadFunctionalGroupDefinitions(reader); break;

                    case "StockFunctionalGroupDefinitions": configuration.StockFunctionalGroupDefinitions = JsonReadFunctionalGroupDefinitions(reader); break;

                    case "ImpactCellIndices": configuration.ImpactCellIndices = Common.Reader.ReadArray(reader, Common.Reader.ReadInt); break;

                    case "ImpactAll": configuration.ImpactAll = Common.Reader.ReadBoolean(reader); break;

                    case "ScenarioParameters": configuration.ScenarioParameters = Common.Reader.ReadArray(reader, JsonReadScenarioParameters).ToList(); break;

                    case "ScenarioIndex": configuration.ScenarioIndex = Common.Reader.ReadInt(reader); break;

                    case "Simulation": configuration.Simulation = Common.Reader.ReadInt(reader); break;

                    case "EcologicalParameters": configuration.EcologicalParameters = JsonReadEcologicalParameters(reader); break;

                    case "FileNames": configuration.FileNames = Common.Reader.ReadArray(reader, Common.Reader.ReadString).ToList(); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }
            }

            return(configuration);
        }
コード例 #33
0
        public static Madingley.Common.Environment Deserialize(TextReader sr)
        {
            Func<Newtonsoft.Json.JsonTextReader, Tuple<int, int>> JsonReadFocusCell = (reader) =>
            {
                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartArray);

                reader.Read();
                var item1 = Common.Reader.ReadInt(reader);

                reader.Read();
                var item2 = Common.Reader.ReadInt(reader);

                reader.Read();
                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.EndArray);

                return Tuple.Create(item1, item2);
            };

            Func<Newtonsoft.Json.JsonTextReader, IDictionary<string, double[]>> JsonReadCellEnvironment = (reader) =>
            {
                var ret = new Dictionary<string, double[]>();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var key = Convert.ToString(reader.Value);
                    reader.Read();
                    var value = Common.Reader.ReadArray(reader, Common.Reader.ReadDouble);

                    ret.Add(key, value.ToArray());
                }

                return ret;
            };

            var environment = new Madingley.Common.Environment();

            using (var reader = new Newtonsoft.Json.JsonTextReader(sr))
            {
                reader.Read();
                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                        case "CellSize": environment.CellSize = Common.Reader.ReadDouble(reader); break;
                        case "BottomLatitude": environment.BottomLatitude = Common.Reader.ReadDouble(reader); break;
                        case "TopLatitude": environment.TopLatitude = Common.Reader.ReadDouble(reader); break;
                        case "LeftmostLongitude": environment.LeftmostLongitude = Common.Reader.ReadDouble(reader); break;
                        case "RightmostLongitude": environment.RightmostLongitude = Common.Reader.ReadDouble(reader); break;
                        case "Units": environment.Units = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadString); break;
                        case "SpecificLocations": environment.SpecificLocations = Common.Reader.ReadBoolean(reader); break;
                        case "FocusCells": environment.FocusCells = Common.Reader.ReadArray(reader, JsonReadFocusCell).ToList(); break;
                        case "CellEnvironment": environment.CellEnvironment = Common.Reader.ReadArray(reader, JsonReadCellEnvironment).ToList(); break;
                        case "FileNames": environment.FileNames = Common.Reader.ReadArray(reader, Common.Reader.ReadString).ToList(); break;
                        default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }
            }

            return environment;
        }
コード例 #34
0
ファイル: WebHttpJsonElement.cs プロジェクト: ognjenm/egle
            public void DeserializeRequest(Message message, object[] parameters)
            {
                object bodyFormatProperty;
                if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) ||
                    (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw)
                {
                    throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?");
                }

                var bodyReader = message.GetReaderAtBodyContents();
                bodyReader.ReadStartElement("Binary");
                var rawBody = bodyReader.ReadContentAsBase64();
                var ms = new MemoryStream(rawBody);

                var sr = new StreamReader(ms);
                var serializer = new Newtonsoft.Json.JsonSerializer();
                if (parameters.Length == 1)
                {
                    // single parameter, assuming bare
                    parameters[0] = serializer.Deserialize(sr, operation.Messages[0].Body.Parts[0].Type);
                }
                else
                {
                    // multiple parameter, needs to be wrapped
                    Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(sr);
                    reader.Read();
                    if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject)
                    {
                        throw new InvalidOperationException("Input needs to be wrapped in an object");
                    }

                    reader.Read();
                    while (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                    {
                        var parameterName = reader.Value as string;
                        reader.Read();
                        if (parameterNames.ContainsKey(parameterName))
                        {
                            var parameterIndex = parameterNames[parameterName];
                            parameters[parameterIndex] = serializer.Deserialize(reader, operation.Messages[0].Body.Parts[parameterIndex].Type);
                        }
                        else
                        {
                            reader.Skip();
                        }

                        reader.Read();
                    }

                    //Attach parameters retrieved from the Uri
                    var templateMatchResults = (UriTemplateMatch)message.Properties["UriTemplateMatchResults"];
                    foreach (var parameterName in parameterNames.Where(parameterName => parameters[parameterName.Value] == null))
                    {
                        if(templateMatchResults.BoundVariables.AllKeys.Contains(parameterName.Key.ToUpper()))
                            parameters[parameterName.Value] = templateMatchResults.BoundVariables[parameterName.Key.ToUpper()];
                    }

                    reader.Close();
                }

                sr.Close();
                ms.Close();
            }
コード例 #35
0
        protected virtual void OnInstalling(object sender, DoWorkEventArgs e)
        {
            //return;
            TransarmWorkerInfo         seed      = e.Argument as TransarmWorkerInfo;
            PatchNotificationEventArgs seedEvent = seed.Params as PatchNotificationEventArgs;

            string pso2datadir            = DefaultValues.Directory.PSO2Win32Data;
            string largefilesBackupFolder = Path.Combine(pso2datadir, DefaultValues.Directory.PSO2Win32DataBackup, DefaultValues.Directory.Backup.LargeFiles);

            this.OnCurrentStepChanged(new StepEventArgs(string.Format(LanguageManager.GetMessageText("Begin0PatchFiles", "Extracting {0} data"), Infos.DefaultValues.AIDA.Strings.LargeFilesPatchCalled)));
            string myPatcher = Path.Combine(seed.Path, Infos.DefaultValues.AIDA.Tweaker.TransArmThingiesOrWatever.TransAmEXE);
            string my7zDB    = Path.Combine(seed.Path, Infos.DefaultValues.AIDA.Tweaker.TransArmThingiesOrWatever.LargeFilesDB + "zip");
            string myDB      = string.Empty;
            bool   isOkay    = false;
            var    result    = AbstractExtractor.ExtractZip(my7zDB, seed.Path, null);

            isOkay = result.IsSuccess;
            myDB   = result.SuccessItems[0].Key;
            File.Delete(my7zDB);
            if (isOkay)
            {
                if (false)
                {
                    this.OnCurrentStepChanged(new StepEventArgs(string.Format(LanguageManager.GetMessageText("BeginRestoring0PatchFiles", "Getting {0} filelist"), Infos.DefaultValues.AIDA.Strings.LargeFilesPatchCalled)));
                    string rawtbl      = this.myWebClient_ForAIDA.DownloadString(Classes.AIDA.WebPatches.PatchesFileListInfos);
                    string sourceTable = string.Empty;
                    using (var theTextReader = new StringReader(rawtbl))
                        using (var jsonReader = new Newtonsoft.Json.JsonTextReader(theTextReader))
                            while (jsonReader.Read())
                            {
                                if (jsonReader.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                                {
                                    if (jsonReader.Value is string && (jsonReader.Value as string).ToLower() == "largefileslist")
                                    {
                                        sourceTable = jsonReader.ReadAsString();
                                    }
                                }
                            }

                    string[] tbl_files = AIDA.StringToTableString(sourceTable);
                    string   originalFile, backupFile, currentIndexString;
                    this.OnCurrentStepChanged(new StepEventArgs(string.Format(LanguageManager.GetMessageText("Creating0PatchBackup", "Creating backup for {0} files"), Infos.DefaultValues.AIDA.Strings.LargeFilesPatchCalled)));
                    int total = tbl_files.Length;
                    this.OnCurrentTotalProgressChanged(new ProgressEventArgs(total));
                    Directory.CreateDirectory(largefilesBackupFolder);
                    for (int i = 0; i < tbl_files.Length; i++)
                    {
                        currentIndexString = tbl_files[i];
                        originalFile       = Path.Combine(pso2datadir, currentIndexString);
                        backupFile         = Path.Combine(largefilesBackupFolder, currentIndexString);
                        File.Copy(originalFile, backupFile, true);
                        this.OnCurrentProgressChanged(new ProgressEventArgs(i + 1));
                    }
                }

                this.OnCurrentStepChanged(new StepEventArgs(LanguageManager.GetMessageText("CallTransarmPatcherBackup", "Call patcher and wait for patcher finish the job")));
                this.OnProgressBarStateChanged(new ProgressBarStateChangedEventArgs(Forms.MyMainMenu.ProgressBarVisibleState.Infinite));
                patcherProcess = Infos.CommonMethods.MakeProcess(myPatcher);
                //-i "Backup/" -h largefiles-10-7-2016 lf.stripped.db "Out"
                string MyBaseDateString = "largefiles-" + seed.Date.Month.ToString() + "-" + seed.Date.Day.ToString() + "-" + seed.Date.Year.ToString();
                //lf.stripped.db
                //Infos.DefaultValues.AIDA.Tweaker.TransArmThingiesOrWatever.LargeFilesBackupFolder

                List <string> myParams = new List <string>();
                myParams.Add(Infos.DefaultValues.AIDA.Tweaker.TransArmThingiesOrWatever.paramNodeForBackupOutput);
                myParams.Add(Infos.DefaultValues.AIDA.Tweaker.TransArmThingiesOrWatever.LargeFilesBackupFolder);

                myParams.Add(Infos.DefaultValues.AIDA.Tweaker.TransArmThingiesOrWatever.paramNodeForOutput);
                myParams.Add(MyBaseDateString);
                myParams.Add(myDB);
                myParams.Add(Infos.DefaultValues.AIDA.Tweaker.TransArmThingiesOrWatever.ValidPath(DefaultValues.Directory.PSO2Win32Data));

                string pso2bin  = DefaultValues.Directory.PSO2Dir;
                string veda     = Path.Combine(pso2bin, Infos.DefaultValues.AIDA.Tweaker.TransArmThingiesOrWatever.VEDA_Filename);
                string asdadasd = Leayal.ProcessHelper.TableStringToArgs(myParams);
                //Log.LogManager.GetLog("asdasd.txt", true).Print(asdadasd);
                patcherProcess.StartInfo.Arguments        = asdadasd;
                patcherProcess.StartInfo.WorkingDirectory = seed.Path;
                patcherProcess.StartInfo.WindowStyle      = ProcessWindowStyle.Normal;
                if (Leayal.OSVersionInfo.Name.ToLower() != "windows xp")
                {
                    patcherProcess.StartInfo.Verb = "runas";
                }
                Exception exVeda = AIDA.TransarmOrVedaOrWhatever.VEDA_Activate(pso2bin);
                if (exVeda == null)
                {
                    patcherProcess.StartInfo.UseShellExecute = false;
                    patcherProcess.Start();
                    patcherProcess.WaitForExit();
                    File.Delete(veda);
                    this.OnProgressBarStateChanged(new ProgressBarStateChangedEventArgs(Forms.MyMainMenu.ProgressBarVisibleState.None));
                    //Log.LogManager.GetLogDefaultPath("LargeFile.txt", true).Print("LargeFile Exit COde: " + patcher.ExitCode.ToString());
                    try
                    {
                        if ((patcherProcess != null) && (patcherProcess.ExitCode == 0))
                        {
                            patcherProcess = null;
                            e.Result       = seed.Date.ToVersionString();
                        }
                        else
                        {
                            patcherProcess = null;
                            if (seed.Backup)
                            {
                                if (Directory.Exists(largefilesBackupFolder))
                                {
                                    this.OnProgressBarStateChanged(new ProgressBarStateChangedEventArgs(Forms.MyMainMenu.ProgressBarVisibleState.Percent));
                                    this.OnCurrentStepChanged(new StepEventArgs(string.Format(LanguageManager.GetMessageText("Rollback0Patch", "Rolling back the {0} installation"), Infos.DefaultValues.AIDA.Strings.LargeFilesPatchCalled)));
                                    string[] tbl_backup = Directory.GetFiles(largefilesBackupFolder, "*", SearchOption.TopDirectoryOnly);
                                    string   originalFile, backupFile, currentIndexString;
                                    int      total = tbl_backup.Length;
                                    this.OnCurrentTotalProgressChanged(new ProgressEventArgs(total));
                                    for (int i = 0; i < tbl_backup.Length; i++)
                                    {
                                        currentIndexString = Path.GetFileName(tbl_backup[i]);
                                        originalFile       = Path.Combine(pso2datadir, currentIndexString);
                                        backupFile         = Path.Combine(largefilesBackupFolder, currentIndexString);
                                        File.Delete(originalFile);
                                        File.Move(backupFile, originalFile);
                                        this.OnCurrentProgressChanged(new ProgressEventArgs(i + 1));
                                    }
                                }
                            }
                            throw new Exception(LanguageManager.GetMessageText("CancelLargeFilesPatchFiles", "User cancelled or the patcher closed with Error(s)."));
                        }
                        File.Delete(Path.Combine(seed.Path, myDB));
                        File.Delete(myPatcher);
                    }
                    catch (System.Net.WebException) { }
                }
                else
                {
                    throw exVeda;
                }
            }
            else
            {
                throw new Exception(LanguageManager.GetMessageText("BadArchiveOrUnknownError", "Bad archive file or unknown error happened while") + " " + string.Format(LanguageManager.GetMessageText("Begin0PatchFiles", "Extracting {0} data"), Infos.DefaultValues.AIDA.Strings.LargeFilesPatchCalled));
            }
            try
            { Directory.Delete(seed.Path, true); }
            catch (IOException)
            {
                try
                {
                    Leayal.IO.DirectoryHelper.EmptyFolder(seed.Path);
                    Directory.Delete(seed.Path, true);
                }
                catch { }
            }
            e.Result = seedEvent.NewPatchVersion;
        }
コード例 #36
0
        protected void OnUninstalling(object sender, DoWorkEventArgs e)
        {
            WorkerInfo wi = e.Argument as WorkerInfo;

            this.OnCurrentStepChanged(new StepEventArgs(string.Format(LanguageManager.GetMessageText("Restoring0PatchFiles", "Restoring {0} files"), Infos.DefaultValues.AIDA.Strings.LargeFilesPatchCalled)));
            string sourceTable = string.Empty;

            using (var theTextReader = new StringReader(wi.Params as string))
                using (var jsonReader = new Newtonsoft.Json.JsonTextReader(theTextReader))
                    while (jsonReader.Read())
                    {
                        if (jsonReader.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                        {
                            if (jsonReader.Value is string && (jsonReader.Value as string).ToLower() == "largefileslist")
                            {
                                sourceTable = jsonReader.ReadAsString();
                            }
                        }
                    }

            string[]      tbl_files           = AIDA.StringToTableString(sourceTable);
            string        pso2datafolder      = DefaultValues.Directory.PSO2Win32Data;
            string        englishBackupFolder = Path.Combine(pso2datafolder, DefaultValues.Directory.PSO2Win32DataBackup, DefaultValues.Directory.Backup.LargeFiles);
            List <string> backup_files        = new List <string>();

            if (Directory.Exists(englishBackupFolder))
            {
                foreach (string derp in Directory.GetFiles(englishBackupFolder, "*", SearchOption.TopDirectoryOnly))
                {
                    backup_files.Add(Path.GetFileName(derp).ToLower());
                }
            }
            string backedup;
            string data;
            string currentStringIndex;

            this.OnProgressBarStateChanged(new ProgressBarStateChangedEventArgs(Forms.MyMainMenu.ProgressBarVisibleState.Percent));
            if (backup_files.Count > 0)
            {
                if (tbl_files.Length > backup_files.Count)
                {
                    int total = tbl_files.Length;
                    this.OnCurrentTotalProgressChanged(new ProgressEventArgs(total));
                    int           count    = 0;
                    List <string> nonExist = new List <string>();
                    for (int i = 0; i < tbl_files.Length; i++)
                    {
                        currentStringIndex = tbl_files[i].ToLower();
                        data     = Path.Combine(pso2datafolder, currentStringIndex);
                        backedup = Path.Combine(englishBackupFolder, currentStringIndex);
                        if (File.Exists(backedup))
                        {
                            backup_files.Remove(currentStringIndex);
                            File.Delete(data);
                            File.Move(backedup, data);
                            count++;
                            this.OnCurrentProgressChanged(new ProgressEventArgs(count + 1));
                        }
                        else
                        {
                            nonExist.Add(currentStringIndex);
                        }
                    }
                    if (backup_files.Count > 0)
                    {
                        for (int i = 0; i < backup_files.Count; i++)
                        {
                            currentStringIndex = backup_files[i];
                            data     = Path.Combine(pso2datafolder, currentStringIndex);
                            backedup = Path.Combine(englishBackupFolder, currentStringIndex);
                            if (File.Exists(backedup))
                            {
                                File.Delete(data);
                                File.Move(backedup, data);
                                count++;
                                this.OnCurrentProgressChanged(new ProgressEventArgs(count + 1));
                            }
                        }
                    }
                    Directory.Delete(englishBackupFolder, true);
                    if (nonExist.Count > 0)
                    {
                        this.OnCurrentTotalProgressChanged(new ProgressEventArgs(nonExist.Count));
                        this.OnCurrentStepChanged(new StepEventArgs(LanguageManager.GetMessageText("RedownloadingMissingOriginalFiles", "Redownloading missing original files")));
                        using (CustomWebClient downloader = WebClientPool.GetWebClient_PSO2Download())
                        {
                            Dictionary <string, string> downloadlist = new Dictionary <string, string>();
                            for (int i = 0; i < nonExist.Count; i++)
                            {
                                currentStringIndex = nonExist[i];
                                downloadlist.Add("data/win32/" + currentStringIndex + DefaultValues.Web.FakeFileExtension, Path.Combine(pso2datafolder, currentStringIndex));
                            }
                            downloader.AutoUserAgent = true;
                            PSO2UpdateManager.RedownloadFiles(downloader, downloadlist, Downloader_StepProgressChanged, Downloader_DownloadFileProgressChanged, this.Uninstall_RedownloadCallback);
                            e.Result = false;
                        }
                    }
                    else
                    {
                        e.Result = true;
                    }
                }
                else
                {
                    int total = backup_files.Count;
                    this.OnCurrentTotalProgressChanged(new ProgressEventArgs(total));
                    for (int i = 0; i < backup_files.Count; i++)
                    {
                        currentStringIndex = backup_files[i];
                        data     = Path.Combine(pso2datafolder, currentStringIndex);
                        backedup = Path.Combine(englishBackupFolder, currentStringIndex);
                        if (File.Exists(backedup))
                        {
                            File.Delete(data);
                            File.Move(backedup, data);
                            this.OnCurrentProgressChanged(new ProgressEventArgs(i + 1));
                        }
                    }
                    Directory.Delete(englishBackupFolder, true);
                    e.Result = true;
                }
            }
            else if (tbl_files.Length > 0)
            {
                if (!this.IsInstalled)
                {
                    throw new KeyNotFoundException(string.Format(LanguageManager.GetMessageText("0PatchIsNotInstalled", "{0} is not installed."), Infos.DefaultValues.AIDA.Strings.LargeFilesPatchCalled));
                }
                this.OnCurrentTotalProgressChanged(new ProgressEventArgs(tbl_files.Length));
                this.OnCurrentStepChanged(new StepEventArgs(LanguageManager.GetMessageText("RedownloadingMissingOriginalFiles", "Redownloading missing original files")));
                using (CustomWebClient downloader = WebClientPool.GetWebClient_PSO2Download())
                {
                    Dictionary <string, string> downloadlist = new Dictionary <string, string>();
                    for (int i = 0; i < tbl_files.Length; i++)
                    {
                        currentStringIndex = tbl_files[i];
                        downloadlist.Add("data/win32/" + currentStringIndex + DefaultValues.Web.FakeFileExtension, Path.Combine(pso2datafolder, currentStringIndex));
                    }
                    downloader.AutoUserAgent = true;
                    PSO2UpdateManager.RedownloadFiles(downloader, downloadlist, Downloader_StepProgressChanged, Downloader_DownloadFileProgressChanged, this.Uninstall_RedownloadCallback);
                    e.Result = false;
                }
            }
            else
            {
                throw new Exception("Unknown Error");
                //Failed
            }
        }