Ejemplo n.º 1
0
        public override async Task <ResponseResult <TResponseParser> > Execute()
        {
            var webRequestBuilder = new ASWebRequestBuilder();

            string xml = this.Parameters.BuildXml(this.CommandName);

            NetworkCredential credential = new NetworkCredential(this.Settings.Login, this.Settings.Password);

            string url = string.Format("{0}{1}?Cmd={2}&User={3}&DeviceId={4}&DeviceType={5}",
                                       this.Settings.HostName,
                                       ServerUrlDirectory,
                                       this.CommandName,
                                       this.Settings.Login,
                                       this.Settings.DeviceId,
                                       this.Settings.DeviceType);

            var headers = new Dictionary <string, string>
            {
                { "MS-ASProtocolVersion", this.Settings.ProtocolVersion },
                { "X-MS-PolicyKey", this.Settings.PolicyKey.ToString() },
            };

            WebRequestResponse response = null;

            try
            {
                response = await webRequestBuilder.SendRequestAsync(
                    url,
                    HttpMethod.Post,
                    ContentTypeWbXml,
                    xml,
                    headers,
                    credential);

                // settings must be updated if a redirection occured
                string requestUri = response.Request.RequestUri.GetSchemeAndHost();
                if (requestUri.TrimEnd('/') != this.Settings.HostName.TrimEnd('/'))
                {
                    string oldHostName = this.Settings.HostName;
                    this.Settings.HostName = requestUri;
                    LogService.Log("ASCommandBase", $"Successfull redirection from {oldHostName} to {requestUri}");
                }

                if (response.Response.IsSuccessStatusCode)
                {
                    var parser = new TResponseParser();
                    parser.ParseResponse(this.CommandName, response);

                    return(ResponseResult <TResponseParser> .Create(parser, requestUri));
                }
                else
                {
                    return(this.CreateResponseResult(null, response, requestUri));
                }
            }
            catch (Exception ex)
            {
                return(this.CreateResponseResult(ex, response, url));
            }
        }
Ejemplo n.º 2
0
        public void ParseResponse(string commandName, WebRequestResponse response)
        {
            if (response.Response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new CommandAuthorizationException(string.Format("Authorization failed: {0}", response.Response.ReasonPhrase));
            }

            string xml = response.ResponseBody;

            XDocument xdoc = null;

            string xmlValidationErrorMessage;

            if (!EwsXmlHelper.IsValidXml(xml, out xmlValidationErrorMessage))
            {
                if (this.RequireValidXml)
                {
                    throw new CommandResponseXmlException(string.Format("Invalid xml content: {0}", xmlValidationErrorMessage));
                }
            }
            else
            {
                xdoc = XDocument.Load(new StringReader(xml));
            }

            this.ParseResponseCore(commandName, xdoc, response);
        }
Ejemplo n.º 3
0
        private void ManageClientAcknowledgement(XElement collection, WebRequestResponse response)
        {
            var responses = collection.Element("Responses");

            if (responses == null)
            {
                return;
            }

            // tasks added
            var adds = responses.Elements("Add");

            if (adds != null)
            {
                foreach (var add in adds)
                {
                    var status = add.Element("Status").Value;

                    if (status == "1")
                    {
                        var clientId = int.Parse(add.Element("ClientId").Value);
                        var serverId = add.Element("ServerId").Value;
                        this.ServerAddedTasks++;
                        this.ClientServerMapIds.Add(clientId, serverId);
                    }
                    else
                    {
                        TryTrackEvent("Add failed status " + status, response.RequestBody);
                        if (InvalidStatusFound != null)
                        {
                            InvalidStatusFound(this, new EventArgs <string>($"Update task status failure: {status}"));
                        }
                    }
                }
            }

            // tasks changed
            var changes = responses.Elements("Change");

            if (changes != null)
            {
                foreach (var change in changes)
                {
                    var status = change.Element("Status").Value;

                    // Manage status != 1
                    if (status == "1")
                    {
                        this.ServerModifiedTasks++;
                    }
                    else
                    {
                        TryTrackEvent("Update failed status " + status, response.RequestBody);
                    }
                }
            }

            // task deleted, nothing because delete acknowledgement is not sent back
        }
Ejemplo n.º 4
0
        public void ParseResponse(string commandName, WebRequestResponse response)
        {
            if (response.Response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new CommandAuthorizationException(string.Format("Authorization failed: {0}", response.Response.ReasonPhrase));
            }

            string xml = response.ResponseBody;

            string xmlValidationErrorMessage;

            if (!EwsXmlHelper.IsValidXml(xml, out xmlValidationErrorMessage))
            {
                throw new CommandResponseXmlException(string.Format("Invalid xml content: {0}", xmlValidationErrorMessage));
            }

            var root = XDocument.Load(new StringReader(xml)).Root;

            if (response.Response.IsSuccessStatusCode)
            {
                // read error section
                var error = root.XGetChild("Response/Error", NsEwsAutodiscover);
                if (error != null)
                {
                    string errorCode = error.XGetChildValue <string>("ErrorCode", NsEwsAutodiscover);
                    string message   = error.XGetChildValue <string>("Message", NsEwsAutodiscover);
                    string debugData = error.XGetChildValue <string>("DebugData", NsEwsAutodiscover);

                    LogService.Log("AutoDiscoverResult", string.Format("Error response code: {0} message: {1} debug data: {2}", errorCode, message, debugData));
                    return;
                }

                // read protocols section
                var nodes = root.XGetChildrenOf("Response/Account", NsEwsOutlookAutodiscover);
                foreach (var node in nodes)
                {
                    if (node.Name != null && node.Name.LocalName.Equals("Protocol", StringComparison.OrdinalIgnoreCase))
                    {
                        var type   = node.XGetChildValue <string>("Type", NsEwsOutlookAutodiscover);
                        var ewsUrl = node.XGetChildValue <string>("EwsUrl", NsEwsOutlookAutodiscover);

                        // read more about protocol type: http://blogs.technet.com/b/exchange/archive/2008/09/26/3406344.aspx
                        if (type.Equals("exch", StringComparison.OrdinalIgnoreCase))
                        {
                            this.InternalEwsUrl = ewsUrl;
                        }
                        else if (type.Equals("expr", StringComparison.OrdinalIgnoreCase))
                        {
                            this.ExternalEwsUrl = ewsUrl;
                        }
                    }
                    else if (node.Name != null && node.Name.LocalName.Equals("RedirectAddr", StringComparison.OrdinalIgnoreCase))
                    {
                        this.RedirectEmailAddress = node.Value;
                    }
                }
            }
        }
Ejemplo n.º 5
0
        private void PopulateList <T>(ref List <T> list, WebRequestResponse response)
        {
            if (!response.Succeeded)
            {
                return;
            }

            list = new List <T>(response.ResponseArray <T>());
        }
Ejemplo n.º 6
0
        private void PopulateEventCode(WebRequestResponse response, UnityAction <EventCode> onEventCodeReceived)
        {
            if (!response.Succeeded)
            {
                return;
            }

            onEventCodeReceived?.Invoke(response.Response <EventCode>());
        }
Ejemplo n.º 7
0
        private async Task <WebRequestResponse> ProcessRequest(HttpResponseMessage response)
        {
            var ret = new WebRequestResponse();

            ret.IsSuccess  = response.IsSuccessStatusCode;
            ret.Reason     = response.ReasonPhrase;
            ret.StatusCode = (int)response.StatusCode;
            ret.Content    = await response.Content.ReadAsByteArrayAsync();

            return(ret);
        }
Ejemplo n.º 8
0
        public async Task <WebRequestResponse> ProcessRequest(UnityWebRequest request)
        {
            await request.SendWebRequest();

            var ret = new WebRequestResponse();

            ret.IsSuccess  = !request.isNetworkError && !request.isHttpError;
            ret.Reason     = request.error;
            ret.StatusCode = (int)request.responseCode;
            ret.Content    = request.downloadHandler.data;
            return(ret);
        }
Ejemplo n.º 9
0
        private void OnGetBranches(WebRequestResponse response)
        {
            if (!response.Succeeded)
            {
                return;
            }

            foreach (Branch branch in laGranLuchaManager.Branches)
            {
                Instantiate <BranchHandler>(branchPrefab, branchesContainer).Initialize(branch);
            }
        }
Ejemplo n.º 10
0
        private void OnGetDrinks(WebRequestResponse response)
        {
            if (!response.Succeeded)
            {
                return;
            }

            foreach (Drink drink in laGranLuchaManager.Drinks)
            {
                foreach (Variant variant in drink.Variants)
                {
                    Instantiate <CartItemHandler>(cartItemHandler, drinkContainer).Initialize(variant);
                }
            }
        }
Ejemplo n.º 11
0
        private void OnGetFoods(WebRequestResponse response)
        {
            if (!response.Succeeded)
            {
                return;
            }

            foreach (Food food in laGranLuchaManager.Foods)
            {
                foreach (Variant variant in food.Variants)
                {
                    Instantiate <CartItemHandler>(cartItemHandler, foodContainer).Initialize(variant);
                }
            }
        }
Ejemplo n.º 12
0
        private async Task <ResponseResult <TResponseParser> > SendRequestAsync(string xml, string username, string password, bool secondTry = false)
        {
            WebRequestResponse response = null;

            try
            {
                response = await this.webRequestBuilder.SendRequestAsync(
                    this.Settings.ServerUri,
                    HttpMethod.Post,
                    ContentTypeTextXml,
                    xml,
                    new Dictionary <string, string>(),
                    new NetworkCredential(username, password));

                if (response.Response.IsSuccessStatusCode)
                {
                    var parser = new TResponseParser();
                    parser.ParseResponse(this.CommandName, response);

                    return(ResponseResult <TResponseParser> .Create(parser, this.Settings.ServerUri));
                }
                else if (!secondTry && response.Response.StatusCode == HttpStatusCode.Unauthorized && this.Settings.Email != null && this.Settings.Username != this.Settings.Email)
                {
                    // one more try using email for authentication
                    return(await this.SendRequestAsync(xml, this.Settings.Email, this.Settings.Password, true));
                }
                else
                {
                    return(this.CreateResponseResult(null, response, this.Settings.ServerUri));
                }
            }
            catch (Exception ex)
            {
                return(this.CreateResponseResult(ex, response, this.Settings.ServerUri));
            }
        }
Ejemplo n.º 13
0
        protected ResponseResult <TResponseParser> CreateResponseResult(Exception exception, WebRequestResponse response, string uri)
        {
            string exceptionMessage  = null;
            string statusCodeMessage = null;

            if (exception != null)
            {
                exceptionMessage += $"Exception: {exception.Message}";
                if (!string.IsNullOrWhiteSpace(exception.InnerException?.Message))
                {
                    exceptionMessage += $" ({exception.InnerException.Message}).";
                }
                else
                {
                    exceptionMessage += ".";
                }
            }

            if (response != null)
            {
                if (response.Response.StatusCode != HttpStatusCode.OK)
                {
                    if (response.Response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        statusCodeMessage = "Got 'Unauthorized' response status code, check credentials (email, login, password) are correct.";
                    }
                    else
                    {
                        statusCodeMessage = $"Got '{response.Response.StatusCode}' response status code.";
                    }
                }
            }

            HttpResponseMessage responseMessage = null;

            if (response != null && response.Response != null)
            {
                responseMessage = response.Response;
            }

            string message = exceptionMessage;

            if (statusCodeMessage != null)
            {
                if (message != null)
                {
                    message += exceptionMessage;
                }
                else
                {
                    message = statusCodeMessage;
                }
            }

            return(ResponseResult <TResponseParser> .Create(
                       new CommandException($"Error while executing '{this.CommandName}'", message, exception, responseMessage),
                       uri));
        }
Ejemplo n.º 14
0
 protected abstract void ParseResponseCore(string commandName, XDocument document, WebRequestResponse response);
Ejemplo n.º 15
0
        private static void _req(string uri, HttpRequestMethod method, Dictionary <string, string> form, WebRequestResponse webReqResponse)
        {
            var webReq = (HttpWebRequest)NetWebRequest.Create(uri);

            webReq.Method      = method.ToString();
            webReq.ContentType = "application/x-www-form-urlencoded";

            var reqData = Encoding.UTF8.GetBytes(_flattenForm(form));

            webReq.ContentLength = reqData.Length;

            Worker.StartWorker((out object result) =>
            {
                try
                {
                    if (webReq.Method != "GET")
                    {
                        using (var stream = webReq.GetRequestStream()) {
                            stream.Write(reqData, 0, reqData.Length);
                        }
                    }

                    var response              = (HttpWebResponse)webReq.GetResponse();
                    var webResponseData       = new WebRequestResponseData();
                    bool success              = ((int)response.StatusCode) >= 200 && ((int)response.StatusCode) < 300;
                    webResponseData.isSuccess = success;
                    webResponseData.code      = (int)response.StatusCode;
                    webResponseData.data      = new byte[0];
                    if (response != null)
                    {
                        using (var mem = new MemoryStream())
                        {
                            using (var stream = response.GetResponseStream())
                            {
                                while (true)
                                {
                                    var data = stream.ReadByte();
                                    if (data == -1)
                                    {
                                        break;
                                    }
                                    mem.WriteByte((byte)data);
                                }
                                webResponseData.data = mem.ToArray();
                            }
                        }
                    }
                    result = webResponseData;
                    response.Close();
                }
                catch (WebException e)
                {
                    var response              = (HttpWebResponse)e.Response;
                    var webResponseData       = new WebRequestResponseData();
                    webResponseData.isSuccess = false;
                    webResponseData.code      = response != null ? (int)response.StatusCode : 404;
                    webResponseData.data      = new byte[0];
                    result = webResponseData;
                    response?.Close();
                }
                return(true);
            }, (e, result) => {
                if (e != null && !string.IsNullOrEmpty(e.Message))
                {
                    Console.WriteLine("WebRequest Error: " + e);
                }
                webReqResponse?.Invoke(result as WebRequestResponseData);
            });
        }
Ejemplo n.º 16
0
 public static void GET(string uri, Dictionary <string, string> form, WebRequestResponse OnComplete)
 {
     _req(uri, HttpRequestMethod.GET, form, OnComplete);
 }
Ejemplo n.º 17
0
        public void ParseResponse(string commandName, WebRequestResponse response)
        {
            if (response.Response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new CommandAuthorizationException(string.Format("Authorization failed: {0}", response.Response.ReasonPhrase));
            }

            if (response.Response.IsSuccessStatusCode)
            {
                string xml = response.ResponseBody;

                string xmlValidationErrorMessage;
                if (!EwsXmlHelper.IsValidXml(xml, out xmlValidationErrorMessage))
                {
                    throw new CommandResponseXmlException(string.Format("Invalid xml content: {0}", xmlValidationErrorMessage));
                }

                XDocument xdoc = XDocument.Load(new StringReader(xml));

                var responseMessages    = xdoc.Root.XGetChildrenOf(string.Format("Body/{0}Response/ResponseMessages", commandName));
                var ewsResponseMessages = new List <EwsResponseMessage>();

                foreach (var responseMessage in responseMessages)
                {
                    var ewsResponseMessage = new EwsResponseMessage
                    {
                        Class   = responseMessage.XGetAttributeValue <EwsResponseClass>("ResponseClass"),
                        Code    = responseMessage.XGetChildValue <string>("ResponseCode", true),
                        Message = responseMessage.XGetChildValue <string>("MessageText", true),
                        Content = responseMessage
                    };

                    if (ewsResponseMessage.Class != EwsResponseClass.Success || ewsResponseMessage.Code != ResponseCodeNoError)
                    {
                        string message = string.Format("response is invalid (class: {0} code: {1} message: {2}) content: {3})", ewsResponseMessage.Class, ewsResponseMessage.Code, ewsResponseMessage.Message, responseMessage);
                        Log(commandName, message);

                        if (OnInvalidResponse != null)
                        {
                            OnInvalidResponse(this, new EventArgs <string>(message));
                        }
                    }

                    ewsResponseMessages.Add(ewsResponseMessage);
                }

                try
                {
                    this.ParseResponseCore(ewsResponseMessages);
                }
                catch (Exception ex)
                {
                    throw new CommandResponseException(string.Format("Failed to parse {0} response", commandName), ex);
                }
            }
            else
            {
                Log(commandName, string.Format("response does not have HTTP sucess status code (code: {0})", response.Response.StatusCode));
                EwsFault fault = null;
                string   xml;
                try
                {
                    xml = response.ResponseBody;
                    XDocument xdoc = XDocument.Load(new StringReader(xml));

                    fault = this.ExtractFault(xdoc);
                    Log(commandName, string.Format("fault: " + fault));
                }
                catch (Exception)
                {
                    response.Response.Content.ReadAsStringAsync().ContinueWith(r => Log(commandName, string.Format("response: " + r.Result)));
                }

                throw new CommandResponseException(string.Format("Failed to read {0} response, fault: {1}", commandName, fault != null ? fault.ToString() : "unknown fault"));
            }
        }
Ejemplo n.º 18
0
 protected override void ParseResponseCore(string commandName, XDocument document, WebRequestResponse response)
 {
     this.Status    = document.Element("Provision").Element("Policies").Element("Policy").Element("Status").Value;
     this.PolicyKey = document.Element("Provision").Element("Policies").Element("Policy").Element("PolicyKey").Value;
 }
Ejemplo n.º 19
0
        protected override void ParseResponseCore(string commandName, XDocument document, WebRequestResponse response)
        {
            if (document == null)
            {
                // no changes, leave the object as is
                this.Status = "1";
                return;
            }

            if (document.Element("Sync").Elements("Status").Any())
            {
                this.Status = document.Element("Sync").Element("Status").Value;
                LogService.LogFormat("SyncCommandResult", "General status not OK : {0}", this.Status);

                // we detect and are able to react to provisioning error status code
                if (!ActiveSyncErrorHelper.IsStatusProvisioningError(this.Status, null))
                {
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }

                    if (InvalidStatusFound != null)
                    {
                        InvalidStatusFound(this, new EventArgs <string>($"Status: {this.Status}"));
                    }
                }

                return;
            }

            var collection = document.Element("Sync").Element("Collections").Element("Collection");

            this.SyncKey       = collection.Element("SyncKey").Value;
            this.Status        = collection.Element("Status").Value;
            this.MoreAvailable = collection.Elements("MoreAvailable").Any();

            this.ManageServerChanges(collection);
            this.ManageClientAcknowledgement(collection, response);

            LogService.LogFormat("SyncCommandResult", "status: {0} sync key: {1} more: {2}", this.Status, this.SyncKey.TakeLast(5), this.MoreAvailable.ToString());
        }
Ejemplo n.º 20
0
        public WebRequestResponse DoGetRequest(WebRequestData requestData, Microsoft.Xrm.Sdk.ITracingService trace)
        {
            try
            {
                #region debug log

                this.LogPluginFeedback(new LogClass
                {
                    Exception  = "",
                    Level      = "debug",
                    ClassName  = this.GetType().ToString(),
                    MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name,
                    Message    = $"GETing Url:{requestData.Url}",
                    ProcessId  = ""
                }, trace);

                #endregion debug log
            }
            catch (Exception exc)
            {
            }

            WebRequestResponse wrResponse = new WebRequestResponse();
            try
            {
                try
                {
                    using (WebClient client = new WebClient())
                    {
                        var webClient = new WebClient();
                        if (requestData.ContentType != "")
                        {
                            webClient.Headers[HttpRequestHeader.ContentType] = requestData.ContentType;
                        }

                        if (requestData.Authorization != "")
                        {
                            webClient.Headers[HttpRequestHeader.Authorization] = requestData.Authorization;
                        }

                        // var code = "key";
                        string serviceUrl = requestData.Url;
                        wrResponse.Data = webClient.DownloadString(serviceUrl);

                        if (wrResponse.Data != "")
                        {
                            wrResponse.IsSuccessful = true;

                            //TODO:ELiminar para Produccion
                            try
                            {
                                this.LogPluginFeedback(new LogClass
                                {
                                    Exception  = "",
                                    Level      = "debug",
                                    ClassName  = this.GetType().ToString(),
                                    MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name,
                                    Message    = $"Url:{requestData.Url} ResponseFromRequest:{wrResponse.Data}",
                                    ProcessId  = ""
                                }, trace);
                            }
                            catch (Exception e)
                            {
                            }
                        }
                    }
                }
                catch (WebException wex)
                {
                    string error      = "";
                    string statusCode = "";
                    if (wex.Response != null)
                    {
                        using (var errorResponse = (HttpWebResponse)wex.Response)
                        {
                            using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                            {
                                error = reader.ReadToEnd();
                            }
                        }
                    }

                    #region error log

                    this.LogPluginFeedback(new LogClass
                    {
                        Exception  = wex.ToString(),
                        Level      = "error",
                        ClassName  = this.GetType().ToString(),
                        MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name,
                        Message    = $"{error}",
                        ProcessId  = ""
                    }, trace);

                    #endregion error log

                    wrResponse.Data         = null;
                    wrResponse.ErrorMessage = wex.ToString();
                    wrResponse.IsSuccessful = false;
                }
            }
            catch (Exception ex)
            {
                this.LogPluginFeedback(new LogClass
                {
                    Exception  = ex.ToString(),
                    Level      = "error",
                    ClassName  = this.GetType().ToString(),
                    MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name,
                    Message    = $"Excepción realizando el POST request",
                    ProcessId  = ""
                }, trace);

                trace.Trace($"MethodName: {new System.Diagnostics.StackTrace(ex).GetFrame(0).GetMethod().Name}|--|Exception: " + ex.ToString());
                wrResponse.Data         = null;
                wrResponse.IsSuccessful = false;
                wrResponse.ErrorMessage = ex.ToString();
            }

            return(wrResponse);
        }
Ejemplo n.º 21
0
        protected override void ParseResponseCore(string commandName, XDocument document, WebRequestResponse response)
        {
            XElement folderElement = document.Element("FolderSync");

            if (folderElement != null)
            {
                XElement keyElement = folderElement.Element("SyncKey");
                if (keyElement != null)
                {
                    this.SyncKey = keyElement.Value;
                }

                XElement statusElement = folderElement.Element("Status");
                if (statusElement != null)
                {
                    this.Status = statusElement.Value;
                }

                FillFolderList(document, "Add", this.AddedFolders);
                FillFolderList(document, "Update", this.ModifiedFolders);
                FillFolderList(document, "Delete", this.DeletedFolders);
            }
        }