CreateResponseException() 공개 정적인 메소드

Creates a FlickrApiException from the response sent back from Flickr.
public static CreateResponseException ( XmlReader reader ) : Exception
reader System.Xml.XmlReader The containing the response from Flickr.
리턴 System.Exception
예제 #1
0
        public void GetCachedResponse <T>(string cachedResponse, Action <T> callback) where T : IFlickrParsable, new()
        {
            XmlReaderSettings settings = new XmlReaderSettings();

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

            if (callback != null)
            {
                callback(t);
            }
        }
예제 #2
0
        public static void Load(this IFlickrParsable item, string originalXml)
        {
            try
            {
                var reader = XmlReader.Create(new StringReader(originalXml), new XmlReaderSettings
                {
                    IgnoreWhitespace = true
                });

                if (!reader.ReadToDescendant("rsp"))
                {
                    throw new Exception("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();

                item.Load(reader);
            }
            catch (XmlException)
            {
                var newReader = XmlReader.Create(new StringReader(SanitizeXmlString(originalXml)), new XmlReaderSettings
                {
                    IgnoreWhitespace = true
                });

                if (!newReader.ReadToDescendant("rsp"))
                {
                    throw new Exception("Unable to find response element 'rsp' in Flickr response");
                }

                while (newReader.MoveToNextAttribute())
                {
                    if (newReader.LocalName == "stat" && newReader.Value == "fail")
                    {
                        throw ExceptionHandler.CreateResponseException(newReader);
                    }
                }

                newReader.MoveToElement();
                newReader.Read();

                item.Load(newReader);
            }
        }
예제 #3
0
        /// <summary>
        /// Replace an existing photo on Flickr.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> object containing the photo to be uploaded.</param>
        /// <param name="fileName">The filename of the file to replace the existing item with.</param>
        /// <param name="photoId">The ID of the photo to replace.</param>
        /// <returns>The id of the photograph after successful uploading.</returns>
        public string ReplacePicture(Stream stream, string fileName, string photoId)
        {
            var replaceUri = new Uri(ReplaceUrl);

            var parameters = new Dictionary <string, string>
            {
                { "photo_id", photoId }
            };

            if (!string.IsNullOrEmpty(OAuthAccessToken))
            {
                OAuthGetBasicParameters(parameters);
                parameters.Add("oauth_token", OAuthAccessToken);

                var sig = OAuthCalculateSignature("POST", replaceUri.AbsoluteUri, parameters, OAuthAccessTokenSecret);
                parameters.Add("oauth_signature", sig);
            }
            else
            {
                parameters.Add("api_key", apiKey);
                parameters.Add("auth_token", apiToken);
            }

            var responseXml = UploadData(stream, fileName, replaceUri, parameters);

            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);
            return(t.GetElementValue("photoid"));
        }
예제 #4
0
        internal async Task <T> GetResponseAsync <T>(IDictionary <string, string> parameters) where T : class, IFlickrParsable, new()
        {
            if (!parameters.ContainsKey("oauth_consumer_key"))
            {
                parameters.Add("oauth_consumer_key", ApiKey);
            }

            var result = await FlickrResponder.GetDataResponseAsync(this, BaseApiUrl, parameters);

            var typeInfo = typeof(T).GetTypeInfo();

            if (typeInfo.IsEnum)
            {
                return(default(T));
            }
            if (typeInfo.ImplementedInterfaces.Any(t => t.Name == "IFlickrParsable"))
            {
                using (var reader = XmlReader.Create(new StringReader(result), 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);
                        }
                    }

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

                    var item = new T();
                    item.Load(reader);
                    return(item);
                }
            }

            return(default(T));
        }
예제 #5
0
        internal T GetResponse <T>(IDictionary <string, string> parameters) where T : class, IFlickrParsable, new()
        {
            if (!parameters.ContainsKey("oauth_consumer_key"))
            {
                parameters.Add("oauth_consumer_key", ApiKey);
            }

            var result = FlickrResponder.GetDataResponse(this, BaseApiUrl, parameters);

            LastResponse = result;

            if (typeof(T).IsEnum)
            {
                return(default(T));
            }
            if (typeof(T).GetInterface("FlickrNet.IFlickrParsable") != null)
            {
                using (var reader = new XmlTextReader(new StringReader(result)))
                {
                    reader.WhitespaceHandling = WhitespaceHandling.None;

                    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 item = new T();
                    item.Load(reader);
                    return(item);
                }
            }

            return(default(T));
        }
예제 #6
0
        private T GetResponse <T>(Dictionary <string, string> parameters, TimeSpan cacheTimeout) where T : IFlickrParsable, new()
        {
            // Flow for GetResponse.
            // 1. Check API Key
            // 2. Calculate Cache URL.
            // 3. Check Cache for URL.
            // 4. Get Response if not in cache.
            // 5. Write Cache.
            // 6. Parse Response.

            CheckApiKey();

            parameters["api_key"] = ApiKey;

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

            // User of obsolete AuthToken property while we transition over to the new OAuth authentication process.
#pragma warning disable 612,618
            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))
                {
                    parameters.Remove("api_key");
                    OAuthGetBasicParameters(parameters);
                    if (!String.IsNullOrEmpty(OAuthAccessToken))
                    {
                        parameters["oauth_token"] = OAuthAccessToken;
                    }
                }
                else
                {
                    parameters["auth_token"] = AuthToken;
                }
            }
#pragma warning restore 612,618

            var url = CalculateUri(parameters, !String.IsNullOrEmpty(sharedSecret));

            lastRequest = url;

            string responseXml;

            if (InstanceCacheDisabled)
            {
                responseXml = FlickrResponder.GetDataResponse(this, BaseUri.AbsoluteUri, parameters);
            }
            else
            {
                var urlComplete = url;

                var cached = (ResponseCacheItem)Cache.Responses.Get(urlComplete, cacheTimeout, true);
                if (cached != null)
                {
                    Debug.WriteLine("Cache hit.");
                    responseXml = cached.Response;
                }
                else
                {
                    Debug.WriteLine("Cache miss.");
                    responseXml = FlickrResponder.GetDataResponse(this, BaseUri.AbsoluteUri, parameters);

                    var resCache = new ResponseCacheItem(new Uri(urlComplete), responseXml, DateTime.UtcNow);

                    Cache.Responses.Shrink(Math.Max(0, Cache.CacheSizeLimit - responseXml.Length));
                    Cache.Responses[urlComplete] = resCache;
                }
            }

            lastResponse = responseXml;

            //responseXml = responseXml.Trim();

            var reader = new XmlTextReader(new StringReader(responseXml))
            {
                WhitespaceHandling = WhitespaceHandling.None,
            };

            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 item = new T();
            item.Load(reader);

            return(item);
        }
예제 #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);
        }
예제 #8
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 GetResponseAsync <T>(Dictionary <string, string> parameters, Action <FlickrResult <T> > callback) where T : IFlickrParsable, new()
        {
            CheckApiKey();

            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;

            try
            {
                FlickrResponder.GetDataResponseAsync(this, BaseUri.AbsoluteUri, parameters, (r)
                                                     =>
                {
                    FlickrResult <T> result = new FlickrResult <T>();
                    if (r.HasError)
                    {
                        result.Error = r.Error;
                    }
                    else
                    {
                        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;
                    }

                    if (callback != null)
                    {
                        callback(result);
                    }
                });
            }
            catch (Exception ex)
            {
                FlickrResult <T> result = new FlickrResult <T>();
                result.Error = ex;
                if (null != callback)
                {
                    callback(result);
                }
            }
        }
        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);
                    }
                }

                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;
                        }

                        if (null != callback)
                        {
                            callback(result);
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Error = ex;
                        if (null != callback)
                        {
                            callback(result);
                        }
                        return;
                    }
                }, null);
            }, null);

            //WebClient client = new WebClient();
            //client.UploadStringCompleted += delegate(object sender, UploadStringCompletedEventArgs e)
            //{
            //    FlickrResult<T> result = new FlickrResult<T>();

            //    if (e.Error != null)
            //    {
            //        result.Error = e.Error;
            //        callback(result);
            //        return;
            //    }

            //    try
            //    {
            //        string responseXml = e.Result;

            //        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;

            //    }
            //    catch (Exception ex)
            //    {
            //        result.HasError = true;
            //        result.Error = ex;
            //    }

            //    if (callback != null)
            //    {
            //        callback(result);
            //    }

            //};

            //client.Headers["Content-Type"] = "application/x-www-form-urlencoded";
            //client.UploadStringAsync(url, "POST", postContents);
        }
        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", StringComparison.Ordinal) && !method.EndsWith("oauth.checkToken", StringComparison.Ordinal))
            {
                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;
                }
            }


            var url = CalculateUri(parameters, !string.IsNullOrEmpty(sharedSecret));

            lastRequest = url;

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

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

                            var 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)
            {
                var result = new FlickrResult <T>();
                result.Error = ex;
                if (null != callback)
                {
                    callback(result);
                }
            }
        }
        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);
            }

            var result = new FlickrResult <T>();

            var request = (HttpWebRequest)WebRequest.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
                    {
                        var response = (HttpWebResponse)request.EndGetResponse(responseAsyncResult);
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            string responseXml = sr.ReadToEnd();

                            lastResponse = responseXml;

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

                            var 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);
        }
예제 #13
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);
        }
예제 #14
0
        /// <summary>
        /// UploadPicture method that does all the uploading work.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> object containing the pphoto to be uploaded.</param>
        /// <param name="fileName">The filename of the file to upload. Used as the title if title is null.</param>
        /// <param name="title">The title of the photo (optional).</param>
        /// <param name="description">The description of the photograph (optional).</param>
        /// <param name="tags">The tags for the photograph (optional).</param>
        /// <param name="isPublic">false for private, true for public.</param>
        /// <param name="isFamily">true if visible to family.</param>
        /// <param name="isFriend">true if visible to friends only.</param>
        /// <param name="contentType">The content type of the photo, i.e. Photo, Screenshot or Other.</param>
        /// <param name="safetyLevel">The safety level of the photo, i.e. Safe, Moderate or Restricted.</param>
        /// <param name="hiddenFromSearch">Is the photo hidden from public searches.</param>
        /// <returns>The id of the photograph after successful uploading.</returns>
        public string UploadPicture(Stream stream, string fileName, string title, string description, string tags,
                                    bool isPublic, bool isFamily, bool isFriend, ContentType contentType,
                                    SafetyLevel safetyLevel, HiddenFromSearch hiddenFromSearch)
        {
            CheckRequiresAuthentication();

            var uploadUri = new Uri(UploadUrl);

            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"));
            }

            if (!string.IsNullOrEmpty(OAuthAccessToken))
            {
                OAuthGetBasicParameters(parameters);
                parameters.Add("oauth_token", OAuthAccessToken);

                string sig = OAuthCalculateSignature("POST", uploadUri.AbsoluteUri, parameters, OAuthAccessTokenSecret);
                parameters.Add("oauth_signature", sig);
            }
            else
            {
                parameters.Add("api_key", apiKey);
                parameters.Add("auth_token", apiToken);
            }

            string responseXml = UploadData(stream, fileName, uploadUri, parameters);

            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);
            return(t.GetElementValue("photoid"));
        }
예제 #15
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);
        }