コード例 #1
0
ファイル: FB.cs プロジェクト: JeffreyKimani/unityplugins
 public static void API(
     string endpoint,
     HttpMethod method,
     FacebookDelegate callback)
 {
     if (method != HttpMethod.GET) throw new NotImplementedException();
     Task.Run(async () =>
     {
         FacebookClient fb = new FacebookClient(_fbSessionClient.CurrentAccessTokenData.AccessToken);
         FBResult fbResult = null;
         try
         {
             var apiCall = await fb.GetTaskAsync(endpoint, null);
             if (apiCall != null)
             {
                 fbResult = new FBResult();
                 fbResult.Text = apiCall.ToString();
                 fbResult.Json = apiCall as JsonObject;
             }
         }
         catch (Exception ex)
         {
             fbResult = new FBResult();
             fbResult.Error = ex.Message;
         }
         if (callback != null)
         {
             Utils.RunOnUnityAppThread(() => { callback(fbResult); });
         }
     });
 }
コード例 #2
0
 internal static void Request(
     string url,
     HttpMethod method,
     WWWForm query = null,
     FacebookDelegate callback = null)
 {
     FBComponentFactory.AddComponent<AsyncRequestString>()
         .SetUrl(url)
         .SetMethod(method)
         .SetQuery(query)
         .SetCallback(callback);
 }
コード例 #3
0
 internal static void Request(
     string url,
     HttpMethod method,
     Dictionary<string, string> formData = null,
     FacebookDelegate callback = null)
 {
     FBComponentFactory.AddComponent<AsyncRequestString>()
         .SetUrl(url)
         .SetMethod(method)
         .SetFormData(formData)
         .SetCallback(callback);
 }
コード例 #4
0
        public virtual void API(
            string query,
            HttpMethod method,
            Dictionary<string, string> formData = null,
            FacebookDelegate callback = null)
        {
            Dictionary<string, string> inputFormData;
            // Copy the formData by value so it's not vulnerable to scene changes and object deletions
            inputFormData = (formData != null) ? CopyByValue(formData) : new Dictionary<string, string>();
            if (!inputFormData.ContainsKey(AccessTokenKey) && !query.Contains("access_token="))
            {
              inputFormData[AccessTokenKey] = AccessToken;
            }

            AsyncRequestString.Request(GetGraphUrl(query), method, inputFormData, callback);
        }
コード例 #5
0
        public override void API(
            string query,
            HttpMethod method,
            Dictionary<string, string> formData = null,
            FacebookDelegate callback = null)
        {
            if (query.StartsWith("me"))
            {
                FbDebug.Warn("graph.facebook.com/me does not work within the Unity Editor");
            }

            if (!query.Contains("access_token=") && (formData == null || !formData.ContainsKey("access_token")))
            {
                FbDebug.Warn("Without an access_token param explicitly passed in formData, some API graph calls will 404 error in the Unity Editor.");
            }
            fb.API(query, method, formData, callback);
        }
コード例 #6
0
        public void API(
            string query,
            HttpMethod method,
            Facebook.APIDelegate callback = null,
            Dictionary<string, string> formData = null,
            Facebook.ErrorDelegate errorCallback = null)
        {
            FbDebug.Log("Calling API");

            if (!query.StartsWith("/"))
            {
                query = "/" + query;
            }
            string url = IntegratedPluginCanvasLocation.GraphUrl + query;

            // Copy the formData by value so it's not vulnerable to scene changes and object deletions
            Dictionary<string, string> inputFormData = (formData != null) ? CopyByValue(formData) : new Dictionary<string, string>(1);
            if (!inputFormData.ContainsKey(AccessTokenKey))
            {
                inputFormData[AccessTokenKey] = AccessToken;
            }

            StartCoroutine(graphAPI(url, method, callback, inputFormData, errorCallback));
        }
コード例 #7
0
        public static void API(
            string endpoint,
            HttpMethod method,
            FacebookDelegate callback)
        {
            if (_web == null) throw new MissingScaffoldingException();
            if (!IsLoggedIn)
            {
                // Already in use
                if (callback != null)
                    callback(new FBResult() { Error = "Not logged in" });
                return;
            }

            if (method != HttpMethod.GET) throw new NotImplementedException();

            Task.Run(async () =>
            {
                FBResult fbResult = null;
                try
                {
                    var apiCall = await _client.GetTaskAsync(endpoint, null);
                    if (apiCall != null)
                    {
                        fbResult = new FBResult();
                        fbResult.Text = apiCall.ToString();
                        fbResult.Json = apiCall as JsonObject;
                    }
                }
                catch (Exception ex)
                {
                    fbResult = new FBResult();
                    fbResult.Error = ex.Message;
                }
                if (callback != null)
                {
                    Utils.RunOnUnityAppThread(() => { callback(fbResult); });
                }
            });
        }
コード例 #8
0
        public static void API(
            string endpoint,
            HttpMethod method,
            FacebookDelegate callback,
            object parameters = null)
        {
#if NETFX_CORE
            if (_web == null) throw new MissingPlatformException();
            if (!IsLoggedIn)
            {
                // Already in use
                if (callback != null)
                    callback(new FBResult() { Error = "Not logged in" });
                return;
            }

            Task.Run(async () =>
            {
                FBResult fbResult = null;
                try
                {
                    object apiCall;
                    if (method == HttpMethod.GET)
                    {
                        apiCall = await _client.GetTaskAsync(endpoint, parameters);
                    }
                    else if (method == HttpMethod.POST)
                    {
                        apiCall = await _client.PostTaskAsync(endpoint, parameters);
                    }
                    else
                    {
                        apiCall = await _client.DeleteTaskAsync(endpoint);
                    }
                    if (apiCall != null)
                    {
                        fbResult = new FBResult();
                        fbResult.Text = apiCall.ToString();
                        fbResult.Json = apiCall as JsonObject;
                    }
                }
                catch (Exception ex)
                {
                    fbResult = new FBResult();
                    fbResult.Error = ex.Message;
                }
                if (callback != null)
                {
                    Dispatcher.InvokeOnAppThread(() => { callback(fbResult); });
                }
            });
#else
            throw new PlatformNotSupportedException("");
#endif
        }
コード例 #9
0
        /// <summary>
        /// Makes a request to the Facebook server.
        /// </summary>
        /// <param name="httpMethod">Http method. (GET/POST/DELETE)</param>
        /// <param name="path">The resource path or the resource url.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="resultType">The type of deserialize object into.</param>
        /// <returns>The json result.</returns>
        protected virtual object Api(HttpMethod httpMethod, string path, object parameters, Type resultType)
        {
            Stream input;
            bool containsEtag;
            IList<int> batchEtags;
            var httpHelper = PrepareRequest(httpMethod, path, parameters, resultType, out input, out containsEtag, out  batchEtags);

            if (input != null)
            {
                try
                {
                    using (var stream = httpHelper.OpenWrite())
                    {
                        // write input to requestStream
                        var buffer = new byte[BufferSize];
                        while (true)
                        {
                            int bytesRead = input.Read(buffer, 0, buffer.Length);
                            input.Flush();
                            if (bytesRead <= 0) break;
                            stream.Write(buffer, 0, bytesRead);
                            stream.Flush();
                        }
                    }
                }
                catch (WebExceptionWrapper ex)
                {
                    if (ex.GetResponse() == null) throw;
                }
                finally
                {
                    input.Dispose();
                }
            }

            Stream responseStream = null;
            object result = null;
            bool read = false;
            try
            {
                responseStream = httpHelper.OpenRead();
                read = true;
            }
            catch (WebExceptionWrapper ex)
            {
                var response = ex.GetResponse();
                if (response == null) throw;
                if (response.StatusCode == HttpStatusCode.NotModified)
                {
                    var jsonObject = new JsonObject();
                    var headers = new JsonObject();

                    foreach (var headerName in response.Headers.AllKeys)
                        headers[headerName] = response.Headers[headerName];

                    jsonObject["headers"] = headers;
                    result = jsonObject;
                }
                else
                {
                    responseStream = httpHelper.OpenRead();
                    read = true;
                }
            }
            finally
            {
                if (read)
                {
                    string responseString;
                    using (var stream = responseStream)
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            responseString = reader.ReadToEnd();
                        }
                    }

                    result = ProcessResponse(httpHelper, responseString, resultType, containsEtag, batchEtags);
                }
            }

            return result;
        }
コード例 #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookBatchParameter"/> class.
 /// </summary>
 /// <param name="httpMethod">
 /// The http method.
 /// </param>
 /// <param name="path">
 /// The resource path.
 /// </param>
 /// <param name="parameters">
 /// The parameters.
 /// </param>
 public FacebookBatchParameter(HttpMethod httpMethod, string path, object parameters)
 {
     HttpMethod = httpMethod;
     Path = path;
     Parameters = parameters;
 }
コード例 #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookBatchParameter"/> class.
 /// </summary>
 /// <param name="httpMethod">
 /// The http method.
 /// </param>
 /// <param name="path">
 /// The resource path.
 /// </param>
 public FacebookBatchParameter(HttpMethod httpMethod, string path)
     : this(httpMethod, path, null)
 {
 }
コード例 #12
0
        protected virtual void ApiAsync(HttpMethod httpMethod, string path, object parameters, Type resultType, object userState)
        {
            Stream input;
            bool containsEtag;
            IList<int> batchEtags = null;
            var httpHelper = PrepareRequest(httpMethod, path, parameters, resultType, out input, out containsEtag, out batchEtags);
            _httpWebRequest = httpHelper.HttpWebRequest;

#if FLUENTHTTP_CORE_TPL
            if (HttpWebRequestWrapperCreated != null)
                HttpWebRequestWrapperCreated(this, new HttpWebRequestCreatedEventArgs(userState, httpHelper.HttpWebRequest));
#endif

            var uploadProgressChanged = UploadProgressChanged;
            bool notifyUploadProgressChanged = uploadProgressChanged != null && httpHelper.HttpWebRequest.Method == "POST";

            httpHelper.OpenReadCompleted +=
                (o, e) =>
                {
                    FacebookApiEventArgs args;
                    if (e.Cancelled)
                    {
                        args = new FacebookApiEventArgs(e.Error, true, userState, null);
                    }
                    else if (e.Error == null)
                    {
                        string responseString = null;

                        try
                        {
                            using (var stream = e.Result)
                            {
#if NETFX_CORE
                                bool compressed = false;
                                
                                var contentEncoding = httpHelper.HttpWebResponse.Headers.AllKeys.Contains("Content-Encoding") ? httpHelper.HttpWebResponse.Headers["Content-Encoding"] : null;
                                if (contentEncoding != null)
                                {
                                    if (contentEncoding.IndexOf("gzip") != -1)
                                    {
                                        using (var uncompressedStream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress))
                                        {
                                            using (var reader = new StreamReader(uncompressedStream))
                                            {
                                                responseString = reader.ReadToEnd();
                                            }
                                        }

                                        compressed = true;
                                    }
                                    else if (contentEncoding.IndexOf("deflate") != -1)
                                    {
                                        using (var uncompressedStream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress))
                                        {
                                            using (var reader = new StreamReader(uncompressedStream))
                                            {
                                                responseString = reader.ReadToEnd();
                                            }
                                        }

                                        compressed = true;
                                    }
                                }

                                if (!compressed)
                                {
                                    using (var reader = new StreamReader(stream))
                                    {
                                        responseString = reader.ReadToEnd();
                                    }
                                }
#else
                                var response = httpHelper.HttpWebResponse;
                                if (response != null && response.StatusCode == HttpStatusCode.NotModified)
                                {
                                    var jsonObject = new JsonObject();
                                    var headers = new JsonObject();

                                    foreach (var headerName in response.Headers.AllKeys)
                                        headers[headerName] = response.Headers[headerName];

                                    jsonObject["headers"] = headers;
                                    args = new FacebookApiEventArgs(null, false, userState, jsonObject);
                                    OnCompleted(httpMethod, args);
                                    return;
                                }

                                using (var reader = new StreamReader(stream))
                                {
                                    responseString = reader.ReadToEnd();
                                }
#endif
                            }

                            try
                            {
                                object result = ProcessResponse(httpHelper, responseString, resultType, containsEtag, batchEtags);
                                args = new FacebookApiEventArgs(null, false, userState, result);
                            }
                            catch (Exception ex)
                            {
                                args = new FacebookApiEventArgs(ex, false, userState, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            args = httpHelper.HttpWebRequest.IsCancelled ? new FacebookApiEventArgs(ex, true, userState, null) : new FacebookApiEventArgs(ex, false, userState, null);
                        }
                    }
                    else
                    {
                        var webEx = e.Error as WebExceptionWrapper;
                        if (webEx == null)
                        {
                            args = new FacebookApiEventArgs(e.Error, httpHelper.HttpWebRequest.IsCancelled, userState, null);
                        }
                        else
                        {
                            if (webEx.GetResponse() == null)
                            {
                                args = new FacebookApiEventArgs(webEx, false, userState, null);
                            }
                            else
                            {
                                var response = httpHelper.HttpWebResponse;
                                if (response.StatusCode == HttpStatusCode.NotModified)
                                {
                                    var jsonObject = new JsonObject();
                                    var headers = new JsonObject();

                                    foreach (var headerName in response.Headers.AllKeys)
                                        headers[headerName] = response.Headers[headerName];

                                    jsonObject["headers"] = headers;
                                    args = new FacebookApiEventArgs(null, false, userState, jsonObject);
                                }
                                else
                                {
                                    httpHelper.OpenReadAsync();
                                    return;
                                }
                            }
                        }
                    }

                    OnCompleted(httpMethod, args);
                };

            if (input == null)
            {
                httpHelper.OpenReadAsync();
            }
            else
            {
                // we have a request body so write
                httpHelper.OpenWriteCompleted +=
                    (o, e) =>
                    {
                        FacebookApiEventArgs args;
                        if (e.Cancelled)
                        {
                            input.Dispose();
                            args = new FacebookApiEventArgs(e.Error, true, userState, null);
                        }
                        else if (e.Error == null)
                        {
                            try
                            {
                                using (var stream = e.Result)
                                {
                                    // write input to requestStream
                                    var buffer = new byte[BufferSize];
                                    int nread;

                                    if (notifyUploadProgressChanged)
                                    {
                                        long totalBytesToSend = input.Length;
                                        long bytesSent = 0;

                                        while ((nread = input.Read(buffer, 0, buffer.Length)) != 0)
                                        {
                                            stream.Write(buffer, 0, nread);
                                            stream.Flush();

                                            // notify upload progress changed
                                            bytesSent += nread;
                                            OnUploadProgressChanged(new FacebookUploadProgressChangedEventArgs(0, 0, bytesSent, totalBytesToSend, ((int)(bytesSent * 100 / totalBytesToSend)), userState));
                                        }
                                    }
                                    else
                                    {
                                        while ((nread = input.Read(buffer, 0, buffer.Length)) != 0)
                                        {
                                            stream.Write(buffer, 0, nread);
                                            stream.Flush();
                                        }
                                    }
                                }

                                httpHelper.OpenReadAsync();
                                return;
                            }
                            catch (Exception ex)
                            {
                                args = new FacebookApiEventArgs(ex, httpHelper.HttpWebRequest.IsCancelled, userState, null);
                            }
                            finally
                            {
                                input.Dispose();
                            }
                        }
                        else
                        {
                            input.Dispose();
                            var webExceptionWrapper = e.Error as WebExceptionWrapper;
                            if (webExceptionWrapper != null)
                            {
                                var ex = webExceptionWrapper;
                                if (ex.GetResponse() != null)
                                {
                                    httpHelper.OpenReadAsync();
                                    return;
                                }
                            }

                            args = new FacebookApiEventArgs(e.Error, false, userState, null);
                        }

                        OnCompleted(httpMethod, args);
                    };

                httpHelper.OpenWriteAsync();
            }
        }
コード例 #13
0
 protected internal override void ApiAsync(string path, IDictionary<string, object> parameters, HttpMethod httpMethod, object userToken)
 {
     throw new NotImplementedException();
 }
コード例 #14
0
        public void ItShouldReturnTheEquivalentString(HttpMethod httpMethod, string strHttpMethod)
        {
            var result = FacebookUtils.ConvertToString(httpMethod);

            Assert.Equal(strHttpMethod, result);
        }
コード例 #15
0
        private IEnumerator graphAPI(
            string url,
            HttpMethod method,
            Facebook.APIDelegate callback = null,
            Dictionary<string, string> formData = null,
            Facebook.ErrorDelegate errorCallback = null)
        {
            WWW www;
            if (method == HttpMethod.GET)
            {
                string query = (url.Contains("?")) ? "&" : "?";
                if (formData != null)
                {
                    foreach (KeyValuePair<string, string> pair in formData)
                    {
                        query += string.Format("{0}={1}&", Uri.EscapeDataString(pair.Key), Uri.EscapeDataString(pair.Value));
                    }
                }
                www = new WWW(url + query);
            }
            else //POST
            {
                WWWForm query = new WWWForm();
                foreach (KeyValuePair<string, string> pair in formData)
                {
                    query.AddField(pair.Key, pair.Value);
                }

                www = new WWW(url, query);
            }

            FbDebug.Log("Fetching from " + www.url);
            yield return www;

            if (www.error != null)
            {
                if (errorCallback != null)
                {
                    errorCallback(www.error);
                }
                else
                {
                    FbDebug.Error("Web Error: " + www.error);
                }
            }
            else
            {
                if (callback != null)
                {
                    callback(www.text);
                }
                else
                {
                    FbDebug.Log(www.text);
                }
            }
            www.Dispose();
            formData.Clear();
        }
コード例 #16
0
        private HttpHelper PrepareRequest(HttpMethod httpMethod, string path, object parameters, Type resultType, out Stream input, out bool containsEtag, out IList<int> batchEtags)
        {
            input = null;
            containsEtag = false;
            batchEtags = null;

            IDictionary<string, FacebookMediaObject> mediaObjects;
            IDictionary<string, FacebookMediaStream> mediaStreams;
            IDictionary<string, object> parametersWithoutMediaObjects = ToDictionary(parameters, out mediaObjects, out mediaStreams) ?? new Dictionary<string, object>();

            if (!parametersWithoutMediaObjects.ContainsKey("access_token") && !string.IsNullOrEmpty(AccessToken))
                parametersWithoutMediaObjects["access_token"] = AccessToken;
            if (!parametersWithoutMediaObjects.ContainsKey("return_ssl_resources") && IsSecureConnection)
                parametersWithoutMediaObjects["return_ssl_resources"] = true;

            string etag = null;
            if (parametersWithoutMediaObjects.ContainsKey(ETagKey))
            {
                etag = (string)parametersWithoutMediaObjects[ETagKey];
                parametersWithoutMediaObjects.Remove(ETagKey);
                containsEtag = true;
            }

            Uri uri;
            bool isLegacyRestApi = false;
            path = ParseUrlQueryString(path, parametersWithoutMediaObjects, false, out uri, out isLegacyRestApi);

            if (parametersWithoutMediaObjects.ContainsKey("format"))
                parametersWithoutMediaObjects["format"] = "json-strings";

            string restMethod = null;
            if (parametersWithoutMediaObjects.ContainsKey("method"))
            {
                restMethod = (string)parametersWithoutMediaObjects["method"];
                if (restMethod.Equals("DELETE", StringComparison.OrdinalIgnoreCase))
                    throw new ArgumentException("Parameter cannot contain method=delete. Use Delete or DeleteAsync or DeleteTaskAsync methods instead.", "parameters");
                parametersWithoutMediaObjects.Remove("method");
                isLegacyRestApi = true;
            }
            else if (isLegacyRestApi)
            {
                throw new ArgumentException("Parameters should contain rest 'method' name", "parameters");
            }

            UriBuilder uriBuilder;
            if (uri == null)
            {
                uriBuilder = new UriBuilder { Scheme = "https" };

                if (isLegacyRestApi)
                {
                    if (string.IsNullOrEmpty(restMethod))
                        throw new InvalidOperationException("Legacy rest api 'method' in parameters is null or empty.");
                    path = string.Concat("method/", restMethod);
                    parametersWithoutMediaObjects["format"] = "json-strings";
                    if (restMethod.Equals("video.upload"))
                        uriBuilder.Host = UseFacebookBeta ? "api-video.beta.facebook.com" : "api-video.facebook.com";
                    else if (LegacyRestApiReadOnlyCalls.Contains(restMethod))
                        uriBuilder.Host = UseFacebookBeta ? "api-read.beta.facebook.com" : "api-read.facebook.com";
                    else
                        uriBuilder.Host = UseFacebookBeta ? "api.beta.facebook.com" : "api.facebook.com";
                }
                else
                {
                    if (parametersWithoutMediaObjects.ContainsKey("batch"))
                    {
                        var processBatchResponse = !parametersWithoutMediaObjects.ContainsKey("_process_batch_response_") ||
                                               (bool)parametersWithoutMediaObjects["_process_batch_response_"];

                        if (processBatchResponse)
                        {
                            batchEtags = new List<int>();
                            var batch = parametersWithoutMediaObjects["batch"] as IList<object>;
                            if (batch != null)
                            {
                                int i;
                                for (i = 0; i < batch.Count; i++)
                                {
                                    var batchParameter = batch[i] as IDictionary<string, object>;
                                    if (batchParameter != null)
                                    {
                                        IDictionary<string, object> headers = null;
                                        if (batchParameter.ContainsKey("headers"))
                                            headers = (IDictionary<string, object>)batchParameter["headers"];

                                        bool containsBatchEtag = batchParameter.ContainsKey(ETagKey);
                                        if (containsBatchEtag)
                                        {
                                            if (string.IsNullOrEmpty((string)batchParameter[ETagKey]))
                                            {
                                                batchEtags.Add(i);
                                                batchParameter.Remove(ETagKey);
                                                continue;
                                            }
                                            else if (headers == null)
                                            {
                                                headers = new Dictionary<string, object>();
                                                batchParameter["headers"] = headers;
                                            }
                                        }

                                        if (containsBatchEtag)
                                        {
                                            if (!headers.ContainsKey("If-None-Match"))
                                                headers["If-None-Match"] = string.Concat('"', batchParameter[ETagKey], '"');
                                            batchParameter.Remove(ETagKey);
                                            batchEtags.Add(i);
                                        }
                                        else
                                        {
                                            if (headers != null && headers.ContainsKey("If-None-Match"))
                                                batchEtags.Add(i);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (string.IsNullOrEmpty(path))
                    {
                        throw new ArgumentNullException("path");
                    }

                    if (httpMethod == HttpMethod.Post && path.EndsWith("/videos"))
                        uriBuilder.Host = UseFacebookBeta ? "graph-video.beta.facebook.com" : "graph-video.facebook.com";
                    else
                        uriBuilder.Host = UseFacebookBeta ? "graph.beta.facebook.com" : "graph.facebook.com";
                }
            }
            else
            {
                uriBuilder = new UriBuilder { Host = uri.Host, Scheme = uri.Scheme };
            }

            uriBuilder.Path = path;

            string contentType = null;
            var queryString = new StringBuilder();

            SerializeParameters(parametersWithoutMediaObjects);

            if (parametersWithoutMediaObjects.ContainsKey("access_token"))
            {
                var accessToken = parametersWithoutMediaObjects["access_token"];
                if (accessToken != null && (!(accessToken is string) || (!string.IsNullOrEmpty((string)accessToken))))
                    queryString.AppendFormat("access_token={0}&", accessToken);

                parametersWithoutMediaObjects.Remove("access_token");
            }

            if (httpMethod != HttpMethod.Post)
            {
                if (containsEtag && httpMethod != HttpMethod.Get)
                    throw new ArgumentException(string.Format("{0} is only supported for http get method.", ETagKey), "httpMethod");

                // for GET,DELETE
                if (mediaObjects.Count > 0 && mediaStreams.Count > 0)
                    throw new InvalidOperationException("Attachments (FacebookMediaObject/FacebookMediaStream) are valid only in POST requests.");

            #if SILVERLIGHT && !WINDOWS_PHONE
                if (httpMethod == HttpMethod.Delete)
                    queryString.Append("method=delete&");
            #endif
                foreach (var kvp in parametersWithoutMediaObjects)
                    queryString.AppendFormat("{0}={1}&", HttpHelper.UrlEncode(kvp.Key), HttpHelper.UrlEncode(BuildHttpQuery(kvp.Value, HttpHelper.UrlEncode)));
            }
            else
            {
                if (mediaObjects.Count == 0 && mediaStreams.Count == 0)
                {
                    contentType = "application/x-www-form-urlencoded";
                    var sb = new StringBuilder();
                    foreach (var kvp in parametersWithoutMediaObjects)
                        sb.AppendFormat("{0}={1}&", HttpHelper.UrlEncode(kvp.Key), HttpHelper.UrlEncode(BuildHttpQuery(kvp.Value, HttpHelper.UrlEncode)));
                    if (sb.Length > 0)
                        sb.Length--;
                    input = sb.Length == 0 ? null : new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString()));
                }
                else
                {
                    string boundary = Boundary == null
                                          ? DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture) // for unit testing
                                          : Boundary();

                    contentType = string.Concat("multipart/form-data; boundary=", boundary);

                    var streams = new List<Stream>();
                    var indexOfDisposableStreams = new List<int>();

                    // Build up the post message header
                    var sb = new StringBuilder();

                    foreach (var kvp in parametersWithoutMediaObjects)
                    {
                        sb.Append(MultiPartFormPrefix).Append(boundary).Append(MultiPartNewLine);
                        sb.Append("Content-Disposition: form-data; name=\"").Append(kvp.Key).Append("\"");
                        sb.Append(MultiPartNewLine).Append(MultiPartNewLine);
                        sb.Append(BuildHttpQuery(kvp.Value, HttpHelper.UrlEncode));
                        sb.Append(MultiPartNewLine);
                    }

                    indexOfDisposableStreams.Add(streams.Count);
                    streams.Add(new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())));

                    foreach (var facebookMediaObject in mediaObjects)
                    {
                        var sbMediaObject = new StringBuilder();
                        var mediaObject = facebookMediaObject.Value;

                        if (mediaObject.ContentType == null || mediaObject.GetValue() == null || string.IsNullOrEmpty(mediaObject.FileName))
                            throw new InvalidOperationException(AttachmentMustHavePropertiesSetError);

                        sbMediaObject.Append(MultiPartFormPrefix).Append(boundary).Append(MultiPartNewLine);
                        sbMediaObject.Append("Content-Disposition: form-data; name=\"").Append(facebookMediaObject.Key).Append("\"; filename=\"").Append(mediaObject.FileName).Append("\"").Append(MultiPartNewLine);
                        sbMediaObject.Append("Content-Type: ").Append(mediaObject.ContentType).Append(MultiPartNewLine).Append(MultiPartNewLine);

                        indexOfDisposableStreams.Add(streams.Count);
                        streams.Add(new MemoryStream(Encoding.UTF8.GetBytes(sbMediaObject.ToString())));

                        byte[] fileData = mediaObject.GetValue();

                        if (fileData == null)
                            throw new InvalidOperationException(AttachmentValueIsNull);

                        indexOfDisposableStreams.Add(streams.Count);
                        streams.Add(new MemoryStream(fileData));
                        indexOfDisposableStreams.Add(streams.Count);
                        streams.Add(new MemoryStream(Encoding.UTF8.GetBytes(MultiPartNewLine)));
                    }

                    foreach (var facebookMediaStream in mediaStreams)
                    {
                        var sbMediaStream = new StringBuilder();
                        var mediaStream = facebookMediaStream.Value;

                        if (mediaStream.ContentType == null || mediaStream.GetValue() == null || string.IsNullOrEmpty(mediaStream.FileName))
                            throw new InvalidOperationException(AttachmentMustHavePropertiesSetError);

                        sbMediaStream.Append(MultiPartFormPrefix).Append(boundary).Append(MultiPartNewLine);
                        sbMediaStream.Append("Content-Disposition: form-data; name=\"").Append(facebookMediaStream.Key).Append("\"; filename=\"").Append(mediaStream.FileName).Append("\"").Append(MultiPartNewLine);
                        sbMediaStream.Append("Content-Type: ").Append(mediaStream.ContentType).Append(MultiPartNewLine).Append(MultiPartNewLine);

                        indexOfDisposableStreams.Add(streams.Count);
                        streams.Add(new MemoryStream(Encoding.UTF8.GetBytes(sbMediaStream.ToString())));

                        var stream = mediaStream.GetValue();

                        if (stream == null)
                            throw new InvalidOperationException(AttachmentValueIsNull);

                        streams.Add(stream);

                        indexOfDisposableStreams.Add(streams.Count);
                        streams.Add(new MemoryStream(Encoding.UTF8.GetBytes(MultiPartNewLine)));
                    }

                    indexOfDisposableStreams.Add(streams.Count);
                    streams.Add(new MemoryStream(Encoding.UTF8.GetBytes(string.Concat(MultiPartNewLine, MultiPartFormPrefix, boundary, MultiPartFormPrefix, MultiPartNewLine))));
                    input = new CombinationStream(streams, indexOfDisposableStreams);
                }
            }

            if (queryString.Length > 0)
                queryString.Length--;

            uriBuilder.Query = queryString.ToString();

            var request = HttpWebRequestFactory == null
                             ? new HttpWebRequestWrapper((HttpWebRequest)WebRequest.Create(uriBuilder.Uri))
                             : HttpWebRequestFactory(uriBuilder.Uri);

            switch (httpMethod)
            {
                case HttpMethod.Get:
                    request.Method = "GET";
                    break;
                case HttpMethod.Delete:
            #if !(SILVERLIGHT && !WINDOWS_PHONE)
                    request.Method = "DELETE";
                    request.TrySetContentLength(0);
                    break;
            #endif
                case HttpMethod.Post:
                    request.Method = "POST";
                    break;
                default:
                    throw new ArgumentOutOfRangeException("httpMethod");
            }

            request.ContentType = contentType;

            if (!string.IsNullOrEmpty(etag))
                request.Headers[HttpRequestHeader.IfNoneMatch] = string.Concat('"', etag, '"');

            #if !(SILVERLIGHT || NETFX_CORE)
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.AllowWriteStreamBuffering = false;
            #endif
            #if NETFX_CORE
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip,deflate";
            #endif

            if (input != null)
                request.TrySetContentLength(input.Length);

            request.TrySetUserAgent("Facebook C# SDK");

            return new HttpHelper(request);
        }
コード例 #17
0
ファイル: FB.cs プロジェクト: roccolangeweg/LumniBenderOfTime
 public static void API(
     string query,
     HttpMethod method,
     FacebookDelegate<IGraphResult> callback,
     WWWForm formData)
 {
     FacebookImpl.API(query, method, formData, callback);
 }
コード例 #18
0
ファイル: FB.cs プロジェクト: roccolangeweg/LumniBenderOfTime
 public static void API(
     string query,
     HttpMethod method,
     FacebookDelegate<IGraphResult> callback = null,
     Dictionary<string, string> formData = null)
 {
     FacebookImpl.API(query, method, formData, callback);
 }
コード例 #19
0
        /// <summary>
        /// For platforms that do not support dynamic cast it to either IDictionary<string, object> if json object or IList<object> if array.
        /// For primitive types cast it to bool, string, dobule or long depending on the type.
        /// Reference: http://facebooksdk.net/docs/making-asynchronous-requests/#1
        /// </summary>
        public static void API(
            string endpoint,
            HttpMethod method,
            FacebookDelegate callback,
            object parameters = null)
        {
#if NETFX_CORE

            Task.Run(async () =>
            {
                FacebookClient fb = new FacebookClient(_fbSessionClient.CurrentAccessTokenData.AccessToken);
                FBResult fbResult = null;
                try
                {
                    object apiCall;
                    if (method == HttpMethod.GET)
                    {
                        apiCall = await fb.GetTaskAsync(endpoint, parameters);
                    }
                    else if (method == HttpMethod.POST)
                    {
                        apiCall = await fb.PostTaskAsync(endpoint, parameters);
                    }
                    else
                    {
                        apiCall = await fb.DeleteTaskAsync(endpoint);
                    }
                    if (apiCall != null)
                    {
                        fbResult = new FBResult();
                        fbResult.Text = apiCall.ToString();
                        fbResult.Json = apiCall as JsonObject;
                    }
                }
                catch (Exception ex)
                {
                    fbResult = new FBResult();
                    fbResult.Error = ex.Message;
                }
                if (callback != null)
                {
                    Dispatcher.InvokeOnAppThread(() => { callback(fbResult); });
                }
            });
#else
            throw new PlatformNotSupportedException("");
#endif
        }
コード例 #20
0
        public virtual void API(
            string query,
            HttpMethod method,
            WWWForm formData,
            FacebookDelegate callback = null)
        {

            if (formData == null)
            {
                formData = new WWWForm();
            }

            formData.AddField(AccessTokenKey, AccessToken);

            AsyncRequestString.Request(GetGraphUrl(query), method, formData, callback);
        }
コード例 #21
0
 private void OnCompleted(HttpMethod httpMethod, FacebookApiEventArgs args)
 {
     switch (httpMethod)
     {
         case HttpMethod.Get:
             OnGetCompleted(args);
             break;
         case HttpMethod.Post:
             OnPostCompleted(args);
             break;
         case HttpMethod.Delete:
             OnDeleteCompleted(args);
             break;
         default:
             throw new ArgumentOutOfRangeException("httpMethod");
     }
 }
コード例 #22
0
 internal AsyncRequestString SetMethod(HttpMethod method)
 {
     this.method = method;
     return this;
 }
コード例 #23
0
 protected internal override object Api(string path, IDictionary<string, object> parameters, HttpMethod httpMethod, Type resultType)
 {
     throw new NotImplementedException();
 }
コード例 #24
0
        public void API(
            string query,
            HttpMethod method,
            Facebook.APIDelegate callback = null,
            Dictionary<string, string> formData = null,
            Facebook.ErrorDelegate errorCallback = null)
        {
            string[] dictKeys = null;
            string[] dictVals = null;

            if(formData != null && formData.Count > 0)
            {
                dictKeys = new string[formData.Count];
                dictVals = new string[formData.Count];
                int idx = 0;
                foreach( KeyValuePair<string, string> kvp in formData )
                {
                    dictKeys[idx] = kvp.Key;
                    dictVals[idx] = System.String.Copy(kvp.Value);
                    idx++;
                }
            }
            iosCallFbApi(GetCallbackHandle(callback), query, method!=null?method.ToString():null, dictKeys, dictVals, formData!=null?formData.Count:0);
        }
コード例 #25
0
        private FacebookApiEventArgs GetApiEventArgs(AsyncCompletedEventArgs e, string json, out HttpMethod httpMethod)
        {
            var state = (WebClientStateContainer)e.UserState;
            httpMethod = state.Method;

            var cancelled = e.Cancelled;
            var userState = state.UserState;
            var error = e.Error;

            // Check for Graph Exception
            var webException = error as WebExceptionWrapper;
            if (webException != null)
            {
                error = ExceptionFactory.GetGraphException(webException);
            }

            if (error == null)
            {
                error = ExceptionFactory.CheckForRestException(DomainMaps, state.RequestUri, json) ?? error;
            }

            var args = new FacebookApiEventArgs(error, cancelled, userState, json);
            return args;
        }