Ejemplo n.º 1
0
        /// <summary>
        /// Get message string from Exception
        /// </summary>
        internal static WebSyncException GetWebSyncException(Exception exception)
        {
            WebSyncException webSyncException = new WebSyncException(exception.Message);

            webSyncException.Type = exception.GetType().ToString();

            return(webSyncException);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Extract session id and sync stage from header
        /// </summary>
        //private static SyncContext GetSyncContextFromHeader(HttpRequest httpRequest)
        //{
        //    if (!httpRequest.Headers.ContainsKey("Dotmim-Sync-Step"))
        //        throw new Exception("No header containing SyncStage");

        //    if (!httpRequest.Headers.ContainsKey("Dotmim-Sync-SessionId"))
        //        throw new Exception("No header containing Session Id");

        //    var stepValue = httpRequest.Headers.First(kvp => kvp.Key == "Dotmim-Sync-Step");
        //    SyncStage httpStep = (SyncStage)Enum.Parse(typeof(SyncStage), stepValue.Value);

        //    var sessionIdValue = httpRequest.Headers.First(kvp => kvp.Key == "Dotmim-Sync-SessionId");
        //    Guid sessionId = Guid.Parse(sessionIdValue.Value);

        //    SyncContext syncContext = new SyncContext(sessionId);
        //    syncContext.SyncStage = httpStep;

        //    return syncContext;
        //}

        /// <summary>
        /// Write exception to output message
        /// </summary>
        public async Task WriteExceptionAsync(HttpResponse httpResponse, Exception ex)
        {
            var webx        = WebSyncException.GetWebSyncException(ex);
            var webXMessage = JsonConvert.SerializeObject(webx);

            httpResponse.StatusCode    = StatusCodes.Status400BadRequest;
            httpResponse.ContentLength = webXMessage.Length;
            await httpResponse.WriteAsync(webXMessage);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Process a request message with HttpClient object.
        /// </summary>
        public async Task <T> ProcessRequest <T>(T content, CancellationToken cancellationToken)
        {
            if (this.BaseUri == null)
            {
                throw new ArgumentException("BaseUri is not defined");
            }

            HttpResponseMessage response = null;
            T dmSetResponse = default(T);

            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                var requestUri = new StringBuilder();
                requestUri.Append(this.BaseUri.ToString());
                requestUri.Append(this.BaseUri.ToString().EndsWith("/", StringComparison.CurrentCultureIgnoreCase) ? string.Empty : "/");

                // Add params if any
                if (ScopeParameters != null && ScopeParameters.Count > 0)
                {
                    string prefix = "?";
                    foreach (var kvp in ScopeParameters)
                    {
                        requestUri.AppendFormat("{0}{1}={2}", prefix, Uri.EscapeUriString(kvp.Key),
                                                Uri.EscapeUriString(kvp.Value));
                        if (prefix.Equals("?"))
                        {
                            prefix = "&";
                        }
                    }
                }

                // default handler if no one specified
                HttpClientHandler httpClientHandler = this.Handler ?? new HttpClientHandler();

                // serialize dmSet content to bytearraycontent
                var serializer = BaseConverter <T> .GetConverter(SerializationFormat);

                var binaryData = serializer.Serialize(content);
                ByteArrayContent arrayContent = new ByteArrayContent(binaryData);

                // do not dispose HttpClient for performance issue
                if (client == null)
                {
                    client = new HttpClient(httpClientHandler);
                }

                // add it to the default header
                if (this.Cookie != null)
                {
                    client.DefaultRequestHeaders.Add("Cookie", this.Cookie.ToString());
                }

                HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri.ToString())
                {
                    Content = arrayContent
                };

                if (this.CustomHeaders != null && this.CustomHeaders.Count > 0)
                {
                    foreach (var kvp in this.CustomHeaders)
                    {
                        requestMessage.Headers.Add(kvp.Key, kvp.Value);
                    }
                }

                //request.AddHeader("content-type", "application/json");
                if (SerializationFormat == SerializationFormat.Json && !requestMessage.Content.Headers.Contains("content-type"))
                {
                    requestMessage.Content.Headers.Add("content-type", "application/json");
                }

                response = await client.SendAsync(requestMessage, cancellationToken);

                if (cancellationToken.IsCancellationRequested)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                // get response from server
                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception(response.ReasonPhrase);
                }

                // try to set the cookie for http session
                var headers = response?.Headers;
                if (headers != null)
                {
                    if (headers.TryGetValues("Set-Cookie", out IEnumerable <string> tmpList))
                    {
                        var cookieList = tmpList.ToList();

                        // var cookieList = response.Headers.GetValues("Set-Cookie").ToList();
                        if (cookieList != null && cookieList.Count > 0)
                        {
                            // Get the first cookie
                            this.Cookie = CookieHeaderValue.ParseList(cookieList).FirstOrDefault();
                        }
                    }
                }

                using (var streamResponse = await response.Content.ReadAsStreamAsync())
                    if (streamResponse.CanRead && streamResponse.Length > 0)
                    {
                        dmSetResponse = serializer.Deserialize(streamResponse);
                    }

                return(dmSetResponse);
            }
            catch (Exception e)
            {
                if (response.Content == null)
                {
                    throw e;
                }

                try
                {
                    var exrror = await response.Content.ReadAsStringAsync();

                    WebSyncException webSyncException = JsonConvert.DeserializeObject <WebSyncException>(exrror);

                    if (webSyncException != null)
                    {
                        throw webSyncException;
                    }
                }
                catch (WebSyncException)
                {
                    throw;
                }
                catch (Exception)
                {
                    // no need to do something here, just rethrow the initial error
                }

                throw e;
            }
        }