static void Main(string[] args)
        {
            string auth_user_id = "";
            string auth_password = "******";

            string watch_user_ids = "77219798,86061782,16069066";

            var _Request = (HttpWebRequest)WebRequest.Create("http://stream.twitter.com/1/statuses/filter.json?follow=" + watch_user_ids);
            _Request.Credentials = new NetworkCredential(auth_user_id,auth_password);

            while (true)
            {
                var _text = new StreamReader(_Request.GetResponse().GetResponseStream()).ReadLine();
                if (_text != null)
                {
                    if (_text.Length > 0)
                    {
                        var _tweetdata = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(_text);
                        if (_tweetdata.ContainsKey("user") && _tweetdata.ContainsKey("text"))
                        {
                            var _userdata = _tweetdata["user"] as Dictionary<string, object>;

                            Console.WriteLine(" * Tweet Date : " + _tweetdata["created_at"]);
                            Console.WriteLine(" * Name : " + _userdata["name"] + " / ID: @" + _userdata["screen_name"]);
                            Console.WriteLine(_tweetdata["text"]);
                            Console.WriteLine();
                        }
                    }
                }
            }
        }
        public void Login()
        {
            var userName = "******";
            var password = "******";
            var response = HttpClient.PostAsync("/token",
                new FormUrlEncodedContent(new []
                {
                    new KeyValuePair<string, string>("grant_type", "password"),
                    new KeyValuePair<string, string>("username", userName),
                    new KeyValuePair<string, string>("password", password),
                })).Result;
            var bodyValues = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);

            Assert.That(bodyValues.ContainsKey("access_token"));
            Assert.That(bodyValues.ContainsKey("token_type"));
            Assert.That(bodyValues.ContainsKey("expires_in"));
            Assert.That(bodyValues.ContainsKey("user_id"));
            Assert.That(bodyValues.ContainsKey("isClient"));
            Assert.That(bodyValues.ContainsKey("firstName"));
            Assert.That(bodyValues.ContainsKey("lastName"));
            Assert.That(bodyValues.ContainsKey(".issued"));
            Assert.That(bodyValues.ContainsKey(".expires"));
        }
        public static bool PostToLinkedIn(string title, string submittedUrl, string submittedImageUrl)
        {
            string companyId = "10355329";
            string linkedinSharesEndPoint = "https://api.linkedin.com/v1/companies/"+ companyId + "/shares?oauth2_access_token={0}";

            string accessToken = "AQXmrLhp2cUsaax3QtHE7k5YtSxMgyTAhzba-5aFYvREhVp7kvm4FxfkWVM_0_EFGGeZk6GryWDqCGdHbEnDfxSnuqschsQnGE5VSWYRi67rkLm-yhnpJSJXGdPhP6pp2k6VU5x6FZiK75E4u08RedrBcnyL61mF6Rubf6G7mQcSb10CFcQ&format=json HTTP / 1.1";

            //accessToken = "AQWVdIHVNPUnyLHE4mqsGgcoJnauh0ChrATeq7iesnW4WrABtQC_2vRE2o6i3NBd61Zj1BST8yX2xuTyaFs33o07T - 9OmVEVeLiRWIj3xQ - 6JBzMsYJW9D45Uq2safJJJhBSKVDjoqKGFRnda0W5TZ6qEClnA2iaONmIACBmF - cpRKsvtn8&format=json HTTP / 1.1";//"AQVfZEE04LluteLtvO06zY91Olv3RZIEjOS9FR4Ue93HimNhm_uj3mvhvoCUrOFDvxFp5S2HIibGDq0Ls4_ljeDW1z387O413uJbMuYCtnrV - 2fxF2C_POu55FZaB5qDtiIPncqxAIrXuEcF8BRJiexHOuLYwDlPGHOUcLSYtNUl0sE7Kw0&format=json HTTP/1.1";
            title = "åäö ÖÄÅ";
           // title = UrlManager.StringEncodingConvert(title, "ISO-8859-1", "UTF-8");
           
           // title = UrlManager.replaceSymbols(title);

            var requestUrl = String.Format(linkedinSharesEndPoint, accessToken);
            var message = new
            {
                comment = "Testing out the posting on LinkedIn",
                content = new Dictionary<string, string>
                    {
                        { "title", title },
                        { "submitted-url", submittedUrl },
                        {"submitted-image-url" , submittedImageUrl}
                    },
                visibility = new
                {
                    code = "anyone"
                }
            };

            var requestJson = new JavaScriptSerializer().Serialize(message);

            var client = new WebClient();
            var requestHeaders = new NameValueCollection
    {
        { "Content-Type", "application/json" },
        { "x-li-format", "json" }
    };
            client.Encoding = System.Text.Encoding.UTF8;
            client.Headers.Add(requestHeaders);
            var responseJson = client.UploadString(requestUrl, "POST", requestJson);
            var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
            return response.ContainsKey("updateKey");
        }
        public static PaymentResponse Map(string json)
        {
            var paymentResponse = new PaymentResponse();

            var giftResponse = new JavaScriptSerializer().Deserialize<dynamic>(json);
            if(giftResponse.ContainsKey("ResponseOrigin")){ paymentResponse.ResponseOrigin = giftResponse["ResponseOrigin"];}
            if(giftResponse.ContainsKey("DSIXReturnCode")) {paymentResponse.DSIXReturnCode = giftResponse["DSIXReturnCode"];}
            if(giftResponse.ContainsKey("CmdStatus")) {paymentResponse.CmdStatus = giftResponse["CmdStatus"];}
            if(giftResponse.ContainsKey("TextResponse")) {paymentResponse.TextResponse = giftResponse["TextResponse"];}
            if(giftResponse.ContainsKey("UserTraceData")) {paymentResponse.UserTraceData = giftResponse["UserTraceData"];}
            if(giftResponse.ContainsKey("MerchantID")) {paymentResponse.MerchantID = giftResponse["MerchantID"];}
            if(giftResponse.ContainsKey("TranType")) {paymentResponse.TranType = giftResponse["TranType"];}
            if(giftResponse.ContainsKey("TranCode")) {paymentResponse.TranCode = giftResponse["TranCode"];}
            if(giftResponse.ContainsKey("InvoiceNo")) {paymentResponse.InvoiceNo = giftResponse["InvoiceNo"];}
            if(giftResponse.ContainsKey("TerminalName")) {paymentResponse.TerminalName = giftResponse["TerminalName"];}
            if(giftResponse.ContainsKey("OperatorID")) {paymentResponse.OperatorID = giftResponse["OperatorID"];}
            if(giftResponse.ContainsKey("AcctNo")) {paymentResponse.AcctNo = giftResponse["AcctNo"];}
            if(giftResponse.ContainsKey("RefNo")) {paymentResponse.RefNo = giftResponse["RefNo"];}
            if(giftResponse.ContainsKey("AuthCode")) {paymentResponse.AuthCode = giftResponse["AuthCode"];}
            if(giftResponse.ContainsKey("Authorize")) {paymentResponse.Authorize = giftResponse["Authorize"];}
            if(giftResponse.ContainsKey("Purchase")) {paymentResponse.Purchase = giftResponse["Purchase"];}
            if (giftResponse.ContainsKey("Balance")) { paymentResponse.Balance = giftResponse["Balance"]; }


            return paymentResponse;
        }
Exemple #5
0
        public void CircularGraph_Parent()
        {
            var parent = new CI { ID = 1, Title = "parent" };
            var child = new CI { ID = 2, Title = "child" };
            child.AddTo(parent);

            var result = parent.ToJson();
            var deserialized = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(result);

            deserialized["Title"].ShouldBe("parent");
            deserialized.ContainsKey("Children").ShouldBe(false);
        }
		/// <summary>
		/// Deserialize a JWK
		/// </summary>
		/// <param name="json">The json JWK</param>
		/// <returns>A <see cref="JsonWebKey"/></returns>
		public static JsonWebKey FromJson( string json ) {
			var data = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>( json );

			if( !data.ContainsKey( "use" ) ) {
				throw new JsonWebKeyParseException( "missing 'use' parameter in JSON web key" );
			}

			if ( data[ "use" ].ToString() != "sig" ) {
				string msg = String.Format( "invalid 'use' value in JSON web key: {0}", data[ "use" ] );
				throw new JsonWebKeyParseException( msg );
			}

			if( !data.ContainsKey( "kty" ) ) {
				throw new JsonWebKeyParseException( "missing 'kty' parameter in JSON web key" );
			}

			if( !data.ContainsKey( "kid" ) ) {
				throw new JsonWebKeyParseException( "missing 'kid' parameter in JSON web key" );
			}

			Guid id = Guid.Parse( data[ "kid" ].ToString() );
			DateTime? expiresAt = null;
			if( data.ContainsKey( "exp" ) ) {
				long ts = long.Parse( data[ "exp" ].ToString() );
				expiresAt = DateTimeExtensions.FromUnixTime( ts );
			}

			switch( data[ "kty" ].ToString() ) {
				case "RSA":
					if( !data.ContainsKey( "n" ) ) {
						throw new JsonWebKeyParseException( "missing 'n' parameter in RSA JSON web key" );
					}

					if( !data.ContainsKey( "e" ) ) {
						throw new JsonWebKeyParseException( "missing 'e' parameter in RSA JSON web key" );
					}

					if( HasRsaPrivateKeyMaterial( data ) ) {
						throw new JsonWebKeyParseException( "RSA JSON web key has private key material" );
					}

					return new RsaJsonWebKey(
						id: id,
						expiresAt: expiresAt,
						n: data[ "n" ].ToString(),
						e: data[ "e" ].ToString()
					);

				case "EC":
					if( !data.ContainsKey( "crv" ) ) {
						throw new JsonWebKeyParseException( "missing 'crv' parameter in EC JSON web key" );
					}

					if( !data.ContainsKey( "x" ) ) {
						throw new JsonWebKeyParseException( "missing 'x' parameter in EC JSON web key" );
					}

					if( !data.ContainsKey( "y" ) ) {
						throw new JsonWebKeyParseException( "missing 'y' parameter in EC JSON web key" );
					}

					return new EcDsaJsonWebKey(
						id: id,
						expiresAt: expiresAt,
						curve: data[ "crv" ].ToString(),
						x: data[ "x" ].ToString(),
						y: data[ "y" ].ToString()
					);

				default:
					string msg = String.Format( "'{0}' is not a supported JSON eb key type", data[ "kty" ] );
					throw new JsonWebKeyParseException( msg );

			}
		}
        /// <summary>
        /// UserStream 受信処理。
        /// </summary>
        private void GetUserStream(object o)
        {
            while (true)
            {
                WebResponse r;
                {
                    int counter = 0;
                    do
                    {
                        r = BasicTwitterAccess("GET", this._follow_userstream_url);
                        if (r == null)
                        {
                            Thread.Sleep(2000);
                            counter++;
                            if (counter == 2)
                            {
                                // UserStream が2回失敗した場合は、通常取得を1回行う。
                                this.GetTimeline();
                                counter = 0;
                            }
                        }
                    } while (r == null);
                }
                var stream = new StreamReader(r.GetResponseStream());

                while (true)
                {
                    try
                    {
                        var text = stream.ReadLine();
                        if (text != null && this.UserStreams != null)
                        {
                            if (text.Length > 0)
                            {
                                var tweet = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(text);
                                if (tweet.ContainsKey("user") && tweet.ContainsKey("text"))
                                {
                                    var user = tweet["user"] as Dictionary<string, object>;
                                    this.UserStreams(tweet["id_str"] as string, user["screen_name"] as string, user["name"] as string, tweet["text"] as string);
                                }
                                else if (tweet.ContainsKey("delete"))
                                {
                                    var info = (tweet["delete"] as Dictionary<string, object>)["status"] as Dictionary<string, object>;
                                    this.UserStreams(info["id_str"] as string, null, null, null);
                                }
                            }
                        }
                        else
                        {
                            Thread.Sleep(100);
                        }
                    }
                    catch { break; }
                }
                try { r.Close(); }
                catch { }
            }
        }
        public void PostCreditApplication()
        {
            var userName = "******";
            var password = "******";
            var tokenResponse = HttpClient.PostAsync("/token",
                new FormUrlEncodedContent(new []
                {
                    new KeyValuePair<string, string>("grant_type", "password"),
                    new KeyValuePair<string, string>("username", userName),
                    new KeyValuePair<string, string>("password", password)
                })).Result;
            var tokenBodyValues = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(tokenResponse.Content.ReadAsStringAsync().Result);

            var creditTypeResponse = HttpClient.GetAsync("/api/creditTypes").Result;
            var creditTypes = new JavaScriptSerializer().Deserialize<List<CreditTypeModel>>(creditTypeResponse.Content.ReadAsStringAsync().Result);
            var creditApplication = new CreditApplication()
            {
                DesiredAmount = 100000,
                DesiredTerm = 12,
                CreditAim = "sdfsdfsd",

                AptNumber = 2,
                CorpusNumber = 2,
                HomeNumber = 2,
                Locality = "Минская Область",
                Street = "Богдановича",

                MaritalStatus = "холост",
                EducationLevel = "незаконченное высшее",
                NumberOfFamilyMembers = 5,
                NumberOfDependents = 0,

                BirthDate = new DateTime(1993, 12, 8),
                DateOfIssue = DateTime.Now,
                PassportNumber = "MP1231724",
                PersonalNumber = "3081293A005PB9",
                PlaceOfBirth = "Минск, Беларусь",
                PlaceOfIssue = "Фрунзенское РУВД г.Минска",

                FirstName = "Максим",
                LastName = "Рахлеев",
                MiddleName = "Александрович",
                MobilePhone = "375295053587",
                Email = "*****@*****.**",

                CompanyName = "ФордэКонсалтинг",
                Position = ".Net Developer",
                Activity = "sdfsdf",
                DateOfBeginning = new DateTime(2015, 4, 23),
                Profit = 200000000,

                Status = CreditApplicationStatus.InQueue,
                DeclineReason = String.Empty,
                ClientId = tokenBodyValues["user_id"],
                CreditTypeId = creditTypes.First().Id
            };
            var stringContent = new JavaScriptSerializer().Serialize(creditApplication);
            var creditApplicationResponse = HttpClient.PostAsync("/api/creditApplications",
                new StringContent(new JavaScriptSerializer().Serialize(creditApplication), Encoding.Unicode, "application/json")).Result;
            var creditApplicationBodyValues = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(creditApplicationResponse.Content.ReadAsStringAsync().Result);
            Assert.That(creditApplicationBodyValues.ContainsKey("id"));
        }