Beispiel #1
0
        internal static async Task <ServiceEvent <T> > ExecuteStreamAsync <T>(this Uri uri, KZApplication app, Stream content = null, string method = "GET", bool cache = false, TimeSpan?timeout = null, Dictionary <string, string> headers = null, UseToken useToken = UseToken.Application, Action <long[]> onProgress = null, bool cors = false) where T : Stream
        {
            Request  request  = null;
            Response response = null;

            if (headers == null)
            {
                headers = new Dictionary <string, string>();
            }

            try
            {
                // Does the URL require a no cache?
                if (!cache)
                {
                    uri = addNoCache(uri);
                    headers.Add("Cache-Control", "no-cache");
                    headers.Add("Pragma", "no-cache");
                }

                // Adds authentication's header
                if (useToken != UseToken.None && app != null && app.Authentication != null && app.Authentication.User != null)
                {
                    addAuthenticationHeader(app, useToken, headers);
                }

                request = await Request.Create(uri, method.ToUpper(), content, headers, timeout);

                response = (method == "POST" || method == "GET" || method == "PUT") ?
                           await request.Send_POST_GET_PUT(onProgress) :
                           await request.Send_OTHERS(onProgress);

                // Is token expired?
                if (response.StatusCode == HttpStatusCode.Unauthorized && app.User != null)
                {
                    // Refresh token if it is expired
                    var authHeader = response.Headers["WWW-Authenticate"];
                    if (!string.IsNullOrWhiteSpace(authHeader))
                    {
                        var realm = authHeader
                                    .Split(',')
                                    .Where(r => r.StartsWith("error="))
                                    .FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(realm))
                        {
                            var message = realm.Split('=')[1].Trim();
                            if (string.Compare(message, "\"Token is expired\"", StringComparison.CurrentCultureIgnoreCase) == 0)
                            {
                                // Do refresh tokens
                                app.Authentication.RemoveFromCache(app.User.Credential.UserName, app.User.Credential.Password, app.User.Provider);
                                await app.Authentication.Authenticate(app.User.Credential.UserName, app.User.Credential.Password, app.User.Provider);

                                // Set new auth header
                                addAuthenticationHeader(app, useToken, request.Headers);
                                request.Content.Seek(0, SeekOrigin.Begin);

                                // Send request
                                response = (method == "POST" || method == "GET" || method == "PUT") ?
                                           await request.Send_POST_GET_PUT(onProgress) :
                                           await request.Send_OTHERS(onProgress);
                            }
                        }
                    }
                }

                // Process response
                var evt = new ServiceEvent <T>();
                evt.StatusCode = response.StatusCode;
                evt.Headers    = response.Headers;

                var read  = 0L;
                var total = response.Body == null ? 0 : response.Body.Length;

                // Download the body as stream an send progress information

                // Sends initial progress notification
                if (onProgress != null)
                {
                    onProgress(new[] { read, total });
                }

                // Creates the stream that will be returned to the client
                var result = new MemoryStream();
                if (total > 0)
                {
                    // Copies the response body's stream
                    var buffer    = new byte[4096];
                    var bytesRead = await response.Body.ReadAsync(buffer, 0, 4096);

                    while (bytesRead > 0)
                    {
                        result.WriteAsync(buffer, 0, bytesRead);
                        if (onProgress != null)
                        {
                            read += bytesRead;
                            onProgress(new[] { read, total });
                        }
                        bytesRead = await response.Body.ReadAsync(buffer, 0, 4096);
                    }
                    // Rewinds the stream
                    result.Seek(0, SeekOrigin.Begin);
                }
                evt.DataAsStream = (Stream)result;

                return(evt);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (request != null)
                {
                    request.Dispose();
                }
                if (response != null)
                {
                    response.Dispose();
                }
            }
        }
Beispiel #2
0
        internal static async Task <ServiceEvent <T> > ExecuteAsync <T>(this Uri uri, KZApplication app, Stream content = null, string method = "GET", bool cache = false, TimeSpan?timeout = null, Dictionary <string, string> headers = null, UseToken useToken = UseToken.Application, Action <long[]> onProgress = null, bool cors = false)
        {
            Request  request  = null;
            Response response = null;

            if (headers == null)
            {
                headers = new Dictionary <string, string>();
            }

            try
            {
                // Does the URL require a no cache?
                if (!cache)
                {
                    uri = addNoCache(uri);
                    headers.Add("Cache-Control", "no-cache");
                    headers.Add("Accept", "*/*");
                    headers.Add("Pragma", "no-cache");
                }
                if (timeout != null && timeout.HasValue)
                {
                    headers.Add("timeout", timeout.Value.TotalSeconds.ToString());
                }

                //**** Passive Auth HotFix ****
                if (app != null && app.PassiveAuthenticationInformation != null)
                {
                    headers["Authorization"] = "WRAP access_token=\"" + app.PassiveAuthenticationInformation["access_token"] + "\"";
                }
                else
                {
                    // Adds authentication's header
                    if (useToken != UseToken.None && app != null && app.Authentication != null && app.Authentication.User != null)
                    {
                        addAuthenticationHeader(app, useToken, headers);
                    }
                }

                request = await Request.Create(uri, method.ToUpper(), content, headers, timeout);

                response = (method == "POST" || method == "GET" || method == "PUT")?
                           await request.Send_POST_GET_PUT(onProgress) :
                           await request.Send_OTHERS(onProgress);

                // Is token expired?
                if (response.StatusCode == HttpStatusCode.Unauthorized && app.User != null)
                {
                    // Refresh token if it is expired
                    var authHeader = response.Headers["WWW-Authenticate"];
                    if (!string.IsNullOrWhiteSpace(authHeader))
                    {
                        var realm = authHeader
                                    .Split(',')
                                    .Where(r => r.StartsWith("error="))
                                    .FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(realm))
                        {
                            var message = realm.Split('=')[1].Trim();
                            if (string.Compare(message, "\"Token is expired\"", StringComparison.CurrentCultureIgnoreCase) == 0)
                            {
                                //**** Passive Auth HotFix ****
                                if (app.PassiveAuthenticationInformation != null)
                                {
                                    var newAuthToken = refreshPassiveToken(app.PassiveAuthenticationInformation);
                                    request.Headers["Authorization"] = "WRAP access_token=\"" + newAuthToken + "\"";
                                    request.Content.Seek(0, SeekOrigin.Begin);

                                    // Send request
                                    response = (method == "POST" || method == "GET" || method == "PUT") ?
                                               await request.Send_POST_GET_PUT(onProgress) :
                                               await request.Send_OTHERS(onProgress);
                                }
                                else
                                {
                                    // Do refresh tokens
                                    app.Authentication.RemoveFromCache(app.User.Credential.UserName, app.User.Credential.Password, app.User.Provider);
                                    await app.Authentication.Authenticate(app.User.Credential.UserName, app.User.Credential.Password, app.User.Provider);

                                    // Set new auth header
                                    addAuthenticationHeader(app, useToken, request.Headers);
                                    request.Content.Seek(0, SeekOrigin.Begin);

                                    // Send request
                                    response = (method == "POST" || method == "GET" || method == "PUT") ?
                                               await request.Send_POST_GET_PUT(onProgress) :
                                               await request.Send_OTHERS(onProgress);
                                }
                            }
                        }
                    }
                }

                // Process response
                var evt = new ServiceEvent <T>();
                evt.StatusCode = response.StatusCode;
                evt.Headers    = response.Headers;

                if (typeof(T) == typeof(object))
                {
                    using (var stream = response.Body)
                    {
                        using (var reader = new StreamReader(stream, UTF8Encoding.UTF8))
                        {
                            var data = await reader.ReadToEndAsync();

                            evt.DataAsString = data;
                        }
                        evt.DataAsStream = response.Body;
                    }
                }
                else if (response.Headers.ContainsKey("Content-Type") && response.Headers["Content-Type"].Contains("application/json"))
                {
                    using (var reader = new StreamReader(response.Body, Encoding.UTF8))
                    {
                        using (var jsonReader = new JsonTextReader(reader))
                        {
                            evt.Data = serializer.Deserialize <T>(jsonReader);
                        }
                    }
                }
                return(evt);
            }
            catch (Exception e)
            {
                throw;
            }
            finally
            {
                if (request != null)
                {
                    request.Dispose();
                }
                if (response != null)
                {
                    response.Dispose();
                }
            }
        }