예제 #1
0
        public static void JayrockReaderStrings ()
        {
            for (int i = 0; i < Common.Iterations; i++) {
                StringReader sr = new StringReader (Common.JsonStrings);
                JsonReader reader = new JsonTextReader (sr);

                while (reader.Read ());
            }
        }
예제 #2
0
        public static void JayrockReaderLastProperty ()
        {
            for (int i = 0; i < Common.Iterations; i++) {
                bool found = false;

                StringReader sr = new StringReader (Common.JsonText);

                JsonReader reader = new JsonTextReader (sr);

                while (reader.Read ()) {
                    if (reader.TokenClass == JsonTokenClass.Member &&
                        reader.Text == "LastProperty") {
                        found = true;
                        break;
                    }
                }

                if (! found)
                    Console.WriteLine ("LastProperty not found!");
            }
        }
예제 #3
0
        public void ProcessResponse(WebResponse response)
        {
            StreamReader sr = new StreamReader(response.GetResponseStream());

            if (onMessage != null && severity >= 7)
                onMessage(this,"[{0}] Reading response...",DateTime.Now);

            string data = sr.ReadToEnd ();

            response.Close ();

            Log.Write("Response: ");
            Log.WriteLine (data.ToString()+"\n");

            if (onMessage != null && severity >= 7)
                onMessage(this,"[{0}] Processing response...",DateTime.Now);

            using (JsonTextReader reader = new JsonTextReader(new StringReader(data)))
            {
            string text = "";

                Stack<string> level = new Stack<string>();
                //Stack<string> token = new Stack<string>();

                while(reader.Read())
                {
                    switch (reader.TokenClass.Name)
                    {
                        case "Member":
                            Log.Write("[{0}] {1} : ",level.Count,text = reader.Text);
                            break;
                        case "Array":
                        case "Object":
                            if (text == "")
                                Log.WriteLine("[{0}] {1} ()",level.Count,reader.TokenClass);
                            else
                                Log.WriteLine("({0})",reader.TokenClass);
                            level.Push(text);
              text = "";
                            break;
                        case "EndArray":
                        case "EndObject":
                            Log.WriteLine("[{0}] {1} ({2})",level.Count-1,reader.TokenClass,level.Pop());
                            break;
                        case "BOF":
                        case "EOF":
                            break;
                        default :
                            Log.WriteLine("{0} ({1})",reader.Text,reader.TokenClass);
                            break;
                    }
                }

                if (onMessage != null && severity >= 7)
                    onMessage(this,"[{0}] Processing complete!\n",DateTime.Now);

                if (onMessage != null && severity >= 6)
                    onMessage(this,"\n[{0}] {1} RPC call(s) remaining today",
                              DateTime.Now, cache.rpcLimit - cache.rpcCount);

                Log.WriteLine("-------------------------");
            Log.Flush();  // if we crash when we Deserialize, we still get the log!
            }

              JavaScriptSerializer js = new JavaScriptSerializer();

              r = js.Deserialize<Response>(data);

              if (r.error != null) return;

              // Cache what we need from status, if no errors
              cache.time = r.result.status.server.time;
              cache.rpcCount = r.result.status.empire.rpc_count;
              cache.rpcLimit = r.result.status.server.rpc_limit;
              cache.home_planet_id = r.result.status.empire.home_planet_id;

              // Update or add planet names to session cache
              foreach (KeyValuePair<string,string> p in r.result.status.empire.planets)
              {
            if (myColony.ContainsKey(p.Key)) {
              myColony[p.Key].name = p.Value;
            } else {
              Colony colony = new Colony(p.Key,p.Value);
              myColony.Add(p.Key,colony);
              cache.colony.Add(colony);
            }
              }
        }
 public void Blank()
 {
     JsonTextReader reader = new JsonTextReader(new StringReader(string.Empty));
     reader.Read();
 }
예제 #5
0
파일: Program.cs 프로젝트: db48x/KeeFox
        private static void Main(string[] args)
        {
            const int keywordsLimit = 70;
            
            Console.WriteLine("Yahoo (JSON) News Reader");
            Console.WriteLine();
            Console.WriteLine("When prompted, enter keywords (e.g. Ray Charles) to search");
            Console.WriteLine("news for. Program ends if an empty keyword list is supplied.");

            WebClient client = new WebClient();
            string urlFormat = args.Length > 0 ? args[0].Trim() : string.Empty;

            if (string.IsNullOrEmpty(urlFormat))
            {
                urlFormat = "http://search.yahooapis.com/NewsSearchService/V1/newsSearch?" +
                    "appid=YahooDemo&query={0}&results=10&language=en&output=json";
            }

            while (true)
            {
                Console.WriteLine();
                Console.Write("Keywords: ");

                string keywords = Console.ReadLine().Trim();

                if (keywords.Length == 0)
                    return;

                if (keywords.Length > keywordsLimit)
                {
                    Console.WriteLine("Keywords exceed {0:N0} chars! Try again.", keywordsLimit);
                    continue;
                }

                Console.WriteLine();
                Console.Write("Downloading news...");

                string escapedKeywords = Uri.EscapeUriString(keywords);
                Uri url = new Uri(string.Format(urlFormat, escapedKeywords));
                string news = client.DownloadString(url);

                Console.WriteLine("Done!");
                Console.WriteLine();

                //
                // Read through the entire JSON response and display the
                // string value of object member named "Title". The
                // shape of the news data looks something like this:
                //
                //  { 
                //      "ResultSet" : {
                //          "totalResultsAvailable" : ...,
                //          "totalResultsReturned" : ...,
                //          "firstResultPosition": ...,
                //          "Result" : [ 
                //             {
                //                  "Title" : "..."
                //                 ...
                //              },
                //              ...
                //          ]
                //      }
                //  }
                //

                using (JsonTextReader reader = new JsonTextReader(new StringReader(news)))
                {
                    while (reader.Read())
                    {
                        if (reader.Depth == 4 &&
                            reader.TokenClass == JsonTokenClass.Member && 
                            reader.Text == "Title")
                        {
                            reader.Read(/* member */);
                            Console.WriteLine(reader.ReadString());
                        }
                    }
                }
            }
        }
예제 #6
0
파일: Pool.cs 프로젝트: wasabii/BitMaker
        /// <summary>
        /// Parses a <see cref="WebResponse"/> containing the results of a 'getwork' request.
        /// </summary>
        /// <param name="webResponse"></param>
        /// <returns></returns>
        Work ParseGetWork(WebResponse webResponse)
        {
            // obtain and update current block number
            uint blockNumber = 0;
            if (webResponse.Headers["X-Blocknum"] != null)
                CurrentBlockNumber = blockNumber = uint.Parse(webResponse.Headers["X-Blocknum"]);

            // parse and update long poll url value if present
            var longPollUrlStr = webResponse.Headers["X-Long-Polling"];
            if (longPollUrlStr == null)
                longPollUrl = null;
            else if (longPollUrlStr == "")
                longPollUrl = url;
            else if (longPollUrlStr.StartsWith("http:") || longPollUrlStr.StartsWith("https:"))
                longPollUrl = new Uri(longPollUrlStr);
            else
                longPollUrl = new Uri(url, longPollUrlStr);

            // longPollUrl does not specify user info, but userinfo was required on initial url
            if (string.IsNullOrWhiteSpace(longPollUrl.UserInfo) && !string.IsNullOrWhiteSpace(url.UserInfo))
            {
                var b = new UriBuilder(longPollUrl);
                var u = url.UserInfo
                    .Split(':')
                    .Select(i => HttpUtility.UrlDecode(i))
                    .ToArray();
                if (u.Length >= 2)
                {
                    b.UserName = u[0];
                    b.Password = u[1];
                }
                longPollUrl = b.Uri;
            }

            // retrieve invocation response
            using (var txt = new StreamReader(webResponse.GetResponseStream()))
            using (var rdr = new JsonTextReader(txt))
            {
                if (!rdr.MoveToContent() && rdr.Read())
                    throw new JsonException("Unexpected content from 'getwork'.");

                var response = JsonConvert.Import<JsonGetWork>(rdr);
                if (response == null)
                    throw new JsonException("No response returned.");

                if (response.Error != null)
                    Console.WriteLine("JSON-RPC: {0}", response.Error);

                var result = response.Result;
                if (result == null)
                    return null;

                // decode data
                var data = Memory.Decode(result.Data);
                if (data.Length != 128)
                    throw new InvalidDataException("Received data is not valid.");

                // extract only header portion
                var header = new byte[80];
                Array.Copy(data, header, 80);

                // decode target
                var target = Memory.Decode(result.Target);
                if (target.Length != 32)
                    throw new InvalidDataException("Received target is not valid.");

                // generate new work instance
                var work = new Work()
                {
                    Pool = this,
                    BlockNumber = blockNumber,
                    Header = header,
                    Target = target,
                };

                // release connection
                webResponse.Close();

                return work;
            }
        }
예제 #7
0
파일: Pool.cs 프로젝트: wasabii/BitMaker
        /// <summary>
        /// Invokes the 'getwork' JSON method, submitting the proposed work. Returns <c>true</c> if the service accepts
        /// the proposed work.
        /// </summary>
        /// <param name="work"></param>
        /// <returns></returns>
        public bool SubmitWorkRpc(IMiner miner, Work work, string comment)
        {
            var req = OpenRpc(miner, comment);
            if (req == null)
                return false;

            // header needs to have SHA-256 padding appended
            var data = Sha256.AllocateInputBuffer(80);

            // prepare header buffer with SHA-256
            Sha256.Prepare(data, 80, 0);
            Sha256.Prepare(data, 80, 1);

            // dump header data on top of padding
            Array.Copy(work.Header, data, 80);

            // encode in proper format
            var solution = Memory.Encode(data);

            Console.WriteLine();
            Console.WriteLine("SOLUTION: {0,10} {1}", miner.GetType().Name, Memory.Encode(work.Header));
            Console.WriteLine();
            Console.WriteLine();

            using (var txt = new StreamWriter(req.GetRequestStream()))
            using (var wrt = new JsonTextWriter(txt))
            {
                wrt.WriteStartObject();
                wrt.WriteMember("id");
                wrt.WriteString("json");
                wrt.WriteMember("method");
                wrt.WriteString("getwork");
                wrt.WriteMember("params");
                wrt.WriteStartArray();
                wrt.WriteString(solution);
                wrt.WriteEndArray();
                wrt.WriteEndObject();
                wrt.Flush();
            }

            using (var txt = new StreamReader(req.GetResponse().GetResponseStream()))
            using (var rdr = new JsonTextReader(txt))
            {
                if (!rdr.MoveToContent() && rdr.Read())
                    throw new JsonException("Unexpected content from 'getwork <data>'.");

                var response = JsonConvert.Import<JsonSubmitWork>(rdr);
                if (response == null)
                    throw new JsonException("No response returned.");

                if (response.Error != null)
                    Console.WriteLine("JSON-RPC: {0}", response.Error);

                Console.WriteLine();
                Console.WriteLine("{0}: {1,10} {2}", response.Result ? "ACCEPTED" : "REJECTED", miner.GetType().Name, Memory.Encode(work.Header));
                Console.WriteLine();
                Console.WriteLine();

                return response.Result;
            }
        }
예제 #8
0
 public void ReadPositionsAfterEof()
 {
     JsonTextReader reader = new JsonTextReader(new StringReader("[ \nhello ]"));
     while (reader.Read()) { /* NOP */ }
     Assert.AreEqual(2, reader.LineNumber, "Line number");
     Assert.AreEqual(7, reader.LinePosition, "Line position");
     Assert.AreEqual(10, reader.CharCount, "Character count");
 }
예제 #9
0
파일: Pool.cs 프로젝트: furyan/MatriXMiner
        /// <summary>
        /// Parses a <see cref="WebResponse"/> containing the results of a 'getwork' request.
        /// </summary>
        /// <param name="webResponse"></param>
        /// <returns></returns>
        private Work ParseGetWork(WebResponse webResponse)
        {
            // obtain and update current block number
            uint blockNumber = 0;
            if (webResponse.Headers["X-Blocknum"] != null)
                CurrentBlockNumber = blockNumber = uint.Parse(webResponse.Headers["X-Blocknum"]);

            // parse and update long poll url value if present
            var longPollUrlStr = webResponse.Headers["X-Long-Polling"];
            if (longPollUrlStr == null)
                longPollUrl = null;
            else if (longPollUrlStr == "")
                longPollUrl = url;
            else if (longPollUrlStr.StartsWith("http:") || longPollUrlStr.StartsWith("https:"))
                longPollUrl = new Uri(longPollUrlStr);
            else
                longPollUrl = new Uri(url, longPollUrlStr);

            // retrieve invocation response
            using (var txt = new StreamReader(webResponse.GetResponseStream()))
            using (var rdr = new JsonTextReader(txt))
            {
                if (!rdr.MoveToContent() && rdr.Read())
                    throw new JsonException("Unexpected content from 'getwork'.");

                var response = JsonConvert.Import<JsonGetWork>(rdr);
                if (response == null)
                    throw new JsonException("No response returned.");

                if (response.Error != null)
                    Console.WriteLine("JSON-RPC: {0}", response.Error);

                var result = response.Result;
                if (result == null)
                    return null;

                // decode data
                var data = Memory.Decode(result.Data);
                if (data.Length != 128)
                    throw new InvalidDataException("Received data is not valid.");

                // extract only header portion
                var header = new byte[80];
                Array.Copy(data, header, 80);

                // decode target
                var target = Memory.Decode(result.Target);
                if (target.Length != 32)
                    throw new InvalidDataException("Received target is not valid.");

                // generate new work instance
                var work = new Work()
                {
                    Pool = this,
                    BlockNumber = blockNumber,
                    Header = header,
                    Target = target,
                };

                // release connection
                webResponse.Close();

                return work;
            }
        }
예제 #10
0
 private bool TryParseField(JsonTextReader reader, string pTwitterObjName)
 {
     if (reader.Text != null && reader.Text == pTwitterObjName)
     {
         reader.Read();
         return true;
     }
     return false;
 }
예제 #11
0
 private void InitializeLoop(JsonTextReader reader)
 {
     while (reader.Read())
     {
         if (BeginningOfResultFound(reader))
             break;
     }
 }
예제 #12
0
        private List<SearchResult> GetResults(string queryWord)
        {
            List<SearchResult> results = new List<SearchResult>();

            string text = CreateConnectionAndGetResult(queryWord);

            JsonTextReader reader = new JsonTextReader(new StringReader(text));
            InitializeLoop(reader);
            while (reader.Read())
            {
                // At this point we should be at the user ID.
                SearchResult result = new SearchResult();
                result.UserID = reader.Text;

                // Now read the rest of the object.
                while (ParseJSON(reader, result))
                {
                    if (!reader.Read())
                        break;
                }
                // We are finished with this object. Add it to the list.
                results.Add(result);
            }

            return results;
        }
예제 #13
0
    private void SaveData(string data)
    {
        List<Task> colTask = new List<Task>();
        Task currTask = null;
        // read the data into a .NET object and save
        using (JsonTextReader reader = new JsonTextReader(new StringReader(data)))
        {
            bool toContinue = true;
            do
            {
                if (reader.TokenClass == JsonTokenClass.BOF)
                    reader.Read();  // read to get in the file
                else if (reader.TokenClass == JsonTokenClass.Object)
                {
                    currTask = new Task();
                    reader.Read();  // read to get to the first member
                }
                else if (reader.TokenClass == JsonTokenClass.Member
                            && reader.Text == "taskID")
                {
                    reader.Read();                                      //  Read to get to the member data
                    currTask.TaskID = new Guid(reader.ReadString());    // then read the data
                }
                else if (reader.TokenClass == JsonTokenClass.Member
                            && reader.Text == "isComplete")
                {
                    reader.Read();                                 //  Read to get to the member data
                    currTask.IsComplete = reader.ReadBoolean();    // then read the data
                }
                else if (reader.TokenClass == JsonTokenClass.Member
                            && reader.Text == "description")
                {
                    reader.Read();                                 //  Read to get to the member data
                    currTask.Description = reader.ReadString();    // then read the data
                }
                else if (reader.TokenClass == JsonTokenClass.Member
                            && reader.Text == "dueDate")
                {
                    reader.Read();                                 //  Read to get to the member data
                    currTask.DueDate = DateTime.Parse(reader.ReadString());    // then read the data
                }
                else if (reader.TokenClass == JsonTokenClass.EndObject)
                {
                    colTask.Add(currTask);
                    reader.Read();
                }
                else if (reader.TokenClass == JsonTokenClass.EndArray)
                    toContinue = false;
                else
                    reader.Read();  // just continue reading, don't want to get stuck

            } while (toContinue == true);

        }

        // prioratize them according to the order they were saved
        int counter = 0;
        foreach (Task task in colTask)
        {
            task.Priority = counter++;
        }

        // Don't allow them to have more than 10
        while (colTask.Count > 10)
        {
            colTask.Remove(colTask[10]);
        }

        // Now call SQL and save it
        // make DB call to get tasks
        SqlConnection conn = null;
        SqlTransaction transaction = null;
        try
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PTO_Procs"].ConnectionString);
            conn.Open();
            transaction = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand("sp_DeleteAllTasks", conn, transaction);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.ExecuteNonQuery();

            SqlCommand cmdInsert = null;
            foreach (Task task in colTask)
            {
                cmdInsert = new SqlCommand("sp_InsertTask", conn, transaction);
                cmdInsert.CommandType = CommandType.StoredProcedure;
                cmdInsert.Parameters.Add(new SqlParameter("@taskID", task.TaskID));
                cmdInsert.Parameters.Add(new SqlParameter("@description", task.Description));
                cmdInsert.Parameters.Add(new SqlParameter("@dueDate", task.DueDate));
                cmdInsert.Parameters.Add(new SqlParameter("@isComplete", task.IsComplete));
                cmdInsert.Parameters.Add(new SqlParameter("@priority", task.Priority));

                cmdInsert.ExecuteNonQuery();
            }

            transaction.Commit();
        }
        catch (Exception ex)
        {
            if (transaction != null)
                transaction.Rollback();
            throw ex;
        }
        finally
        {
            if (conn != null)
                conn.Close();
        }

        Response.ContentType = "application/json";
        Response.Write("Saved");
        Response.End();
    }
예제 #14
0
        public static void JayrockOutputFile ()
        {
            using (FileStream fs = new FileStream ("jayrock_out.txt",
                                                   FileMode.Create)) {
                StreamWriter out_stream = new StreamWriter (fs);

                StringReader sr = new StringReader (Common.JsonText);

                JsonReader reader = new JsonTextReader (sr);


                out_stream.WriteLine (
                    "*** Reading with Jayrock.Json.JsonReader");

                while (reader.Read ()) {
                    out_stream.Write ("Token: {0}", reader.TokenClass);

                    if (reader.Text != null)
                        out_stream.WriteLine (" Value: {0}", reader.Text);
                    else
                        out_stream.WriteLine ("");

                }


                out_stream.WriteLine (
                    "\n*** Writing with Jayrock.Json.JsonWriter");

                JsonWriter writer = new JsonTextWriter (out_stream);
                int n = Common.SampleObject.Length;
                for (int i = 0; i < n; i += 2) {
                    switch ((char) Common.SampleObject[i]) {
                    case '{':
                        writer.WriteStartObject ();
                        break;

                    case '}':
                        writer.WriteEndObject ();
                        break;

                    case '[':
                        writer.WriteStartArray ();
                        break;

                    case ']':
                        writer.WriteEndArray ();
                        break;

                    case 'P':
                        writer.WriteMember (
                            (string) Common.SampleObject[i + 1]);
                        break;

                    case 'I':
                        writer.WriteNumber (
                            (int) Common.SampleObject[i + 1]);
                        break;

                    case 'D':
                        writer.WriteNumber (
                            (double) Common.SampleObject[i + 1]);
                        break;

                    case 'S':
                        writer.WriteString (
                            (string) Common.SampleObject[i + 1]);
                        break;

                    case 'B':
                        writer.WriteBoolean (
                            (bool) Common.SampleObject[i + 1]);
                        break;

                    case 'N':
                        writer.WriteNull ();
                        break;
                    }
                }


                out_stream.WriteLine (
                    "\n\n*** Data imported with " +
                    "Jayrock.Json.Conversion.JsonConvert\n");

                Person art = (Person) JsonConvert.Import (typeof (Person),
                                                          Common.PersonJson);

                out_stream.Write (art.ToString ());


                out_stream.WriteLine (
                    "\n\n*** Object exported with " +
                    "Jayrock.Json.Conversion.JsonConvert\n");

                out_stream.Write (JsonConvert.ExportToString (
                        Common.SamplePerson));

                out_stream.WriteLine (
                    "\n\n*** Generic object exported with " +
                    "Jayrock.Json.Conversion.JsonConvert\n");
                JsonObject person = (JsonObject) JsonConvert.Import (
                    Common.PersonJson);

                out_stream.Write (JsonConvert.ExportToString (person));


                out_stream.WriteLine (
                    "\n\n*** Hashtable exported with " +
                    "Jayrock.Json.Conversion.JsonConvert\n");

                out_stream.Write (JsonConvert.ExportToString (
                        Common.HashtablePerson));

                out_stream.Close ();
            }
        }