ShipmentAsyncResult GetResponseFromService(string httpRequestMethod, string authorizationHeader, Shipment shipment = null) { string shipperServiceUrl = ConfigurationManager.AppSettings["TargetService"] + RelativePath; JavaScriptSerializer serializer = new JavaScriptSerializer(); IList <Shipment> shipmentList = null; try { HttpWebRequest request = WebRequest.Create(shipperServiceUrl) as HttpWebRequest; request.Method = httpRequestMethod; request.Headers["Authorization"] = authorizationHeader; request.ContentType = "application/json"; if (shipment != null) { // serialize the shipment if available string shipmentData; shipmentData = serializer.Serialize(shipment); using (Stream stream = request.GetRequestStream()) { stream.Write(Encoding.UTF8.GetBytes(shipmentData), 0, shipmentData.Length); } } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // deserialize the response shipmentList = serializer.Deserialize( new StreamReader(response.GetResponseStream()).ReadToEnd(), typeof(IList <Shipment>)) as IList <Shipment>; response.Close(); } } catch (WebException webEx) { // error during fetching data string errorMessage = errorMessage = webEx.Message; if (webEx.Response != null) { HttpWebResponse response = (HttpWebResponse)webEx.Response; if (response.StatusCode == HttpStatusCode.Unauthorized) { MessageBoxResult result = MessageBox.Show("Do you want to clear the user from the token cache and reauthenticate?", "Error talking to service", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { // clear the cache and reauthenticate the user to get a new token _authenticationContext.TokenCacheStore.Clear(); selectedIdentityProviderDescriptor = null; DisplayErrorMessage("Please retry your operation now!"); } else { DisplayErrorMessage(errorMessage); } return(new ShipmentAsyncResult(null)); } else { errorMessage += new StreamReader(webEx.Response.GetResponseStream()).ReadToEnd(); throw new InvalidOperationException(errorMessage); } } } catch (Exception ex) { throw new InvalidOperationException("Error occurred while creating a new shipment. " + ex.Message); } return(new ShipmentAsyncResult(shipmentList)); }
ShipmentAsyncResult CreateNewShipment(Shipment shipment, string authorizationHeader) { return(GetResponseFromService("POST", authorizationHeader, shipment)); }