private void searchCallback(RestRequest request, RestResponse response, object sender)
        {
            XmlReader rdr = XmlReader.Create(response.ContentStream);
            while (!rdr.EOF)
            {
                if (rdr.ReadToFollowing("exercise"))
                {
                    SearchedExercise exercise = new SearchedExercise();
                    rdr.ReadToFollowing("id");
                    exercise.id = rdr.ReadElementContentAsInt();
                    rdr.ReadToFollowing("name");
                    exercise.Name = rdr.ReadElementContentAsString();
                    rdr.ReadToFollowing("exercise-description");
                    exercise.Description = rdr.ReadElementContentAsString();
                    rdr.ReadToFollowing("exercise-type");
                    exercise.exercise_type = rdr.ReadElementContentAsString();
                    rdr.ReadToFollowing("exercise-video-url");
                    exercise.exercise_video_url = rdr.ReadElementContentAsString();
                    rdr.ReadToFollowing("exercise-picture-url");
                    exercise.PictureUrl = rdr.ReadElementContentAsString();
                    rdr.ReadToFollowing("exercise-order");
                    if (!rdr.MoveToAttribute("nil"))
                        exercise.exercise_order = rdr.ReadElementContentAsInt();
                    else
                        exercise.exercise_order = 0;

                    exercises.Add(exercise);
                }
            }

            OnSearchComplete();
        }
Exemplo n.º 2
0
 public static void GetFriends(EventHandler<FriendsListEventArgs> callback)
 {
     var serializer = new Hammock.Serialization.HammockDataContractJsonSerializer();
     RestClient client = new RestClient
     {
         Authority = baseUrl,
         Timeout = new TimeSpan(0, 0, 0, _timeOut),
         Serializer = serializer,
         Deserializer = serializer
     };
     RestRequest request = new RestRequest
                               {
                                   Path = "GetFriends" + "?timestamp=" + DateTime.Now.Ticks.ToString(),
                                   Timeout = new TimeSpan(0, 0, 0, _timeOut)
                               };
     friendscallback = callback;
     try
     {
         client.BeginRequest(request, new RestCallback<List<Friend>>(GetFriendsCallback));
     }
     catch (Exception ex)
     {
         friendscallback.Invoke(null, new FriendsListEventArgs() { Friends = null, Error = new WebException("Communication Error!", ex) });
     }
     
 }
Exemplo n.º 3
0
        public static bool storeTweetMark(AccountTwitter account, string type, decimal id)
        {
            return(false);

            Hammock.RestRequest oauthRequest = account.twitterService.PrepareEchoRequest();
            oauthRequest.Path      = string.Format("/v1/lastread?collection={0}&username={1}&api_key={2}", type, account.Login.Username.ToLower(), "");
            oauthRequest.UserAgent = "Nymphicus for Windows";
            oauthRequest.Method    = Hammock.Web.WebMethod.Post;

            // Generate post objects
            Dictionary <string, object> postParameters   = new Dictionary <string, object>();
            Dictionary <string, string> additonalHeaders = new Dictionary <string, string>();

            // Create request and receive response
            string     postURL = string.Format("https://api.tweetmarker.net/");
            RestClient client  = new RestClient {
                Authority = postURL
            };

            client.Method = Hammock.Web.WebMethod.Post;
            client.AddPostContent(WebHelpers.getBytesFromString(id.ToString()));

            RestResponse response = client.Request(oauthRequest);

            return(response.StatusCode == HttpStatusCode.OK);
        }
Exemplo n.º 4
0
        public static void Main(string[] args)
        {
            if(args.Length == 0)
            {
                PrintUsage();
                return;
            }

            if(args.Length == 1)
            {
                Uri uri;
                if(Uri.TryCreate(args[0], UriKind.Absolute, out uri))
                {
                    _client.Authority = uri.Scheme + "://" + uri.Authority;
                    var request = new RestRequest { Path = uri.PathAndQuery };
                    var response = _client.Request(request);
                    response.Content.Out();
                    return;
                }
                else
                {
                    
                }
            }
        }
Exemplo n.º 5
0
        private void newFoodLogEntryCallback(RestRequest request, Hammock.RestResponse response, object obj)
        {
            if (response.StatusCode == HttpStatusCode.Created ||
                response.StatusCode == HttpStatusCode.OK)
            {
                Dispatcher.BeginInvoke(()=>
                txtProgressMessage.Text = dbwp7Resources.Success);
            }
            else
                Dispatcher.BeginInvoke(()=>
                txtProgressMessage.Text = dbwp7Resources.CouldNotSave);

            System.Threading.Thread.Sleep(800);

            Dispatcher.BeginInvoke(() =>
            {
                spProcessing.Visibility = Visibility.Collapsed;
                txtProgressMessage.Text = dbwp7Resources.Processing;
            });

            if (FoodEntryLogged != null)
                FoodEntryLogged(this, new RoutedEventArgs());

          
        }
Exemplo n.º 6
0
 private void PhotoPostCompleted(RestRequest request, RestResponse response, object userstate)
 {
     // We want to ensure we are running on our thread UI
     Deployment.Current.Dispatcher.BeginInvoke(() =>
     {
         if (response.StatusCode == HttpStatusCode.Created)
         {
             Deployment.Current.Dispatcher.BeginInvoke(
                 () =>
                 {
                     ToastPrompt toast = new ToastPrompt
                     {
                         Title = "ajapaik",
                         Message = "your photo was uploaded",
                     };
                     toast.Show();
                 });
         }
         else
         {
             MessageBox.Show("Error while uploading to server. Please try again later. " +
                     "If this error persists please let the program author know.");
         }
     });
 }
Exemplo n.º 7
0
        public ActionResult Index()
        {
            var restConfig = RestConfig.Current;
            if (string.IsNullOrEmpty(restConfig.UserId))
                return RedirectToAction("Authorize");

            var client = new RestClient {Authority = restConfig.BaseUrl};
            var request = new RestRequest
                              {
                                  Path = string.Format("users/{0}/queues/instant", restConfig.UserId),
                                  Credentials = OAuthCredentials.ForProtectedResource(
                                      restConfig.OAuthKey, restConfig.OAuthSharedSecret,
                                      restConfig.OAuthToken, restConfig.OAuthTokenSecret)
                              };
            var response = client.Request(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var xml = XDocument.Parse(response.Content);
                var items = from i in xml.Descendants("queue_item")
                            select new Movie
                                       {
                                           Title = (string) i.Descendants("title").Attributes("regular").FirstOrDefault(),
                                           Thumbnail = (string)i.Descendants("box_art").Attributes("small").FirstOrDefault(),
                                           ReleaseYear = (string)i.Descendants("release_year").FirstOrDefault(),
                                           Link = (string)i.Descendants("link").Where(x => (string) x.Attribute("rel") == "alternate").Attributes("href").FirstOrDefault()
                                       };
                var model = new {Response = response, Items = items}.ToExpando();
                return View(model);
            }
            return View(new {Response = response, Items = (object) null}.ToExpando());
        }
        /**
         * ASync callback for posting a new photo
         **/
        public void PostCompleted(RestRequest request, RestResponse response, object target)
        {
            Dispatcher.BeginInvoke(() => this.postProgress.Visibility = System.Windows.Visibility.Collapsed);
            this.isPosting = false;
            // HACK: This is kind of hacky...
            Dispatcher.BeginInvoke(() => ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true);

            if (response.StatusCode == HttpStatusCode.Created)
            {
                Dispatcher.BeginInvoke(() => {
                    MessageBox.Show("Photo Posted Successfully!");
                    this.captionTextbox.IsEnabled = true;

                    // Reset photo and caption
                    this.hasDefaultText = true;
                    this.captionTextbox.Text = "Enter a Caption...";
                    this.captionTextbox.TextAlignment = TextAlignment.Center;
                    this.captionTextbox.Foreground = this.Resources["InactiveTextBrush"] as Brush;

                    this.photo = null;
                    this.photoPreview.Source = new BitmapImage(new Uri("/Images/photo_icon.png", UriKind.Relative));
                    this.photoPreview.Stretch = Stretch.None;
                    this.photoPreview.SetValue(Canvas.MarginProperty, new Thickness(9, 69, 6, 0));
                });
            }
            else
            {
                Dispatcher.BeginInvoke(() => {
                    MessageBox.Show("Error Posting Photo: " + response.Content);
                    this.captionTextbox.IsEnabled = true; // Re-enable the text box
                });
            }
        }
Exemplo n.º 9
0
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            RestClient client2 = new RestClient
            {
                Authority = "https://graph.facebook.com/",
            };

            RestRequest request2 = new RestRequest
            {
                Path = "/me/feed?message=" + WatermarkTB.Text
            };
            if (imgstream != null)
            {
                string albumId = (string)settings["facebook_photo"];
                request2 = new RestRequest
                {
                    Path = albumId + "/photos?message=" + WatermarkTB.Text
                };
                request2.AddFile("photo", "image.jpg", imgstream);
            }
            request2.AddField("access_token", (string)settings["facebook_token"]);
            var callback = new RestCallback(
                (restRequest, restResponse, userState) =>
                {
                    // Callback when signalled
                }
                );
            client2.BeginRequest(request2, callback);

            MessageBox.Show("Share successfully.", "Thanks", MessageBoxButton.OK);
            this.NavigationService.GoBack();
        }
Exemplo n.º 10
0
        public void fetchXml()
        {
            User = usernamBox.Text.Replace(" ", "").Replace("/", "").Replace(".", "");
            URL = new Uri("http://" + User + ".tumblr.com/api/read/json");

            int max = 0;
            var client = new RestClient();
            client.Authority = URL.ToString();
            var request = new RestRequest();
            request.AddParameter("type", "photo");
            request.AddParameter("num", "50");
            request.AddParameter("filter", "text");
            var r1 = client.Request(request);
            var t = r1.Content.ToString().Replace("var tumblr_api_read = ", "");
            var firstResponse = JsonParser.FromJson(t);
            max = Convert.ToInt32(firstResponse["posts-total"]);
            // to eventually make each fetch a separate request
            for (int i = 0; i < max; i += 51)
            {
                if (i != 0)
                {
                    request.AddParameter("start", i.ToString());
                }
                var r2 = client.Request(request);
                var t2 = r2.Content.ToString().Replace("var tumblr_api_read = ", "");
                var Response = JsonParser.FromJson(t2);

                getUrls(Response.ToDictionary(x => x.Key, x => x.Value));
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// ステータスを更新します
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="accessTokenSecret"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static dynamic UpdateStatus(string accessToken, string accessTokenSecret, string message)
        {
            var client = new RestClient
            {
                Authority = "http://api.twitter.com",
                UserAgent = "OAuthSample",
            };

            var credentials = OAuthCredentials.ForProtectedResource(
                Config.TwitterConsumerKey,
                Config.TwitterConsumerSecret,
                accessToken,
                accessTokenSecret);
            credentials.ParameterHandling = OAuthParameterHandling.UrlOrPostParameters;

            var request = new RestRequest
            {
                Path = "statuses/update.json",
                Method = WebMethod.Post,
                Credentials = credentials,
            };

            request.AddParameter("status", message);

            var response = client.Request(request);
            return DynamicJson.Parse(response.Content);
        }
Exemplo n.º 12
0
        public string MakeYahooPostSample()
        {
            var client = new RestClient
                         	{
                         		Authority = "http://api.search.yahoo.com/ContentAnalysisService",
                         		VersionPath = "V1"
                         	};
            var request = new RestRequest
                          	{
                          		Path = "termExtraction",
                                Method = WebMethod.Post
                          	};

            var appId = "YahooDemo";
            var context = "Italian sculptors and painters of the renaissance favored the Virgin Mary for inspiration";
            var query = "madonna";

            request.AddField("appid", appId);
            request.AddField("context", context);
            request.AddField("query", query);

            var response = client.Request(request);

            return response.Content;
        }
Exemplo n.º 13
0
 public void modifiedEntryCallback(RestRequest request, Hammock.RestResponse response, object obj)
 {
     if (response.StatusCode == HttpStatusCode.OK)
         Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/JumpPage.xaml", UriKind.RelativeOrAbsolute)));
     else
         Dispatcher.BeginInvoke(() => MessageBox.Show(dbwp7Resources.FailedToDeleteTheEntry));
 }
Exemplo n.º 14
0
        public string GetTwitterRedirectUrl(string consumerKey, string consumerSecret, string CallBackUrl)
        {
            OAuthCredentials credentials = new OAuthCredentials()
            {
                Type = OAuthType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey = consumerKey,
                ConsumerSecret = consumerSecret,
                CallbackUrl = CallBackUrl
            };

            // Use Hammock to create a rest client
            var client = new RestClient
            {
                Authority = "https://api.twitter.com/oauth",
                Credentials = credentials
            };

            // Use Hammock to create a request
            var request = new RestRequest
            {
                Path = "request_token"
            };

            // Get the response from the request
            var response = client.Request(request);

            var collection = HttpUtility.ParseQueryString(response.Content);
            //string str = collection[1].ToString();
            //HttpContext.Current.Session["requestSecret"] = collection[1];
            string rest = "https://api.twitter.com/oauth/authorize?oauth_token=" + collection[0] + "~" + collection[1];

            return rest;
        }
Exemplo n.º 15
0
        private void GetTwitterToken()
        {
            var credentials = new OAuthCredentials
            {
                Type = OAuthType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey = Constants.ConsumerKey,
                ConsumerSecret = Constants.ConsumerKeySecret,
                Version = Constants.OAuthVersion,
                CallbackUrl = Constants.CallbackUri
            };
            var client = new RestClient
            {
                Authority = "https://api.twitter.com/oauth",
                Credentials = credentials,
                HasElevatedPermissions = true,
                SilverlightAcceptEncodingHeader = "gizp",
                DecompressionMethods = DecompressionMethods.GZip,
            };

            var request = new RestRequest
            {
                Path = "/request_token"
            };
            client.BeginRequest(request, new RestCallback(TwitterRequestTokenCompleted));
        }
Exemplo n.º 16
0
        public RestResponse GetFavorites(string user, int page, int pageSize)
        {
            // Documentation for GET /favorites
            // https://dev.twitter.com/docs/api/1/get/favorites

            // Create the REST Client
            var client = new RestClient {Authority = "http://api.twitter.com/1"};

            // Create the REST Request
            var request = new RestRequest {Path = "favorites.json", Method = WebMethod.Get};
            request.AddParameter("id", user);
            request.AddParameter("page", page.ToString());
            request.AddParameter("count", pageSize.ToString());

            // Set API authentication tokens
            var appSettings = ConfigurationManager.AppSettings;
            request.Credentials = OAuthCredentials.ForProtectedResource(
                appSettings["ConsumerKey"], appSettings["ConsumerSecret"], appSettings["Token"],
                appSettings["TokenSecret"]);

            // Make request
            var response = client.Request(request);

            return response;
        }
Exemplo n.º 17
0
        private static string RetrieveTweets(string sinceId)
        {
            BasicAuthCredentials credentials = new BasicAuthCredentials
                                                   {
                                                       Username = WebConfigurationManager.AppSettings["ScreenName"],
                                                       Password = WebConfigurationManager.AppSettings["SuperTweetPassword"]
                                                   };
            RestClient client = new RestClient
                                    {
                                        Authority = "http://api.supertweet.net",
                                        VersionPath = "1"
                                    };

            string possibleSinceId = string.IsNullOrWhiteSpace(sinceId) ? "": string.Format("&since_id={0}", sinceId) ;

            RestRequest request = new RestRequest
                                      {
                                          Credentials = credentials,
                                          Path = string.Format("statuses/home_timeline.json?count=200&include_entities=false{0}", possibleSinceId)
                                      };
            RestResponse response = client.Request(request);

            var content = response.Content;
            return content;
        }
Exemplo n.º 18
0
        public void GetComments(String id, int count, GetCommentsCompleteHandler handler)
        {
            if (m_netEngine == null)
                m_netEngine = new DoubanNetEngine();
            RestRequest request = new RestRequest();
            request.Method = WebMethod.Get;
            request.Path = String.Format("shuo/v2/statuses/{0}/comments", id);
            request.AddParameter("count", count.ToString());

            m_netEngine.SendRequest(request, (DoubanSdkResponse response) =>
            {
                if (response.errCode == DoubanSdkErrCode.SUCCESS)
                {
                    GetCommentsEventArgs args = new GetCommentsEventArgs();
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Comment>));
                    List<Comment> list = ser.ReadObject(response.stream) as List<Comment>;
                    args.comments = list;
                    args.errorCode = DoubanSdkErrCode.SUCCESS;
                    args.specificCode = response.specificCode;
                    handler(args);
                }
                else
                {
                    GetCommentsEventArgs args = new GetCommentsEventArgs();
                    args.comments = null;
                    args.errorCode = response.errCode;
                    args.specificCode = response.specificCode;
                    handler(args);
                }
            });
        }
Exemplo n.º 19
0
        public void AddComments(String id, String text, CompleteHandler handler)
        {
            if (m_netEngine == null)
                m_netEngine = new DoubanNetEngine();
            RestRequest request = new RestRequest();
            request.Method = WebMethod.Post;
            request.Path = String.Format("shuo/v2/statuses/{0}/comments", id);
            request.AddParameter("text", text);
            request.AddParameter("source", DoubanSdkData.AppKey);

            m_netEngine.SendRequest(request, (DoubanSdkResponse response) =>
            {
                if (response.errCode == DoubanSdkErrCode.SUCCESS)
                {
                    DoubanEventArgs args = new DoubanEventArgs();
                    args.errorCode = DoubanSdkErrCode.SUCCESS;
                    args.specificCode = response.specificCode;
                    handler(args);
                }
                else
                {
                    DoubanEventArgs args = new DoubanEventArgs();
                    args.errorCode = response.errCode;
                    args.specificCode = response.specificCode;
                    handler(args);
                }
            });
        }
Exemplo n.º 20
0
        public void BeginUserRealtimeLinks(BitlyLogin user, RestCallback callback)
        {
            var request = new RestRequest {Path = "user/realtime_links"};
            request.AddParameter("format", "json");
            request.AddParameter("access_token", user.access_token);

            _sslClient.BeginRequest(request, callback);
        }
Exemplo n.º 21
0
        private void mealListGetCallback(RestRequest request, Hammock.RestResponse response, object obj)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(MealNames[]));
            meals = json.ReadObject(response.ContentStream) as MealNames[];

            if (MealListLoaded != null)
                MealListLoaded(this, new EventArgs());

        }
Exemplo n.º 22
0
 private void excerciseQueryCallback(RestRequest request, Hammock.RestResponse response, object obj)
 {
     if (response.StatusCode == HttpStatusCode.OK)
     {
         DataContractJsonSerializer jSon = new DataContractJsonSerializer(typeof(ExcerciseSet[]));
         sets = jSon.ReadObject(response.ContentStream) as ExcerciseSet[];
     }
     OnWorkoutLoaded();
 }
Exemplo n.º 23
0
        private void EndGetRequestUrl(RestRequest request, RestResponse response, object userState)
        {
            var r = new Regex("oauth_token=([^&.]*)&oauth_token_secret=([^&.]*)");
            Match match = r.Match(response.Content);
            ((OAuthCredentials)Credentials).Token = match.Groups[1].Value;
            ((OAuthCredentials)Credentials).TokenSecret = match.Groups[2].Value;

            RequestUrlCallback(request, response, String.Format("{0}{1}?{2}", OAuthBase, TokenAuthUrl, response.Content));
        }
Exemplo n.º 24
0
 internal TwitterStream(OAuthCredentials credential, string authority, RestRequest request=null)
 {
     _credential = credential;
     _authority = authority;
     if (request != null)
         Request = request;
     else
         Request = new RestRequest();
 }
Exemplo n.º 25
0
        protected override RestRequest CreateAuthTokensRequest()
        {
            var request = new RestRequest
            {
                Path = "/oauth/request_token/"
            };

            return request;
        }
Exemplo n.º 26
0
        /// <summary>
        /// ログインユーザ情報を取得します
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static dynamic GetUserInformation(string accessToken)
        {
            // see http://developers.facebook.com/docs/reference/api/user/

            var client = new RestClient { Authority = "https://graph.facebook.com/" };
            var request = new RestRequest { Path = "me" };
            request.AddParameter("access_token", accessToken);
            var response = client.Request(request);
            return DynamicJson.Parse(response.Content);
        }
        /**
         * Called when we finally need the access token!
         **/
        public void AccessTokenCallback(RestRequest request, RestResponse response, object target)
        {
            string queryString = response.Content;

            // Get the FINAL tokens
            userCredentials.OAuthToken = Common.GetValueFromQueryString(queryString, "oauth_token");
            userCredentials.OAuthTokenSecret = Common.GetValueFromQueryString(queryString, "oauth_token_secret");

            Dispatcher.BeginInvoke(() => this.oAuthClearButton.Visibility = System.Windows.Visibility.Visible);
        }
Exemplo n.º 28
0
        public void GetRequestToken(OAuthCredentials oaCredentials)
        {
            oaCredentials.Type = OAuthType.RequestToken;
            RestRequest rrRequest = new RestRequest
            {
                Path = C_REQUEST_TOKEN_URL
            };

            DoRequest(rrRequest, oaCredentials, new APIReturn(GetRequestTokenCallback, null, oaCredentials));
        }
Exemplo n.º 29
0
        protected override RestRequest CreateTokensRequest(NameValueCollection parameters)
        {
            var request = new RestRequest
            {
                Path = "/oauth/access_token/",
                DecompressionMethods = Hammock.Silverlight.Compat.DecompressionMethods.None
            };

            return request;
        }
Exemplo n.º 30
0
        /// <summary>
        /// Adds a URL to Pocker with reference to the tweet which generated it.
        /// </summary>
        /// <param name="url">URL to save.</param>
        /// <param name="tweetId">Tweet ID.</param>
        /// <param name="action">Callback.</param>
        public void AddUrl(string url, long tweetId, Action<ReadLaterResponse> action)
        {
            if (_client == null)
                InitRestClient();

            RestRequest request = new RestRequest
            {
                Path = "add?" + GetCredentials() + "&ref_id=" + tweetId.ToString() + "&url=" + url + "&apikey=" + SensitiveData.PocketAPIKey
            };

            _client.BeginRequest(request, AddUrlCallback, action);
        }
Exemplo n.º 31
-1
 private void PostTweetRequestCallback(RestRequest request, RestResponse response, object obj)
 {
     if (response.StatusCode == System.Net.HttpStatusCode.OK)
     {
         //Success code
     }
 }