A handler that is used to generate an exception from the response sent back by Flickr.
        private void GetResponseAsync <T>(Dictionary <string, string> parameters, Action <FlickrResult <T> > callback) where T : IFlickrParsable, new()
        {
            CheckApiKey();

            parameters["api_key"] = ApiKey;

            // If performing one of the old 'flickr.auth' methods then use old authentication details.
            string method = parameters["method"];

            if (method.StartsWith("flickr.auth") && !method.EndsWith("oauth.checkToken"))
            {
                if (!String.IsNullOrEmpty(AuthToken))
                {
                    parameters["auth_token"] = AuthToken;
                }
            }
            else
            {
                // If OAuth Token exists or no authentication required then use new OAuth
                if (!String.IsNullOrEmpty(OAuthAccessToken) || String.IsNullOrEmpty(AuthToken))
                {
                    OAuthGetBasicParameters(parameters);
                    if (!String.IsNullOrEmpty(OAuthAccessToken))
                    {
                        parameters["oauth_token"] = OAuthAccessToken;
                    }
                }
                else
                {
                    parameters["auth_token"] = AuthToken;
                }
            }


            string url;

            if (!String.IsNullOrEmpty(sharedSecret))
            {
                url = CalculateUri(parameters, true);
            }
            else
            {
                url = CalculateUri(parameters, false);
            }

            lastRequest = url;

            try
            {
                FlickrResponder.GetDataResponseAsync(this, BaseUri.AbsoluteUri, parameters, (r)
                                                     =>
                {
                    FlickrResult <T> result = new FlickrResult <T>();
                    if (r.HasError)
                    {
                        result.Error = r.Error;
                    }
                    else
                    {
                        try
                        {
                            lastResponse = r.Result;

                            XmlReaderSettings settings = new XmlReaderSettings();
                            settings.IgnoreWhitespace  = true;
                            XmlReader reader           = XmlReader.Create(new StringReader(r.Result), 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();

                            T t = new T();
                            ((IFlickrParsable)t).Load(reader);
                            result.Result   = t;
                            result.HasError = false;
                        }
                        catch (Exception ex)
                        {
                            result.Error = ex;
                        }
                    }

                    if (callback != null)
                    {
                        callback(result);
                    }
                });
            }
            catch (Exception ex)
            {
                FlickrResult <T> result = new FlickrResult <T>();
                result.Error = ex;
                if (null != callback)
                {
                    callback(result);
                }
            }
        }
예제 #2
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);
        }
        private void DoGetResponseAsync <T>(Uri url, Action <FlickrResult <T> > callback) where T : IFlickrParsable, new()
        {
            string postContents = String.Empty;

            if (url.AbsoluteUri.Length > 2000)
            {
                postContents = url.Query.Substring(1);
                url          = new Uri(url, String.Empty);
            }

            FlickrResult <T> result = new FlickrResult <T>();

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            request.ContentType = "application/x-www-form-urlencoded";
            request.Method      = "POST";
            request.BeginGetRequestStream(requestAsyncResult =>
            {
                using (Stream s = request.EndGetRequestStream(requestAsyncResult))
                {
                    using (StreamWriter sw = new StreamWriter(s))
                    {
                        sw.Write(postContents);
                        sw.Close();
                    }
                    s.Close();
                }

                request.BeginGetResponse(responseAsyncResult =>
                {
                    try
                    {
                        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(responseAsyncResult);
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            string responseXml = sr.ReadToEnd();

                            lastResponse = responseXml;

                            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();

                            T t = new T();
                            ((IFlickrParsable)t).Load(reader);
                            result.Result   = t;
                            result.HasError = false;

                            sr.Close();
                        }

                        if (null != callback)
                        {
                            callback(result);
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Error = ex;
                        if (null != callback)
                        {
                            callback(result);
                        }
                    }
                }, null);
            }, null);
        }
예제 #4
0
        private async Task <FlickrResult <T> > GetResponseAsync <T>(Dictionary <string, string> parameters) where T : IFlickrParsable, new()
        {
            var hashApiSig = CalculateAuthSignature(parameters);

            CheckApiKey();

            FlickrResult <T> result = new FlickrResult <T>();

            var parseResult = new Func <Uri, string, T>((uri, response) =>
            {
                lastResponse = response;

                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreWhitespace  = true;
                XmlReader reader           = XmlReader.Create(new StringReader(response.Trim()), 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();

                T t = new T();
                ((IFlickrParsable)t).Load(reader);

                return(t);
            });



            parameters["api_key"] = ApiKey;

            if (!String.IsNullOrEmpty(OAuthAccessToken) || String.IsNullOrEmpty(AuthToken))
            {
                OAuthGetBasicParameters(parameters);
                parameters.Remove("api_key");
                if (!String.IsNullOrEmpty(OAuthAccessToken))
                {
                    parameters["oauth_token"] = OAuthAccessToken;
                }
            }
            else
            {
                parameters["auth_token"] = AuthToken;
            }

            Uri url;

            if (!String.IsNullOrEmpty(sharedSecret))
            {
                url = CalculateUri(parameters, true);
            }
            else
            {
                url = CalculateUri(parameters, false);
            }

            lastRequest = url.AbsoluteUri;

            //get cached result if its there
            var cachedResult = TryGetCacheCall(hashApiSig);

            if (!string.IsNullOrEmpty(cachedResult))
            {
                result.Result   = parseResult(url, cachedResult);
                result.HashCall = hashApiSig;
                result.HasError = false;
                return(result);
            }


            try
            {
                var r = await FlickrResponder.GetDataResponseAsync(this, hashApiSig, BaseUri.AbsoluteUri, parameters);

                if (r.HasError)
                {
                    result.Error = r.Error;
                }
                else
                {
                    //cache results
                    CacheCall(r.HashCall, r.Result);

                    result.Result   = parseResult(url, r.Result);
                    result.HashCall = r.HashCall;
                    result.HasError = false;
                }
            }
            catch (Exception ex)
            {
                result.Error = ex;
            }

            return(result);
        }