Exemplo n.º 1
0
        public ActionResult CodeProject(string method)
        {
            try
            {
                if (Session["CodeProject:AccessToken"] == null)
                {
                    throw new Exception(Test.Resources.Strings.SessionIsDead);
                }

                var token = (OAuth2AccessToken)Session["CodeProject:AccessToken"];

                // execute the request
                var result = OAuthUtility.Get
                             (
                    "https://api.codeproject.com/v1/Articles",
                    new HttpParameterCollection
                {
                    { "tags", "asp.net,c#,vb.net" }
                },
                    authorization: new HttpAuthorization(AuthorizationType.Bearer, token.Value)
                             );

                return(Content(result.ToString(), "text/plain"));
            }
            catch (Exception ex)
            {
                return(Content(ex.ToString(), "text/plain"));
            }
        }
Exemplo n.º 2
0
        private void ButtonAuthenticate_Click(object sender, EventArgs e)
        {
            if (AuthTokenResponse == null)
            {
                AppendLineToOutput("Already authenticated. Check ratelimiting details.");
                return;
            }

            AuthTokenResponse = OAuthUtility.GetAccessToken(Settings.Default.ConsumerKey,
                                                            Settings.Default.ConsumerSecret,
                                                            AuthTokenResponse.Token,
                                                            TextBoxInput.Text);

            var tokenResponse = AuthTokenResponse;

            Settings.Default.UserAccessToken  = tokenResponse.Token;
            Settings.Default.UserAccessSecret = tokenResponse.TokenSecret;
            Settings.Default.Save();

            Tokens.AccessToken       = Settings.Default.UserAccessToken;
            Tokens.AccessTokenSecret = Settings.Default.UserAccessSecret;

            CommandManagement.Init(this, Tokens);

            AppendLineToOutput("Authentication succeeded.");
        }
Exemplo n.º 3
0
        /// <summary>
        /// Gets the user details.
        /// </summary>
        /// <param name="accessToken">May contain an access token, which will have to be used in obtaining information about the user.</param>
        /// <returns>
        /// <para>Returns an instance of the <see cref="UserInfo"/> class, containing information about the user.</para>
        /// </returns>
        public override UserInfo GetUserInfo(AccessToken accessToken = null)
        {
            accessToken = base.GetSpecifiedTokenOrCurrent(accessToken);

            // execute the request
            var result = OAuthUtility.Get
                         (
                "https://api.assembla.com/v1/user.json",
                accessToken: accessToken
                         );

            // help: http://api-doc.assembla.com/content/ref/user_show.html
            // http://api-doc.assembla.com/content/ref/user_fields.html

            // field mapping
            var map = new ApiDataMapping();

            map.Add("id", "UserId", typeof(string));
            map.Add("login", "UserName", typeof(string));
            map.Add("name", "DisplayName");
            map.Add("email", "Email");
            map.Add("phone", "Phone");

            // parse the server response and returns the UserInfo instance
            return(new UserInfo(result, map));
        }
Exemplo n.º 4
0
        public void ExecuteRequestTest()
        {
            var parameters = new HttpParameterCollection
            {
                { "content", "hello world!" },
                { "contentType", "text/plain" }
            };

            var result = OAuthUtility.Get("http://api.foxtools.ru/v2/Http", parameters);

            Assert.True(result.Contains("hello world!"));

            parameters = new HttpParameterCollection
            {
                { Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAFUAAABVCAYAAAA49ahaAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsIAAA7CARUoSoAAAAR/SURBVHhe7ZDRbiMxDAPv/3+6px62gDomzGVsb+4hA0wNiJSS5k/x9aSO3X3mp70+U4endOzuMz/t9Zk6PKVjd5/5aa/P1OEpHbv7zE97feY43Im7n+ZO4vJV1P16x+FO3P00dxKXr6Lu1zsOd+Lup7mTuHwVdb/ecbgTdz/NncTlq6j79Y7DDnMnSXNKVKdL0txJVF7vOOwwd5I0p0R1uiTNnUTl9Y7DDnMnSXNKVKdL0txJVF7vOOwwd5I0p0R1uiTNnUTl9Y7DDnMnSfNUh+szdxKV1zsOO8ydJM1THa7P3ElUXu847DB3kjRPdbg+cydReb3jsMPcSdI81eH6zJ1E5fWOww5zJ3E5cX3mlKS5k6i83nHYYe4kLieuz5ySNHcSldc7DjvMncTlxPWZU5LmTqLyesdhh7mTuJy4PnNK0txJVF7vONzJu++7fBV1v95xuJN333f5Kup+veNwJ+++7/JV1P16x+FO3n3f5auo+/X+Hp6WPJ2f9vpMHZ6SPJ2f9vpMHZ6SPJ2f9vpMHZ6SPJ2f9t9n/vv7RtSXmsE+/R/4/KgH+PyoB/j8qAeo73H2S7n7zKlD7cx0qJ2Zipr70gruPnPqUDszHWpnpqLmvrSCu8+cOtTOTIfamamouS+t4O4zpw61M9OhdmYq7KeoQzMdaqebom50HWpn5h0+P6rYmXmHz48qdmbe4fOjip2Zd6ieXv5xFXWzm+L2mVOH2pmpqLku/7iKutlNcfvMqUPtzFTUXJd/XEXd7Ka4febUoXZmKmquyz+uom52U9w+c+pQOzMVy7/anQ+ZwX2aku6z7yQqz781UEcTuE9T0n32nUTl+bcG6mgC92lKus++k6g8/9ZAHU3gPk1J99l3EpXn3xqoox2XO9J99qkj7Ste22q4L+FyR7rPPnWkfcVrWw33JVzuSPfZp460r3htq+G+hMsd6T771JH2Fa9tbYT/hJO43MF9+gqfHxX79BU+Pyr26St8flTs01eoPX3slClunzklae5U1FyXT5ni9plTkuZORc11+ZQpbp85JWnuVNRcl0+Z4vaZU5LmTkXNfWmFp++nEtXpEpXXOw538vT9VKI6XaLyesfhTp6+n0pUp0tUXu843MnT91OJ6nSJyusdhx3mTuJywj51qJ0ucTlhn16dcdhh7iQuJ+xTh9rpEpcT9unVGYcd5k7icsI+daidLnE5YZ9enXHYYe4kLifsU4fa6RKXE/bp1RmHHeZO4nJHun+6f4e6Mz/K3Elc7kj3T/fvUHfmR5k7icsd6f7p/h3qzvwocydxuSPdP92/Q92ZH2XuJC53uP2nc+e1Mw47zJ3E5Q63/3TuvHbGYYe5k7jc4fafzp3XzjjsMHcSlzvc/tO589oZhztJ77NPiep0HWpn5h2qly8lpPfZp0R1ug61M/MO1cuXEtL77FOiOl2H2pl5h+rlSwnpffYpUZ2uQ+3MvEP19PIpSZrvlqzm39T8d+m0JM13S1bzb2r+u3Rakua7Jav5NzX/XTotSfPdktX8Gz39sMDX11/4Q2CGtGAk5wAAAABJRU5ErkJggg==") },
                { "test", 123 },
                { new HttpFormParameter("x", "y") },
                { new HttpFormParameter("a", "bc") },
                { "contentType", "text/plain" }
            };

            result = OAuthUtility.Post("http://api.foxtools.ru/v2/Http", parameters);

            Assert.True(result.ToString().IndexOf("PNG") != -1);

            parameters = new HttpParameterCollection
            {
                { new HttpFile("file1", "test.png", "image/png", Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAEAAAAA/CAYAAABQHc7KAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDoAABSCAABFVgAADqXAAAXb9daH5AAACLOSURBVHja5Jp3VNTXtsd/gBRFEJA2wNBhYBgcYGboQxuGNggIIlUEISgan8ZrucbEFpNAosaSGEuaqBRJ0dhNTIiioMbevVFjiSWWaK6x6+f98/glXPG1de99d6131vouBmbWcPbn7L3PPvv8BED4/ywBEAYPHvxcDRkyRKiurhYmTJggvPbaa8Ls2bOFRYsWCU1NTcKOHTuE/fv3C+fOnRNu374tnDt3Tti/f7/Q2toqtLS0CJ988okwd+5cy9deey1s4sSJhTU1Na+WlZUtKSgo+DorK+u0Xq+/rtVqL2k0mn3BwcFNfn5+s/z8/EZ4eHjobWxs3GxsbIx69+4tmJqaCqampoKRkZHwvGFsbCz07t1bMDY2Fn+3s7MTnJ2dBScnp271DwGwb98+obW11e2zzz4rr6+vb1iwYMHp2bNnP5w9ezbz589n6dKl1NfX09jYSFNTE8uXL2fx4sXU1tYyZswYcnNzUavVTx0dHX/p1avXdhMTkxmmpqYxpqampv/qAHpcuHBBf/jw4Yb29vabra2tbNu2jf3793P69GmuXbvGnTt3uH//Pk+ePOF54+HDh1y+fJm2tjbmzJlDWloatra2TwRB2C8IwjhBEFz/1QCYnDt3LvuXX37ZfuPGDc6dO8e5c+e4ceMGv/76K7/++iu3b98WXz948ICWlhamTZvG9evXaWxspK6ujtu3b/PkyRMRzp07d/jtt98AOHv2LK+//joymQxBEK4JglAnCILb/zmAbdu2he7du3fjyZMnuXjxIleuXBH1/fff88MPP3D79m1u3LjBzZs3uXXrFo8ePWLmzJkkJCTw008/8eqrr5KWlsbVq1d58uQJDx48AKC2tpaAgABmzpzJ8ePHRSgffvghcnkQgiBcEQRhjCAIFv90AIsXLzZvbm6evGHDht/27NnDmTNnuHjx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8/v+mtt96aNXPmzBGvvPKKfty4cdLRo0cbDR06VCgqKhKKioqEfxiA/8/69wEAGjgk0I9Qd/wAAAAASUVORK5CYII=")) },
                { "dd", 20 },
                { "id", 13 },
                { new HttpFormParameter("key", "e91268b7-1162-4044-9236-7191c8c3b5d2") },
                { "contentType", "text/plain" }
            };

            result = OAuthUtility.Post("http://api.foxtools.ru/v2/Http", parameters);

            Assert.True(result.ToString().Contains("test.png"));
            Assert.True(result.ToString().Contains("e91268b7-1162-4044-9236-7191c8c3b5d2"));

            using (var fs = new FileStream(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "oauth.dat"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                parameters = new HttpParameterCollection
                {
                    { new HttpFile("file1", "123.png", "image/png", fs) },
                    { "dd", 20 },
                    { "id", 13 },
                    { "key", "e91268b7-1162-4044-9236-7191c8c3b5d2" },
                    { "contentType", "text/plain" }
                };

                result = OAuthUtility.ExecuteRequest("POST", "http://api.foxtools.ru/v2/Http", parameters);

                Assert.True(result.ToString().Contains("123.png"));
            }

            result = OAuthUtility.Get("https://github.com/alekseynemiro/nemiro.oauth.dll/archive/master.zip");

            Assert.True(result.IsFile);
            Assert.Contains("master.zip", result.FileName);
        }
Exemplo n.º 5
0
        internal OAuthTokenResponse GetTwitterRequestToken()
        {
            try {
                if (PortalSettings.CustomSettings.ContainsKey("SITESETTINGS_TWITTER_APP_ID") &&
                    !PortalSettings.CustomSettings["SITESETTINGS_TWITTER_APP_ID"].ToString().Equals(string.Empty) &&
                    PortalSettings.CustomSettings.ContainsKey("SITESETTINGS_TWITTER_APP_SECRET") &&
                    !PortalSettings.CustomSettings["SITESETTINGS_TWITTER_APP_SECRET"].ToString().Equals(string.Empty))
                {
                    string appId     = PortalSettings.CustomSettings["SITESETTINGS_TWITTER_APP_ID"].ToString();
                    var    appSecret = PortalSettings.CustomSettings["SITESETTINGS_TWITTER_APP_SECRET"].ToString();

                    string server = ConvertRelativeUrlToAbsoluteUrl(HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/SignIn/LogInTweeter.aspx"));                        //ConvertRelativeUrlToAbsoluteUrl("~/DesktopModules/CoreModules/SignIn/LogInTweeter.aspx");
                    Session["TwitterAppId"]     = appId;
                    Session["TwitterAppSecret"] = appSecret;

                    OAuthTokenResponse requestToken = OAuthUtility.GetRequestToken(appId, appSecret, server);

                    return(requestToken);
                }

                return(null);
            } catch (Exception) {
                return(null);
            }
        }
Exemplo n.º 6
0
        private void GetFiles()
        {
            // help: https://developers.google.com/drive/v2/reference/files/list

            this.Cursor = Cursors.WaitCursor;

            string q = "trashed=false";

            if (!String.IsNullOrEmpty(this.CurrentFolderId))
            {
                q = String.Format("'{0}' in parents and {1}", this.CurrentFolderId, q);
            }
            else
            {
                q = String.Format("'{0}' in parents and {1}", "root", q);
            }

            OAuthUtility.GetAsync
            (
                "https://www.googleapis.com/drive/v2/files",
                parameters: new HttpParameterCollection
            {
                { "maxResults", "1000" },
                { "q", q }
            },
                authorization: new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken),
                callback: GetFiles_Result
            );
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Twitter"/> class.
        /// </summary>
        public Twitter()
        {
            _consumerKey    = Configuration.singleton( )["twitterConsumerKey"];
            _consumerSecret = Configuration.singleton( )["twitterConsumerSecret"];

            _accessToken       = Configuration.singleton( )["twitterAccessToken"];
            _accessTokenSecret = Configuration.singleton( )["twitterAccessTokenSecret"];



            if (Configuration.singleton()["twitterRequestToken"] != "" || (_accessToken != "" && _accessTokenSecret != ""))
            {
                return;
            }

            try
            {
                OAuthTokenResponse tkn = OAuthUtility.GetRequestToken(_consumerKey, _consumerSecret);
                Configuration.singleton( )["twitterRequestToken"] = tkn.Token;


                Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(tkn.Token);



                Helpmebot6.irc.ircPrivmsg(Helpmebot6.debugChannel,
                                          "Please authorise access to Twitter: " + authorizationUri);
            }
            catch (TwitterizerException ex)
            {
                GlobalFunctions.errorLog(ex);
            }
        }
Exemplo n.º 8
0
        public string GetAuthorizationUrl()
        {
            requestToken = OAuthUtility.GetRequestToken(consumerToken.Key, consumerToken.Secret, "oob");
            var authorizationUri = OAuthUtility.BuildAuthorizationUri(requestToken.Token);

            return(authorizationUri.AbsoluteUri);
        }
Exemplo n.º 9
0
    HttpWebRequest FetchAccessToken(httpMethod method, string oauth_consumer_key, string oauth_consumer_secret, string oauth_token, string oauth_verifier)
    {
        string postData       = "oauth_verifier=" + oauth_verifier;
        string AccessTokenURL = string.Format("{0}?{1}", ACCESS_TOKEN, postData);
        string OAuthHeader    = OAuthUtility.GetAuthorizationHeaderForPost_OR_QueryParameterForGET(new Uri(AccessTokenURL), callbackUrl, method.ToString(), oauth_consumer_key, oauth_consumer_secret, oauth_token, "", out AccessTokenURL);

        if (method == httpMethod.GET)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(AccessTokenURL + "?" + OAuthHeader);
            request.Method = method.ToString();
            return(request);
        }
        else if (method == httpMethod.POST)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(AccessTokenURL);
            request.Method = method.ToString();
            request.Headers["Authorization"] = OAuthHeader;

            byte[] array = Encoding.ASCII.GetBytes(postData);
            request.GetRequestStream().Write(array, 0, array.Length);
            return(request);
        }
        else
        {
            return(null);
        }
    }
Exemplo n.º 10
0
        /// <summary>
        /// Sends a request to refresh the access token.
        /// </summary>
        /// <param name="accessToken">May contain an access token, which should be refreshed.</param>
        /// <remarks>
        /// <para>If <paramref name="accessToken"/> parameter is not specified, it will use the current access token from the same property of the current class instance.</para>
        /// <para>Token must contain the <b>refresh_token</b>, which was received together with the access token.</para>
        /// </remarks>
        /// <exception cref="NotSupportedException">
        /// <para>Provider does not support refreshing the access token, or the method is not implemented.</para>
        /// <para>Use the property <see cref="OAuthBase.SupportRefreshToken"/>, to check the possibility of calling this method.</para>
        /// </exception>
        /// <exception cref="AccessTokenException">
        /// <para>Access token is not found or is not specified.</para>
        /// <para>-or-</para>
        /// <para><b>refresh_token</b> value is empty.</para>
        /// </exception>
        /// <exception cref="RequestException">Error during execution of a web request.</exception>
        public override AccessToken RefreshToken(AccessToken accessToken = null)
        {
            if (!this.SupportRefreshToken)
            {
                throw new NotSupportedException();
            }

            var token = (OAuth2AccessToken)base.GetSpecifiedTokenOrCurrent(accessToken, refreshTokenRequired: true);

            var parameters = new HttpParameterCollection();

            parameters.AddFormParameter("access_token", token.Value);
            parameters.AddFormParameter("client_id", this.ApplicationId);
            parameters.AddFormParameter("client_secret", this.ApplicationSecret);
            parameters.AddFormParameter("grant_type", GrantType.RefreshToken);
            parameters.AddFormParameter("refresh_token", token.RefreshToken);

            var result = OAuthUtility.Post
                         (
                this.AccessTokenUrl,
                parameters: parameters
                         );

            return(new OAuth2AccessToken(result));
        }
Exemplo n.º 11
0
        public TwitterClient()
        {
            if (File.Exists(mutefile))
            {
                Logger.WriteLine("No tweeting!");
                return;
            }
            string[] keys = File.ReadAllLines("c");

            tokens.ConsumerKey    = keys[0];
            tokens.ConsumerSecret = keys[1];
            if (!File.Exists("d"))
            {
                var response = OAuthUtility.GetRequestToken(keys[0], keys[1], "oob");
                Console.WriteLine(response.Token);

                Console.WriteLine(string.Format("Go to: http://twitter.com/oauth/authorize?oauth_token={0}", response.Token));

                Console.Write("PIN: ");
                string pin = Console.ReadLine();

                var access = OAuthUtility.GetAccessToken(keys[0], keys[1], response.Token, pin);

                File.WriteAllLines("d", new string[] { access.Token, access.TokenSecret });
                Console.WriteLine("Done?");
            }
            string[] lines = File.ReadAllLines("d");

            tokens.AccessToken       = lines[0];
            tokens.AccessTokenSecret = lines[1];
            k = true;
        }
Exemplo n.º 12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string consumerKey    = "lGHwH8UWgDc4O98M3ocGYg";                //Resources.OAuth.Twitter_App_ID;
        string consumerSecret = "Ha2c5PNlKS9N9Vh04lXBquERBdhL0kUw0PQcc"; //Resources.OAuth.Twitter_App_SecretKey;

        if (Request["oauth_verifier"] == null)
        {
            string redirectTwitterUrl = Request.Url.Scheme + "://" + Request.Url.Host +
                                        @"/Auth/Twitter/TwitterMakeAuth.aspx";

            // Obtain a request token
            OAuthTokenResponse requestToken = OAuthUtility.GetRequestToken(consumerKey, consumerSecret,
                                                                           redirectTwitterUrl);

            // Direct or instruct the user to the following address:
            Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(requestToken.Token);

            Response.Redirect(authorizationUri.AbsoluteUri);
        }
        else if (Request["oauth_token"] != null && Request["oauth_verifier"] != null)
        {
            string oauth_token    = Request["oauth_token"];
            string oauth_verifier = Request["oauth_verifier"];

            OAuthTokenResponse userInfo = OAuthUtility.GetAccessToken(consumerKey, consumerSecret, oauth_token,
                                                                      oauth_verifier);
            string userName = userInfo.ScreenName;

            TwitterResponse <TwitterUser> user = TwitterUser.Show(userName);
            Response.Write(user.ResponseObject.Name);
        }
    }
Exemplo n.º 13
0
        /// <summary>
        /// Gets the user details.
        /// </summary>
        public override UserInfo GetUserInfo()
        {
            // query parameters
            var parameters = new NameValueCollection
            {
                { "access_token", this.AccessToken["access_token"].ToString() }
            };

            // execute the request
            var result = OAuthUtility.ExecuteRequest
                         (
                "GET",
                "https://api.amazon.com/user/profile",
                parameters
                         );

            // field mapping
            var map = new ApiDataMapping();

            map.Add("user_id", "UserId");
            map.Add("name", "DisplayName");
            map.Add("email", "Email");

            // parse the server response and returns user info
            return(new UserInfo(result.Result as Dictionary <string, object>, map));
        }
Exemplo n.º 14
0
        public ActionResult Google(string method)
        {
            try
            {
                if (Session["Google:AccessToken"] == null)
                {
                    throw new Exception(Test.Resources.Strings.SessionIsDead);
                }

                // get access token from session
                var token = (OAuth2AccessToken)Session["Google:AccessToken"];

                // set parameters
                var parameters = new NameValueCollection
                {
                    { "access_token", token.Value }
                };

                string url = String.Format("https://www.google.com/m8/feeds/contacts/{0}/full", HttpUtility.UrlEncode(Session["Google:Email"].ToString()));

                // execute the request
                var result = OAuthUtility.ExecuteRequest("GET", url, parameters);

                return(Content(result.ToString(), "text/plain"));
            }
            catch (Exception ex)
            {
                return(Content(ex.ToString(), "text/plain"));
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Gets the authorize URL.
        /// </summary>
        /// <param name="consumerAppIdent">The consumer app ident.</param>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns>Authorize URL.</returns>
        public string GetAuthorizeUrl(ConsumerAppIdent consumerAppIdent, string returnUrl)
        {
            var requestToken = OAuthUtility.GetRequestToken(
                consumerAppIdent.ConsumerKey, consumerAppIdent.ConsumerSecret, returnUrl);

            return(OAuthUtility.BuildAuthorizationUri(requestToken.Token).AbsoluteUri);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Gets an user details.
        /// </summary>
        /// <param name="accessToken">May contain an access token, which will have to be used in obtaining information about the user.</param>
        /// <returns>
        /// <para>Returns an instance of the <see cref="UserInfo"/> class, containing information about the user.</para>
        /// </returns>
        public override UserInfo GetUserInfo(AccessToken accessToken = null)
        {
            // api documentation:
            // https://www.tumblr.com/docs/en/api/v2#user-methods

            accessToken = base.GetSpecifiedTokenOrCurrent(accessToken);

            this.Authorization["oauth_token"] = accessToken["oauth_token"].ToString();
            this.Authorization.TokenSecret    = accessToken["oauth_token_secret"].ToString();
            // required new stamp
            this.Authorization.Timestamp = OAuthUtility.GetTimeStamp();
            this.Authorization.Nonce     = OAuthUtility.GetRandomKey();

            // execute the request
            var result = OAuthUtility.Get
                         (
                endpoint: "https://api.tumblr.com/v2/user/info",
                parameters: new HttpParameterCollection {
                new HttpUrlParameter("api_key", this.ApplicationId)
            },
                authorization: this.Authorization
                         );

            // field mapping
            var map = new ApiDataMapping();

            map.Add("id", "UserId", typeof(string));
            map.Add("name", "DisplayName");

            // parse the server response and returns the UserInfo instance
            return(new UserInfo(result["response"]["user"], map));
        }
Exemplo n.º 17
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (Request.QueryString["denied"] == null)
     {
         OAuthTokenResponse tokens = OAuthUtility.GetAccessToken(
             "ConsumerKey",
             "ConsumerKeySecret",
             Request.QueryString["oauth_token"], "");
         Dictionary <string, string> values = new Dictionary <string, string>();
         values["AccessToken"]  = tokens.Token;
         values["AccessSecret"] = tokens.TokenSecret;
         values["ScreenName"]   = tokens.ScreenName;
         values["UserId"]       = tokens.UserId.ToString();
         string   fileName = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 6).ToUpper();
         string[] theFiles = System.IO.Directory.GetFiles(Server.MapPath("App_Data/Users/"), tokens.ScreenName + ".*");
         if (theFiles.Length > 0)
         {
             fileName = new System.IO.FileInfo(theFiles[0]).Extension.Substring(1);
         }
         using (System.IO.StreamWriter str = new System.IO.StreamWriter(Server.MapPath("App_Data/Users/" + tokens.ScreenName + "." + fileName)))
         {
             str.Write(JsonConvert.SerializeObject(values));
         }
         txt_APIURL.Text = "http://twittr.me/" + tokens.ScreenName + "/" + fileName;
     }
     else
     {
         Response.Redirect("/");
     }
 }
Exemplo n.º 18
0
        /// <summary>
        /// Gets the user details.
        /// </summary>
        /// <returns>
        /// <para>Returns an instance of the <see cref="UserInfo"/> class, containing information about the user.</para>
        /// </returns>
        public override UserInfo GetUserInfo()
        {
            // query parameters
            var parameters = new NameValueCollection
            {
                { "access_token", this.AccessToken["access_token"].ToString() }
            };

            // execute the request
            var result = OAuthUtility.ExecuteRequest
                         (
                "GET",
                "https://api.dropbox.com/1/account/info",
                parameters,
                null
                         );

            // field mapping
            var map = new ApiDataMapping();

            map.Add("uid", "UserId", typeof(string));
            map.Add("display_name", "DisplayName");
            map.Add("email", "Email");

            // parse the server response and returns the UserInfo instance
            return(new UserInfo(result.Result as Dictionary <string, object>, map));
        }
Exemplo n.º 19
0
 public ActionResult Index()
 {
     try
     {
         if (HttpContext.Cache["LatestRelease"] == null)
         {
             var result = OAuthUtility.Get("https://www.nuget.org/api/v2/Search()?$orderby=Id&$skip=0&$top=30&searchTerm=%27Nemiro.OAuth%27&targetFramework=%27%27&includePrerelease=false");
             foreach (UniValue item in result["feed"]["entry"])
             {
                 if (item["properties"]["Id"].ToString().Equals("Nemiro.OAuth", StringComparison.OrdinalIgnoreCase))
                 {
                     ViewBag.Version = item["properties"]["Version"].ToString();
                     break;
                 }
             }
             HttpContext.Cache.Add("LatestRelease", ViewBag.Version, null, DateTime.Now.AddHours(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
         }
         else
         {
             ViewBag.Version = HttpContext.Cache["LatestRelease"].ToString();
         }
     }
     catch (Exception ex)
     {
         ViewBag.Version = "ERR: " + ex.Message;
     }
     return(View());
 }
Exemplo n.º 20
0
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = Application.StartupPath;
            //openFileDialog1.FileName = "version.txt";
            if (openFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            //MessageBox.Show(Path.GetFileName(openFileDialog1.FileName));
            OAuthUtility.PutAsync
            (
                "https://api-content.dropbox.com/1/files_put/auto/",
                new HttpParameterCollection
            {
                { "access_token", Properties.Settings.Default.AccessToken },
                { "path", Path.Combine(CurrentPath, Path.GetFileName(openFileDialog1.FileName)) },
                { "overwrite", "true" },
                { "autorename", "true" },
                { openFileDialog1.OpenFile() }
            },
                callback: Upload_Result
            );
        }
Exemplo n.º 21
0
        /// <summary>
        /// Gets the user details.
        /// </summary>
        /// <param name="accessToken">May contain an access token, which will have to be used in obtaining information about the user.</param>
        /// <remarks>
        /// <para>Access token must contain the user ID in the parameter <b>xoauth_yahoo_guid</b>.</para>
        /// </remarks>
        public override UserInfo GetUserInfo(AccessToken accessToken = null)
        {
            accessToken = base.GetSpecifiedTokenOrCurrent(accessToken);

            string url = String.Format("https://social.yahooapis.com/v1/user/{0}/profile?format=json", accessToken["xoauth_yahoo_guid"]);

            var result = OAuthUtility.Get
                         (
                endpoint: url,
                accessToken: accessToken
                         );

            var map = new ApiDataMapping();

            map.Add("guid", "UserId", typeof(string));
            map.Add("givenName", "FirstName");
            map.Add("familyName", "LastName");
            map.Add("nickname", "DisplayName");
            map.Add("profileUrl", "Url");
            map.Add("birthdate", "Birthday", typeof(DateTime), @"MM\/dd\/yyyy");
            map.Add
            (
                "gender", "Sex",
                delegate(UniValue value)
            {
                if (!value.HasValue)
                {
                    return(Sex.None);
                }
                if (value.Equals("M", StringComparison.OrdinalIgnoreCase))
                {
                    return(Sex.Male);
                }
                else if (value.Equals("F", StringComparison.OrdinalIgnoreCase))
                {
                    return(Sex.Female);
                }
                return(Sex.None);
            }
            );
            map.Add
            (
                "image", "Userpic",
                delegate(UniValue value)
            {
                return(Convert.ToString(value["imageUrl"]));
            }
            );
            map.Add
            (
                "phones", "Phone",
                delegate(UniValue value)
            {
                return(Convert.ToString(value["number"]));
            }
            );

            return(new UserInfo(result["profile"], map));
        }
Exemplo n.º 22
0
 private void GetRecentMedia()
 {
     OAuthUtility.GetAsync
     (
         String.Format("{0}/users/self/media/recent?access_token={1}", API_BASE_URL, this.AccessToken),
         callback: GetRecentMedia_Result
     );
 }
Exemplo n.º 23
0
        public async Task <string> GetPricePlan()
        {
            HttpClient client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            string json = await client.GetStringAsync(BaseUrl + "price_plan_details.json");

            return(json);
        }
Exemplo n.º 24
0
        public async Task <string> GetSims()
        {
            HttpClient client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            string json = await client.GetStringAsync(BaseUrl + "msisdn_list.json?alias=1");

            return(json);
        }
Exemplo n.º 25
0
        public async Task <string> GetBalance()
        {
            HttpClient client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            string json = await client.GetStringAsync(BaseUrl + "sim_balance.json");

            return(json);
        }
Exemplo n.º 26
0
        //REFERRALS
        public async Task <string> GetVikingPointsReferrals()
        {
            HttpClient client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            string json = await client.GetStringAsync(BaseUrl + "points/referrals.json");

            return(json);
        }
Exemplo n.º 27
0
 private void GetFiles()
 {
     OAuthUtility.GetAsync("https://api.dropboxapi.com/1/metadata/auto/", new HttpParameterCollection {
         { "path", CurrentPath },
         { "access_token", Properties.Settings.Default.AccessToken }
     }, callback: GetFiles_Result
                           );
 }
Exemplo n.º 28
0
        // see console app sample

        // sample flow for Twitter authroize
        //public async static Task<AccessToken> AuthorizeSample(string consumerKey, string consumerSecret)
        //{
        //    // create authorizer
        //    var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);

        //    // get request token
        //    var tokenResponse = await authorizer.GetRequestToken("https://api.twitter.com/oauth/request_token");
        //    var requestToken = tokenResponse.Token;

        //    var pinRequestUrl = authorizer.BuildAuthorizeUrl("https://api.twitter.com/oauth/authorize", requestToken);

        //    // open browser and get PIN Code
        //    Process.Start(pinRequestUrl);

        //    // enter pin
        //    Console.WriteLine("ENTER PIN");
        //    var pinCode = Console.ReadLine();

        //    // get access token
        //    var accessTokenResponse = await authorizer.GetAccessToken("https://api.twitter.com/oauth/access_token", requestToken, pinCode);

        //    // save access token.
        //    var accessToken = accessTokenResponse.Token;
        //    Console.WriteLine("Key:" + accessToken.Key);
        //    Console.WriteLine("Secret:" + accessToken.Secret);

        //    return accessToken;
        //}

        public async Task <string> GetTimeline(int count, int page)
        {
            var client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            var json = await client.GetStringAsync("https://api.twitter.com/1.1/statuses/home_timeline.json?count=" + count + "&page=" + page);

            return(json);
        }
Exemplo n.º 29
0
        public ActionResult ConnectToTwitter()
        {
            OAuthTokenResponse response = OAuthUtility.GetRequestToken(ConfigurationManager.AppSettings["consumerKey"], ConfigurationManager.AppSettings["consumerSecret"], "http://" + Request.Url.Authority.ToString() + "/Account");

            Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(response.Token);

            return(Redirect(authorizationUri.ToString()));
        }
Exemplo n.º 30
0
        /// <summary>
        /// Gets the user details.
        /// </summary>
        /// <returns>
        /// <para>Returns an instance of the <see cref="UserInfo"/> class, containing information about the user.</para>
        /// </returns>
        /// <exception cref="ApiException"/>
        public override UserInfo GetUserInfo()
        {
            // http://api.mail.ru/docs/reference/rest/users.getInfo/
            var parameters = new NameValueCollection
            {
                { "method", "users.getInfo" },
                { "app_id", this.ApplicationId },
                { "secure", "1" },
                { "uid", this.AccessToken["x_mailru_vid"].ToString() },
                { "format", "json" }
            };

            string signatureBaseString = parameters.Sort().ToParametersString();

            parameters["sig"] = OAuthUtility.GetMD5Hash(signatureBaseString + this.ApplicationSecret);

            var result = OAuthUtility.ExecuteRequest
                         (
                "POST",
                "http://www.appsmail.ru/platform/api",
                parameters
                         );

            if (!result.IsArray)
            {
                throw new ApiException(result, "Expected one-dimensional array."); //Ожидается одномерный массив.
            }

            var map = new ApiDataMapping();

            map.Add("uid", "UserId", typeof(string));
            map.Add("first_name", "FirstName");
            map.Add("last_name", "LastName");
            map.Add("nick", "DisplayName");
            map.Add("email", "Email");
            map.Add("email", "UserName");
            map.Add("pic", "Userpic");
            map.Add("link", "Url");
            map.Add("birthday", "Birthday", typeof(DateTime), @"dd\.MM\.yyyy");
            map.Add
            (
                "sex", "Sex",
                delegate(object value)
            {
                if (Convert.ToInt32(value) == 0)
                {
                    return(Sex.Male);
                }
                else if (Convert.ToInt32(value) == 1)
                {
                    return(Sex.Female);
                }
                return(Sex.None);
            }
            );

            return(new UserInfo(result[0] as Dictionary <string, object>, map));
        }