示例#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);
        }
示例#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);
        }
示例#3
0
        /// <summary>
        /// Process a request message with HttpClient object.
        /// </summary>
        public async Task <T> ProcessRequest <T>(SyncContext context, T content, CancellationToken cancellationToken)
        {
            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)
                {
                    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);

                // Create the httpClient and send content
                using (HttpClient client = new HttpClient(httpClientHandler))
                {
                    if (this.cookieName != null && this.cookieValue != null)
                    {
                        // add it to the default header
                        client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(this.cookieName, this.cookieValue).ToString());
                    }

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

                    if (this.customHeaders != null)
                    {
                        foreach (var kvp in this.customHeaders)
                        {
                            requestMessage.Headers.Add(kvp.Key, kvp.Value);
                        }
                    }

                    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
                                var cookie = SetCookieHeaderValue.ParseList(cookieList).First();

                                this.cookieName  = cookie.Name.Value;
                                this.cookieValue = cookie.Value.Value;
                            }
                        }
                    }

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