private static async Task <GenericWriteObject <T> > CallOdataEndpointAsyncComplexByDate <T>(string requestUri, ServiceData authData, DateTime startDate, DateTime endDate) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authData.AuthMethod, authData.AuthToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.Timeout = new TimeSpan(0, 3, 0); string endPoint = requestUri + "/" + startDate.Year + "?budatf=" + startDate.ToString("yyyyMMdd") + "&budatt=" + endDate.ToString("yyyyMMdd"); var result = new GenericWriteObject <T>(); try { using (var response = await client.GetAsync(endPoint)) { var responseString = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { result.WriteObject = JsonConvert.DeserializeObject <T>(responseString); return(result); } else { result.Exception = new AxBaseException { ApplicationException = new ApplicationException(responseString) }; return(result); } } } catch (ArgumentNullException ne) { result.Exception = new AxBaseException { ApplicationException = ne }; return(result); } catch (TaskCanceledException) { result.Exception = new AxBaseException { ApplicationException = new ApplicationException("Timeout Expired for " + requestUri) }; return(result); } catch (Exception e) { result.Exception = new AxBaseException { ApplicationException = e }; return(result); } }
public async Task <GenericWriteObject <T> > CallOdataEndpointPostStringReturn <T>(string oDataEndpoint, string filters, T postDataObject, ServiceData authData, string csrfToken) { using (HttpClientHandler handler = new HttpClientHandler()) { handler.CookieContainer = this.cookieContainer; using (HttpClient client = new HttpClient(handler)) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authData.AuthMethod, authData.AuthToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (!string.IsNullOrEmpty(csrfToken)) { client.DefaultRequestHeaders.Add("x-csrf-token", csrfToken); } client.Timeout = new TimeSpan(0, 3, 0); string endpoint = authData.BaseUrl + authData.OdataUrlPostFix + oDataEndpoint + filters ?? ""; var postData = JsonConvert.SerializeObject(postDataObject); var content = new StringContent(postData, Encoding.UTF8, "application/json"); var result = new GenericWriteObject <T>(); try { using (var response = await client.PostAsync(endpoint, content)) { if (response.IsSuccessStatusCode) { result.SimpleResult = await response.Content.ReadAsStringAsync(); } else { var errorResult = await response.Content.ReadAsStringAsync(); result.Exception = new AxBaseException { ApplicationException = new Exception("Error when sending post request json = " + postData + " " + errorResult) }; } return(result); } } catch (Exception e) { if (e is AggregateException) { return(new GenericWriteObject <T> { Exception = new AxBaseException { ApplicationException = e.InnerException } }); } else { return(new GenericWriteObject <T> { Exception = new AxBaseException { ApplicationException = e } }); } } } } }
public static async Task <GenericWriteObject <T> > CallOdataEndpointPost <T>(string oDataEndpoint, string filters, T postDataObject) { string baseUrl = System.Configuration.ConfigurationManager.AppSettings["base_url"]; string endpoint = baseUrl + "/data/" + oDataEndpoint + ApplyCrossCompanyFilter(filters) ?? ""; var request = HttpWebRequest.Create(endpoint); request.Headers["Authorization"] = Authenticator.GetAuthData(Common.ErpTasks.ErpTaskStep.AuthenticationType.D365).AuthHeader; //request.Headers["Accept"] = "application/json;odata.metadata=none"; //request.Headers["Content-Type"] = "application/json"; request.Method = "POST"; var postData = JsonConvert.SerializeObject(postDataObject, new EnumConverter()); //request.ContentLength = postData != null ? postData.Length : 0; request.ContentType = "application/json"; GenericWriteObject <T> result = new GenericWriteObject <T>(); try { using (var requestStream = await request.GetRequestStreamAsync()) { using (var writer = new StreamWriter(requestStream)) { writer.Write(postData); writer.Flush(); } } using (var response = (HttpWebResponse)(await request.GetResponseAsync())) { using (var responseStream = response.GetResponseStream()) { using (var streamReader = new StreamReader(responseStream)) { var responseString = streamReader.ReadToEnd(); //string sanitized = SanitizeJsonString(responseString); result.WriteObject = JsonConvert.DeserializeObject <T>(responseString); return(result); //return responseString; } } } } catch (WebException e) { using (var rStream = e.Response.GetResponseStream()) { using (var reader = new StreamReader(rStream)) { result.Exception = JsonConvert.DeserializeObject <AxBaseException>(reader.ReadToEnd()); // TODO: Need to log error; return(result); } } } catch (Exception e) { if (e is AggregateException) { return(new GenericWriteObject <T> { Exception = new AxBaseException { ApplicationException = e.InnerException } }); } else { return(new GenericWriteObject <T> { Exception = new AxBaseException { ApplicationException = e } }); } } }
public static async Task <AxBaseException> CallOdataEndpointComplexByDate <T, Y>(ErpTaskStep step, string filters, List <ErpTaskStepDetails> resultProperties, int actionId, ServiceData authData, DateTime startDate) where T : GenericJsonOdata <Y> { DateTime startTime = DateTime.Now; try { var baseUrl = authData.BaseUrl; var endpoint = baseUrl + authData.OdataUrlPostFix + step.EndPoint; DateTime firstDayOfMonth = new DateTime(startDate.Year, startDate.Month, 1); var returnODataObject = new GenericWriteObject <Y>(); bool isFirstIteration = true; for (DateTime d = firstDayOfMonth; d <= DateTime.Now.Date; d = d.AddMonths(1)) { returnODataObject = await CallOdataEndpointAsyncComplexByDate <Y>(endpoint, authData, d, d.AddMonths(1).AddDays(-1)); var results = returnODataObject.WriteObject; foreach (var stepDetail in resultProperties) { if (results != null && results.GetType().GetProperty(stepDetail.nested_property_name) != null) { if (isFirstIteration) { DataWriter.TruncateSingleTable(stepDetail.db_table); isFirstIteration = false; } Type genericType = typeof(List <>).MakeGenericType(stepDetail.GetReturnType()); MethodInfo method = typeof(DataWriter).GetMethod("WriteToTable", new Type[] { typeof(IList), typeof(string), typeof(object), typeof(string) }); MethodInfo generic = method.MakeGenericMethod(stepDetail.GetReturnType()); Object[] parameters = new Object[5]; IList list = (IList)results.GetType().GetProperty(stepDetail.nested_property_name).GetValue(results); if (list != null) { //var list = Convert.ChangeType(results[stepDetail.PropertyName], genericType); parameters = new object[] { list, stepDetail.db_table, authData.InjectionPropertyValue, authData.InjectionPropertyName }; generic.Invoke(null, parameters); } //DataWriter.WriteToTable(((List<dynamic>)results[stepDetail.PropertyName]).GetDataReader(), stepDetail.DbTable, // authData.InjectionPropertyValue, authData.InjectionPropertyName); } } } if (returnODataObject.Exception != null) { DataWriter.LogErpActionStep(actionId, step.StepName, startTime, false, returnODataObject.Exception.ErrorMessage, returnODataObject.Exception.StackTrace, step.Id); } else { DataWriter.LogErpActionStep(actionId, step.StepName, startTime, true, null, null, step.Id); } return(returnODataObject.Exception); } catch (Exception e) { DataWriter.LogErpActionStep(actionId, step.StepName, startTime, false, e.Message, e.StackTrace, step.Id); return(new AxBaseException { ApplicationException = e }); } }