OAuthCalculateAuthHeader() public static method

Returns the string for the Authorisation header to be used for OAuth authentication. Parameters other than OAuth ones are ignored.
public static OAuthCalculateAuthHeader ( string>.Dictionary parameters ) : string
parameters string>.Dictionary OAuth and other parameters.
return string
Exemplo n.º 1
0
        private string UploadData(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters)
        {
            string boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);

            byte[] dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uploadUri);

            //req.UserAgent = "Mozilla/4.0 FlickrNet API (compatible; MSIE 6.0; Windows NT 5.1)";
            req.Method = "POST";
            if (Proxy != null)
            {
                req.Proxy = Proxy;
            }
            req.Timeout     = HttpTimeout;
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            //req.Expect = String.Empty;
            if (!String.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }

            req.ContentLength = dataBuffer.Length;

            using (Stream reqStream = req.GetRequestStream())
            {
                int bufferSize = 32 * 1024;
                if (dataBuffer.Length / 100 > bufferSize)
                {
                    bufferSize = bufferSize * 2;
                }

                int uploadedSoFar = 0;

                while (uploadedSoFar < dataBuffer.Length)
                {
                    reqStream.Write(dataBuffer, uploadedSoFar, Math.Min(bufferSize, dataBuffer.Length - uploadedSoFar));
                    uploadedSoFar += bufferSize;

                    if (OnUploadProgress != null)
                    {
                        UploadProgressEventArgs args = new UploadProgressEventArgs(uploadedSoFar, dataBuffer.Length);
                        OnUploadProgress(this, args);
                    }
                }
                reqStream.Close();
            }

            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            StreamReader sr = new StreamReader(res.GetResponseStream());
            string       s  = sr.ReadToEnd();

            sr.Close();
            return(s);
        }
Exemplo n.º 2
0
        public async Task <string> UploadPicture(Stream stream, string filename, string title, string description, string tags, bool isPublic, bool isFamily, bool isFriend, ContentType contentType, SafetyLevel safetyLevel, HiddenFromSearch hiddenFromSearch)
        {
            var parameters = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(title))
            {
                parameters.Add("title", title);
            }
            if (!string.IsNullOrEmpty(description))
            {
                parameters.Add("description", description);
            }
            if (!string.IsNullOrEmpty(tags))
            {
                parameters.Add("tags", tags);
            }

            parameters.Add("is_public", isPublic ? "1" : "0");
            parameters.Add("is_friend", isFriend ? "1" : "0");
            parameters.Add("is_family", isFamily ? "1" : "0");

            if (safetyLevel != SafetyLevel.None)
            {
                parameters.Add("safety_level", safetyLevel.ToString("D"));
            }
            if (contentType != ContentType.None)
            {
                parameters.Add("content_type", contentType.ToString("D"));
            }
            if (hiddenFromSearch != HiddenFromSearch.None)
            {
                parameters.Add("hidden", hiddenFromSearch.ToString("D"));
            }

            FlickrResponder.OAuthGetBasicParameters(parameters);
            parameters.Add("oauth_consumer_key", ApiKey);
            parameters.Add("oauth_token", OAuthAccessToken);
            parameters.Add("oauth_signature",
                           OAuthCalculateSignature("POST", UploadUrl, parameters, OAuthAccessTokenSecret));

            var boundary = FlickrResponder.CreateBoundary();
            var data     = FlickrResponder.CreateUploadData(stream, filename, parameters, boundary);

            var oauthHeader       = FlickrResponder.OAuthCalculateAuthHeader(parameters);
            var contentTypeHeader = "multipart/form-data; boundary=" + boundary;

            var response = await FlickrResponder.UploadDataAsync(UploadUrl, data, contentTypeHeader, oauthHeader);

            var match = Regex.Match(response, "<photoid>(\\d+)</photoid>");

            if (!match.Success)
            {
                throw new FlickrException("Unable to determine photo id from upload response: " + response);
            }

            return(match.Groups[1].Value);
        }
Exemplo n.º 3
0
        private string UploadData(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters)
        {
            var boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            var authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);
            var dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            var req = (HttpWebRequest)WebRequest.Create(uploadUri);

            req.Method = "POST";
            if (Proxy != null)
            {
                req.Proxy = Proxy;
            }
            req.Timeout     = HttpTimeout;
            req.ContentType = "multipart/form-data; boundary=" + boundary;

            if (!string.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }

            req.AllowWriteStreamBuffering = false;
            req.SendChunked = true;
            //req.ContentLength = dataBuffer.Length;

            using (var reqStream = req.GetRequestStream())
            {
                var bufferSize = 32 * 1024;
                if (dataBuffer.Length / 100 > bufferSize)
                {
                    bufferSize = bufferSize * 2;
                }
                dataBuffer.UploadProgress += (o, e) => { if (OnUploadProgress != null)
                                                         {
                                                             OnUploadProgress(this, e);
                                                         }
                };
                dataBuffer.CopyTo(reqStream, bufferSize);
                reqStream.Flush();
            }

            var res    = (HttpWebResponse)req.GetResponse();
            var stream = res.GetResponseStream();

            if (stream == null)
            {
                throw new FlickrWebException("Unable to retrieve stream from web response.");
            }

            var sr = new StreamReader(stream);
            var s  = sr.ReadToEnd();

            sr.Close();
            return(s);
        }
Exemplo n.º 4
0
        public async Task <OAuthRequestToken> OAuthRequestTokenAsync(string callbackUrl)
        {
            const string url = "https://www.flickr.com/services/oauth/request_token";

            IDictionary <string, string> parameters = new Dictionary <string, string>();

            FlickrResponder.OAuthGetBasicParameters(parameters);
            parameters.Add("oauth_callback", callbackUrl);
            parameters.Add("oauth_consumer_key", ApiKey);

            var sig = OAuthCalculateSignature("POST", url, parameters, null);

            parameters.Add("oauth_signature", sig);

            var data       = FlickrResponder.OAuthCalculatePostData(parameters);
            var authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);

            var response = await FlickrResponder.DownloadDataAsync("POST", url, data, null, authHeader);

            return(OAuthRequestToken.ParseResponse(response));
        }
Exemplo n.º 5
0
        public async Task <OAuthAccessToken> OAuthAccessTokenAsync(string requestToken, string requestTokenSecret, string verifier)
        {
            const string url = "https://www.flickr.com/services/oauth/access_token";

            if (verifier.Contains("://"))
            {
                var uri = new Uri(verifier);
                verifier =
                    uri.Query.Split(new[] { '&' })
                    .Select(s => s.Split(new[] { '=' }))
                    .First(s => s[0] == "oauth_verifier")[1];
            }
            IDictionary <string, string> parameters = new Dictionary <string, string>();

            FlickrResponder.OAuthGetBasicParameters(parameters);

            parameters.Add("oauth_consumer_key", ApiKey);
            parameters.Add("oauth_verifier", verifier);
            parameters.Add("oauth_token", requestToken);

            var sig = OAuthCalculateSignature("POST", url, parameters, requestTokenSecret);

            parameters.Add("oauth_signature", sig);

            var data       = FlickrResponder.OAuthCalculatePostData(parameters);
            var authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);
            var response   = await FlickrResponder.DownloadDataAsync("POST", url, data, null, authHeader);

            var accessToken = FlickrNet.OAuthAccessToken.ParseResponse(response);

            // Set current access token.
            OAuthAccessToken       = accessToken.Token;
            OAuthAccessTokenSecret = accessToken.TokenSecret;

            return(accessToken);
        }
Exemplo n.º 6
0
        private void UploadDataAsync(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters, Action <FlickrResult <string> > callback)
        {
            string boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);

            var dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            var req = (HttpWebRequest)WebRequest.Create(uploadUri);

            req.Method      = "POST";
            req.ContentType = "multipart/form-data; boundary=" + boundary;
#if (!SILVERLIGHT && !WINDOWS_PHONE)
            req.SendChunked = true;
#endif
            req.AllowWriteStreamBuffering = false;

            if (!string.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }

            req.BeginGetRequestStream(
                r =>
            {
                var result = new FlickrResult <string>();

                using (var reqStream = req.EndGetRequestStream(r))
                {
                    try
                    {
                        var bufferSize = 32 * 1024;
                        if (dataBuffer.Length / 100 > bufferSize)
                        {
                            bufferSize = bufferSize * 2;
                        }
                        dataBuffer.UploadProgress += (o, e) =>
                        {
                            if (OnUploadProgress != null)
                            {
                                OnUploadProgress(this, e);
                            }
                        };
                        dataBuffer.CopyTo(reqStream, bufferSize);
                        reqStream.Close();
                    }
                    catch (Exception ex)
                    {
                        result.Error = ex;
                        callback(result);
                    }
                }

                req.BeginGetResponse(
                    r2 =>
                {
                    try
                    {
                        var res         = req.EndGetResponse(r2);
                        var sr          = new StreamReader(res.GetResponseStream());
                        var responseXml = sr.ReadToEnd();
                        sr.Close();

                        var t = new UnknownResponse();
                        ((IFlickrParsable)t).Load(responseXml);
                        result.Result   = t.GetElementValue("photoid");
                        result.HasError = false;
                    }
                    catch (Exception ex)
                    {
                        if (ex is WebException)
                        {
                            var oauthEx  = new OAuthException(ex);
                            result.Error = string.IsNullOrEmpty(oauthEx.Message) ? ex : oauthEx;
                        }
                        else
                        {
                            result.Error = ex;
                        }
                    }

                    callback(result);
                },
                    this);
            },
                this);
        }
Exemplo n.º 7
0
        private void UploadDataAsync(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters, Action <FlickrResult <string> > callback)
        {
            string boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);

            byte[] dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uploadUri);

            req.Method      = "POST";
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            if (!String.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }

            req.BeginGetRequestStream(
                r =>
            {
                Stream s       = req.EndGetRequestStream(r);
                int bufferSize = 1024 * 32;
                int soFar      = 0;
                while (soFar < dataBuffer.Length)
                {
                    if ((dataBuffer.Length - soFar) < bufferSize)
                    {
                        bufferSize = dataBuffer.Length - soFar;
                    }
                    s.Write(dataBuffer, soFar, bufferSize);
                    soFar += bufferSize;

                    if (OnUploadProgress != null)
                    {
                        UploadProgressEventArgs args = new UploadProgressEventArgs(soFar, dataBuffer.Length);
                        OnUploadProgress(this, args);
                    }
                }

                req.BeginGetResponse(
                    r2 =>
                {
                    FlickrResult <string> result = new FlickrResult <string>();

                    try
                    {
                        WebResponse res    = req.EndGetResponse(r2);
                        StreamReader sr    = new StreamReader(res.GetResponseStream());
                        string responseXml = sr.ReadToEnd();


                        XmlReaderSettings settings = new XmlReaderSettings();
                        settings.IgnoreWhitespace  = true;
                        XmlReader reader           = XmlReader.Create(new StringReader(responseXml), settings);

                        if (!reader.ReadToDescendant("rsp"))
                        {
                            throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                        }
                        while (reader.MoveToNextAttribute())
                        {
                            if (reader.LocalName == "stat" && reader.Value == "fail")
                            {
                                throw ExceptionHandler.CreateResponseException(reader);
                            }
                            continue;
                        }

                        reader.MoveToElement();
                        reader.Read();

                        UnknownResponse t = new UnknownResponse();
                        ((IFlickrParsable)t).Load(reader);
                        result.Result   = t.GetElementValue("photoid");
                        result.HasError = false;
                    }
                    catch (Exception ex)
                    {
                        if (ex is WebException)
                        {
                            OAuthException oauthEx = new OAuthException(ex);
                            if (String.IsNullOrEmpty(oauthEx.Message))
                            {
                                result.Error = ex;
                            }
                            else
                            {
                                result.Error = oauthEx;
                            }
                        }
                        else
                        {
                            result.Error = ex;
                        }
                    }

                    callback(result);
                },
                    this);
            },
                this);
        }
Exemplo n.º 8
0
        private string UploadData(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters)
        {
            var boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            var authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);
            var dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            var req = (HttpWebRequest)WebRequest.Create(uploadUri);

            req.Method = "POST";
            if (Proxy != null)
            {
                req.Proxy = Proxy;
            }
            req.Timeout     = HttpTimeout;
            req.ContentType = "multipart/form-data; boundary=" + boundary;

            if (!string.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }


            req.UserAgent



            // VTVT na zaklade: http://genjurosdojo.blogspot.cz/2012/10/the-remote-server-returned-error-504.html

            /*req.Headers["User-Agent"]*/ = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0)" +
                                            " (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";



            req.AllowWriteStreamBuffering = false;
            req.SendChunked = true;
            //req.ContentLength = dataBuffer.Length;

            using (var reqStream = req.GetRequestStream())
            {
                var bufferSize = 32 * 1024;
                if (dataBuffer.Length / 100 > bufferSize)
                {
                    bufferSize = bufferSize * 2;
                }
                dataBuffer.UploadProgress += (o, e) => { if (OnUploadProgress != null)
                                                         {
                                                             OnUploadProgress(this, e);
                                                         }
                };
                dataBuffer.CopyTo(reqStream, bufferSize);
                reqStream.Flush();
            }

            var res    = (HttpWebResponse)req.GetResponse();
            var stream = res.GetResponseStream();

            if (stream == null)
            {
                throw new FlickrWebException("Unable to retrieve stream from web response.");
            }

            var sr = new StreamReader(stream);
            var s  = sr.ReadToEnd();

            sr.Close();
            return(s);
        }
Exemplo n.º 9
0
        private void UploadDataAsync(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters, Action <FlickrResult <string> > callback)
        {
            string boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);

            var dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            var req = WebRequest.Create(uploadUri);

            req.Method      = "POST";
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            if (!String.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }

            req.BeginGetRequestStream(
                r =>
            {
                using (var reqStream = req.EndGetRequestStream(r))
                {
                    var bufferSize = 32 * 1024;
                    if (dataBuffer.Length / 100 > bufferSize)
                    {
                        bufferSize = bufferSize * 2;
                    }
                    dataBuffer.UploadProgress += (o, e) => { if (OnUploadProgress != null)
                                                             {
                                                                 OnUploadProgress(this, e);
                                                             }
                    };
                    dataBuffer.CopyTo(reqStream, bufferSize);
                    reqStream.Close();
                }

                req.BeginGetResponse(
                    r2 =>
                {
                    var result = new FlickrResult <string>();

                    try
                    {
                        var res         = req.EndGetResponse(r2);
                        var sr          = new StreamReader(res.GetResponseStream());
                        var responseXml = sr.ReadToEnd();
                        sr.Close();

                        var settings = new XmlReaderSettings {
                            IgnoreWhitespace = true
                        };
                        var reader = XmlReader.Create(new StringReader(responseXml), settings);

                        if (!reader.ReadToDescendant("rsp"))
                        {
                            throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                        }
                        while (reader.MoveToNextAttribute())
                        {
                            if (reader.LocalName == "stat" && reader.Value == "fail")
                            {
                                throw ExceptionHandler.CreateResponseException(reader);
                            }
                        }

                        reader.MoveToElement();
                        reader.Read();

                        var t = new UnknownResponse();
                        ((IFlickrParsable)t).Load(reader);
                        result.Result   = t.GetElementValue("photoid");
                        result.HasError = false;
                    }
                    catch (Exception ex)
                    {
                        if (ex is WebException)
                        {
                            var oauthEx  = new OAuthException(ex);
                            result.Error = String.IsNullOrEmpty(oauthEx.Message) ? ex : oauthEx;
                        }
                        else
                        {
                            result.Error = ex;
                        }
                    }

                    callback(result);
                },
                    this);
            },
                this);
        }
Exemplo n.º 10
0
        public async Task <string> UploadPictureAsync(Stream stream, string filename, string title, string description, string tags, bool isPublic, bool isFamily, bool isFriend, ContentType contentType, SafetyLevel safetyLevel, HiddenFromSearch hiddenFromSearch)
        {
            var parameters = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(title))
            {
                parameters.Add("title", title);
            }
            if (!string.IsNullOrEmpty(description))
            {
                parameters.Add("description", description);
            }
            if (!string.IsNullOrEmpty(tags))
            {
                parameters.Add("tags", tags);
            }

            parameters.Add("is_public", isPublic ? "1" : "0");
            parameters.Add("is_friend", isFriend ? "1" : "0");
            parameters.Add("is_family", isFamily ? "1" : "0");

            if (safetyLevel != SafetyLevel.None)
            {
                parameters.Add("safety_level", safetyLevel.ToString("D"));
            }
            if (contentType != ContentType.None)
            {
                parameters.Add("content_type", contentType.ToString("D"));
            }
            if (hiddenFromSearch != HiddenFromSearch.None)
            {
                parameters.Add("hidden", hiddenFromSearch.ToString("D"));
            }

            FlickrResponder.OAuthGetBasicParameters(parameters);
            parameters.Add("oauth_consumer_key", ApiKey);
            parameters.Add("oauth_token", OAuthAccessToken);
            parameters.Add("oauth_signature",
                           OAuthCalculateSignature("POST", UploadUrl, parameters, OAuthAccessTokenSecret));

            var boundary = FlickrResponder.CreateBoundary();
            var data     = FlickrResponder.CreateUploadData(stream, filename, parameters, boundary);

            var oauthHeader       = FlickrResponder.OAuthCalculateAuthHeader(parameters);
            var contentTypeHeader = "multipart/form-data; boundary=" + boundary;

            var response = await FlickrResponder.UploadDataAsync(UploadUrl, data, contentTypeHeader, oauthHeader);

            var match = Regex.Match(response, "<photoid>(\\d+)</photoid>");

            if (match.Success)
            {
                return(match.Groups[1].Value);
            }

            using (var reader = XmlReader.Create(new StringReader(response), new XmlReaderSettings {
                IgnoreWhitespace = true
            }))
            {
                if (!reader.ReadToDescendant("rsp"))
                {
                    throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                }
                while (reader.MoveToNextAttribute())
                {
                    if (reader.LocalName == "stat" && reader.Value == "fail")
                    {
                        throw ExceptionHandler.CreateResponseException(reader);
                    }
                }
            }

            throw new FlickrException("Unable to determine photo id from upload response: " + response);
        }