public async Task <ExecutionResponse <BranchCreateLinkResponse> > CreateDeepLink(BranchIoDeepLinkParms deepLinkParms) { ExecutionResponse <BranchCreateLinkResponse> response = new ExecutionResponse <BranchCreateLinkResponse>(); try { string url = branchIoConfig.ApiUrl + "/v1/url"; deepLinkParms.branch_key = branchIoConfig.ApiKey; string serializedContent = JsonConvert.SerializeObject(deepLinkParms); HttpContent content = new StringContent(serializedContent, Encoding.UTF8, "application/json"); using (HttpResponseMessage sendResponse = await BaseService.Client.PostAsync(url, content)) { if (sendResponse.StatusCode != HttpStatusCode.OK) { var responseContent = JsonConvert.DeserializeObject(await sendResponse.Content.ReadAsStringAsync()); MessagesHelper.SetValidationMessages(response, "Error", responseContent.ToString(), lang: "en"); return(response); } var res = JsonConvert.DeserializeObject <BranchCreateLinkResponse>(await sendResponse.Content.ReadAsStringAsync()); response.Result = res; response.State = ResponseState.Success; } } catch (Exception ex) { MessagesHelper.SetException(response, ex); } return(response); }
public async Task <ExecutionResponse <bool> > SendNotification(SendNotificationDTO sendNotificationDTO) { ExecutionResponse <bool> response = new ExecutionResponse <bool>(); var androidConfig = new AndroidConfig(); androidConfig.Notification = new AndroidNotification(); Message message = new Message { Notification = new FcmSharp.Requests.Notification { Title = sendNotificationDTO.Title, Body = sendNotificationDTO.Body, }, AndroidConfig = androidConfig, Data = sendNotificationDTO.Data }; CancellationTokenSource cts = new CancellationTokenSource(); var tokens = sendNotificationDTO.UserTokens.Select(ut => ut.Token).ToArray(); var result = await fcmClient.SendMulticastMessage(tokens, message, false, cts.Token);//.GetAwaiter().GetResult(); // handle error response.State = ResponseState.Success; response.Result = true; return(response); }
static void Main(string[] args) { var serviceProvider = new ServiceCollection() .AddLogging(config => config.AddConsole().SetMinimumLevel(LogLevel.Debug)) .AddTaCqrs() .AddCommandHandler <AddCustomerCommandHandler, AddCustomerCommand>() .AddScoped <IContextDataProvider, ContextDataProvider>() .BuildServiceProvider(); Stopwatch stopwatch = Stopwatch.StartNew(); ILoggerFactory loggerFactory = serviceProvider.GetService <ILoggerFactory>(); ILogger logger = loggerFactory.CreateLogger <Program>(); ICommandInvoker commandInvoker = serviceProvider.GetService <ICommandInvoker>(); for (int i = 0; i < 10; i++) { ExecutionResponse executionResponse = commandInvoker.Invoke(new AddCustomerCommand() { Name = "Customer 1" }).Result; logger.LogDebug($"{executionResponse.AdditionalData.GetCreatedAt()}"); } stopwatch.Stop(); logger.LogDebug($"{stopwatch.Elapsed}"); logger.LogDebug("Completed!, Press any key to exit"); Console.WriteLine($"{stopwatch.Elapsed}"); Console.ReadKey(); }
public RemoteExecutionCompletedEventArgs(ExecutionRequest remotingRequest, ExecutionResponse response, ExecutionOptions options, float elapsedMilliseconds) { this.Request = remotingRequest; this.Response = response; this.Options = options; this.ElapsedMilliseconds = elapsedMilliseconds; }
public static async Task <ExecutionResponse <bool> > SendEmail(SendEmailModel model) { ExecutionResponse <bool> response = new ExecutionResponse <bool>(); try { var from = new EmailAddress(model.SenderEmail, ""); var to = new EmailAddress(model.DeptEmail, ""); var plainTextContent = model.Message; var htmlContent = model.htmlContent; var subject = model.Subject; var email = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent); var sendEmailAsyncRes = await sendGridClient.SendEmailAsync(email); if (sendEmailAsyncRes.StatusCode != HttpStatusCode.Accepted) { MessagesHelper.SetValidationMessages(response, "Email_Error", sendEmailAsyncRes.Body.ToString(), lang: "en"); return(response); } response.State = ResponseState.Success; response.Result = true; } catch (Exception ex) { MessagesHelper.SetException(response, ex); } return(response); }
public ExecutionResponse <CityDTO> Update(City city) { var res = new ExecutionResponse <CityDTO>(); try { unitOfWork.CreateTransaction(); var cityRes = cityRepository.Update(city); var cityDto = new CityDTO() { Id = cityRes.Id, Name = cityRes.Name }; unitOfWork.Save(); unitOfWork.Commit(); res.Result = cityDto; return(res); } catch (Exception ex) { res.Exception = ex; unitOfWork.Rollback(); return(res); } }
protected virtual async Task <IActionResult> CommandResult <T>(T command) where T : ICommand { ExecutionResponse commandResponse = await this.commandInvoker.Invoke(command); return(this.HandleCommandResponse(commandResponse)); }
public static void MapExecutionResponse <T>(ExecutionResponse <T> res, Exception ex, string message, ResponseState state, T result) { res.Result = result; res.State = state; res.Exception = ex; res.Message = message; }
public static void SetException <T>(ExecutionResponse <T> res, Exception ex, string lang = "ar") { SetDetailedMessages(res, "generalError", "an error occured", lang); res.State = ResponseState.Error; res.Exception = ex; res.Result = default(T); }
public async Task <List <ExecutionResponse> > WriteEntryAsync(EventEntry entry) { var result = new List <ExecutionResponse>(); ExecutionResponse response = null; foreach (var item in providers) { try { response = await item.WriteEntryAsync(entry); } catch (Exception ex) { response = GenerateResponseFromException(item, ex); response.Message = $"An error has occurred during log entry writing."; } if (response.IsSuccess == false) { result.Add(response); } } return(result); }
private bool HandleObjectMessage(string msg) { // ******************** // ADD OBJECT HANDLERS BELOW // ******************** return (ErrorResponse.TryHandle(msg, Streams.ErrorSubject) || SubscribeResponse.TryHandle(msg, Streams.SubscribeSubject) || BookResponse.TryHandle(msg, Streams.BookSubject) || TradeResponse.TryHandle(msg, Streams.TradesSubject) || QuoteResponse.TryHandle(msg, Streams.QuoteSubject) || LiquidationResponse.TryHandle(msg, Streams.LiquidationSubject) || PositionResponse.TryHandle(msg, Streams.PositionSubject) || MarginResponse.TryHandle(msg, Streams.MarginSubject) || OrderResponse.TryHandle(msg, Streams.OrderSubject) || WalletResponse.TryHandle(msg, Streams.WalletSubject) || ExecutionResponse.TryHandle(msg, Streams.ExecutionSubject) || FundingResponse.TryHandle(msg, Streams.FundingsSubject) || InstrumentResponse.TryHandle(msg, Streams.InstrumentSubject) || TradeBinResponse.TryHandle(msg, Streams.TradeBinSubject) || InfoResponse.TryHandle(msg, Streams.InfoSubject) || AuthenticationResponse.TryHandle(msg, Streams.AuthenticationSubject)); }
//public List<ExecutionResponse> RemoveBefore(string sourceName, DateTime expirationDate) //{ // List<ExecutionResponse> result = null; // Task.Run(async () => { result = await RemoveBeforeAsync(sourceName, expirationDate); }); // return result; //} public async Task <List <ExecutionResponse> > RemoveBeforeAsync(string sourceName, DateTime expirationDate) { var result = new List <ExecutionResponse>(); ExecutionResponse response = null; foreach (var item in providers) { try { response = await item.RemoveBeforeAsync(sourceName, expirationDate); } catch (Exception ex) { response = GenerateResponseFromException(item, ex); response.Message = $"An error has occurred during remove entryes."; } if (response.IsSuccess == false) { result.Add(response); } } return(result); }
protected virtual async Task <IActionResult> QueryResult <T>(T query) where T : IQuery { ExecutionResponse queryResponse = await this.queryInvoker.Invoke(query); return(this.HandleQueryResponse(queryResponse)); }
public async Task <ExecutionResponse <InfobipSendSmsResponse> > SendMessage(InfobipSmsModel model) { var response = new ExecutionResponse <InfobipSendSmsResponse>(); try { string url = infobipConfig.ApiUrl + "/sms/1/text"; string serializedContent = JsonConvert.SerializeObject(model); HttpContent content = new StringContent(serializedContent, Encoding.UTF8, "application/json"); BaseService.Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("App", infobipConfig.ApiToken); using (HttpResponseMessage sendResponse = await BaseService.Client.PostAsync(url, content)) { if (sendResponse.StatusCode != HttpStatusCode.OK) { var responseContent = JsonConvert.DeserializeObject(await sendResponse.Content.ReadAsStringAsync()); MessagesHelper.SetValidationMessages(response, "Error", responseContent.ToString(), lang: "en"); return(response); } var res = JsonConvert.DeserializeObject <InfobipSendSmsResponse>(await sendResponse.Content.ReadAsStringAsync()); response.Result = res; response.State = ResponseState.Success; } } catch (Exception ex) { MessagesHelper.SetException(response, ex); } return(response); }
/// <summary> /// Handles object messages sent by bitmex. /// </summary> /// <param name="msg">The MSG.</param> /// <param name="streams">The streams.</param> /// <returns></returns> public static bool HandleObjectMessage(string msg, BitmexClientStreams streams) { var response = BitmexJsonSerializer.Deserialize <JObject>(msg); // ******************** // ADD OBJECT HANDLERS BELOW // ******************** return (TradeResponse.TryHandle(response, streams.TradesSubject) || TradeBinResponse.TryHandle(response, streams.TradeBinSubject) || BookResponse.TryHandle(response, streams.BookSubject) || QuoteResponse.TryHandle(response, streams.QuoteSubject) || LiquidationResponse.TryHandle(response, streams.LiquidationSubject) || PositionResponse.TryHandle(response, streams.PositionSubject) || MarginResponse.TryHandle(response, streams.MarginSubject) || OrderResponse.TryHandle(response, streams.OrderSubject) || WalletResponse.TryHandle(response, streams.WalletSubject) || InstrumentResponse.TryHandle(response, streams.InstrumentSubject) || ExecutionResponse.TryHandle(response, streams.ExecutionSubject) || FundingResponse.TryHandle(response, streams.FundingsSubject) || ErrorResponse.TryHandle(response, streams.ErrorSubject) || SubscribeResponse.TryHandle(response, streams.SubscribeSubject) || InfoResponse.TryHandle(response, streams.InfoSubject) || AuthenticationResponse.TryHandle(response, streams.AuthenticationSubject)); }
public async Task <ExecutionResponse <OneSignalAddDeviceResponse> > AddDevice(OneSignalDeviceModel device) { ExecutionResponse <OneSignalAddDeviceResponse> response = new ExecutionResponse <OneSignalAddDeviceResponse>(); try { var json_data = JsonConvert.SerializeObject(device); string url = oneSignalConfig.ApiUrl; string serializedContent = JsonConvert.SerializeObject(json_data); HttpContent content = new StringContent(serializedContent, Encoding.UTF8, "application/json"); using (HttpResponseMessage sendResponse = await BaseService.Client.PostAsync(url, content)) { if (sendResponse.StatusCode != HttpStatusCode.OK) { var responseContent = JsonConvert.DeserializeObject(await sendResponse.Content.ReadAsStringAsync()); MessagesHelper.SetValidationMessages(response, "Error", responseContent.ToString(), lang: "en"); return(response); } var res = JsonConvert.DeserializeObject <OneSignalAddDeviceResponse>(await sendResponse.Content.ReadAsStringAsync()); response.Result = res; response.State = ResponseState.Success; } } catch (Exception ex) { MessagesHelper.SetException(response, ex); } return(response); }
void Start() { //Forced screen rotation to prevent landscape modes Screen.autorotateToPortrait = true; Screen.autorotateToPortraitUpsideDown = true; Screen.autorotateToLandscapeLeft = true; Screen.autorotateToLandscapeRight = true; Screen.orientation = ScreenOrientation.AutoRotation; string argorithmID = PlayerPrefs.GetString("argorithmID"); ARgorithmHeading.GetComponent <TextMeshProUGUI>().SetText(argorithmID); index = -1; placementIndicator.SetActive(false); ARRayCastManager = FindObjectOfType <ARRaycastManager>(); idToPlaceholderMap = new Dictionary <string, GameObject>(); string rawData = PlayerPrefs.GetString("StateSet"); ExecutionResponse response = JsonConvert.DeserializeObject <ExecutionResponse>(rawData); Debug.Log(response.data); stageData = response.convertStageData(); State state = stageData.states[0]; string funcType = state.state_type.Split('_').ToList()[1]; if (funcType == "declare") { placed = false; } }
public static void SetDetailedMessages <T>(ExecutionResponse <T> res, string messageCode, string message, string MetaPlus = "", string lang = "ar") { LocalizeMessage(ref messageCode, ref message, lang); var _MetaPair = GetDetailedMessages(messageCode, message, MetaPlus); res.MessageCode = messageCode; res.Message = _MetaPair[0].Meta + " '" + MetaPlus + "'"; }
private ExecutionResponse GenerateResponseFromException(IProvider provider, Exception ex) { var result = new ExecutionResponse(false) { Source = $"Provider {provider.ID} ({provider.Type.ToString()})", Content = ex.Message }; return(result); }
public IEnumerator run(ExecutionRequest exec, System.Action <ExecutionResponse> callback) { /* * Sends execution request to server and gets the states generated on executing * ARgorithm to given parameters * * The ExecutionResponse returned can have the following status: * - FAILURE: Something went wrong, empty states * - run_example: The states are generated on default parameters * - run_parameters: The states are generated on given parameters */ string body = JsonConvert.SerializeObject(exec); using (UnityWebRequest webRequest = new UnityWebRequest(serverEndpoint + "/argorithms/run", "POST")){ byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(body); webRequest.uploadHandler = (UploadHandler) new UploadHandlerRaw(jsonToSend); webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); webRequest.SetRequestHeader("authorization", "Bearer " + token); webRequest.SetRequestHeader("Content-Type", "application/json"); yield return(webRequest.SendWebRequest()); if (webRequest.isNetworkError) { callback(new ExecutionResponse { status = "FAILURE", data = {} }); } if (webRequest.isDone) { switch (webRequest.responseCode) { case 200: ExecutionResponse res = JsonConvert.DeserializeObject <ExecutionResponse>(webRequest.downloadHandler.text); callback(res); break; default: callback(new ExecutionResponse { status = "FAILURE", data = {} }); break; } } } }
void callback(ExecutionResponse response, string argorithmID) { /* * After the states are recieved, this function is invoked * * This function should send the states to the ARgorithm Parser which in turn send to ARStage */ string data = JsonConvert.SerializeObject(response); PlayerPrefs.SetString("StateSet", data); //PlayerPrefs.SetString("argorithmID", argorithmID); int currentSceneIndex = SceneManager.GetActiveScene().buildIndex; SceneManager.LoadScene(currentSceneIndex + 1); //Debug.Log(PlayerPrefs.GetString("StateSet")); }
/// <summary> /// Convert <see cref="ExecutionResponse"/> object to <see cref="IActionResult"/>. /// </summary> /// <param name="executionResponse">ExecutionResponse object to convert to IActionResult.</param> /// <returns><see cref="NotFoundResult"/> if object is null or converts to <see cref="ObjectResult"/> using /// .GetContent and ActionOutcomeCode.StatusCode</returns> public static IActionResult ConvertToActionResult(this ExecutionResponse executionResponse) { if (executionResponse == null) { return(new NotFoundResult()); } var statusCode = executionResponse.ActionOutcomeCode.StatusCode; if (StatusWithNoResponseBody.Contains(statusCode)) { return(new StatusCodeResult(statusCode)); } return(new ObjectResult(executionResponse.GetContent) { StatusCode = statusCode }); }
public async Task QueryResult_ReturnsStatusCodeOnly_IfStatusCodeHasNoBody(int statusCode) { // Arrange var command = new TestQuery(); var actionOutcome = new ActionOutcome("foobar", statusCode, true); var executionResponse = ExecutionResponse.Create("the result", actionOutcome, null); var invoker = A.Fake <IQueryInvoker>(); A.CallTo(() => invoker.Invoke(command, null)) .Returns(executionResponse); var controller = new TestQueryController(invoker); // Act var result = await controller.CallQuery(command); // Assert result.Should().BeOfType <StatusCodeResult>().Which.StatusCode.Should().Be(statusCode); }
public async Task QueryResult_ReturnsStatusCodeAndContent() { // Arrange var command = new TestQuery(); var executionResponse = ExecutionResponse.Create("the result", ActionOutcome.Conflict, null); var invoker = A.Fake <IQueryInvoker>(); A.CallTo(() => invoker.Invoke(command, null)) .Returns(executionResponse); var controller = new TestQueryController(invoker); // Act var result = (ObjectResult)await controller.CallQuery(command); // Assert result.StatusCode.Should().Be(409); result.Value.Should().Be("the result"); }
public ExecutionResponse Execute() { var result = new ExecutionResponse(true); try { StepAction(); Schedule.Update(); } catch (Exception ex) { result.IsSuccess = false; result.Message = "An error has occured."; result.Content = ex.Message; } ReportStatus?.Invoke(result); return(result); }
public static void SetDetailMessageOfFluentValidation <T>(ExecutionResponse <T> res, ValidationResult validationResult, string lang = "ar") { var metaPairList = new List <MetaPair>(); foreach (ValidationFailure validationFailure in validationResult.Errors) { string messageCode = validationFailure.ErrorCode; string message = GetTranslation(messageCode, lang); metaPairList.Add(new MetaPair() { Property = messageCode, Meta = message, MetaPlus = "" }); res.MessageCode = messageCode; } res.DetailedMessages = metaPairList; }
protected ExecutionResponse CheckFolder(string folderPath) { ExecutionResponse result = new ExecutionResponse(false, "Não foi possível criar a pasta."); try { if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } result = new ExecutionResponse(true); } catch (UnauthorizedAccessException ex) { result.Content = ex.Message; } catch (ArgumentNullException ex) { result.Content = ex.Message; } catch (PathTooLongException ex) { result.Content = ex.Message; } catch (DirectoryNotFoundException ex) { result.Content = ex.Message; } catch (IOException ex) { result.Content = ex.Message; } catch (Exception ex) { result.Content = ex.Message; } return(result); }
protected ExecutionResponse CheckFile(string completePath) { ExecutionResponse result = new ExecutionResponse(false, "Não foi possível criar o arquivo."); try { if (!File.Exists(completePath)) { File.Create(completePath); } result = new ExecutionResponse(true); } catch (UnauthorizedAccessException ex) { result.Content = ex.Message; } catch (ArgumentNullException ex) { result.Content = ex.Message; } catch (PathTooLongException ex) { result.Content = ex.Message; } catch (DirectoryNotFoundException ex) { result.Content = ex.Message; } catch (IOException ex) { result.Content = ex.Message; } catch (Exception ex) { result.Content = ex.Message; } return(result); }
protected async Task <ExecutionResponse> WriteFileOperationAsync(Func <ExecutionResponse> action) { ExecutionResponse result = new ExecutionResponse(false, "Não foi escrever no arquivo."); try { await Task.Run(() => { result = action?.Invoke(); }); } catch (UnauthorizedAccessException ex) { result.Content = ex.Message; } catch (ArgumentNullException ex) { result.Content = ex.Message; } catch (PathTooLongException ex) { result.Content = ex.Message; } catch (DirectoryNotFoundException ex) { result.Content = ex.Message; } catch (IOException ex) { result.Content = ex.Message; } catch (Exception ex) { result.Content = ex.Message; } return(result); }
public ExecutionResponse <bool> Delete(int id) { var res = new ExecutionResponse <bool>(); try { unitOfWork.CreateTransaction(); var city = cityRepository.GetByID(id); cityRepository.Delete(city); unitOfWork.Save(); unitOfWork.Commit(); res.Result = true; return(res); } catch (Exception ex) { unitOfWork.Rollback(); res.Exception = ex; res.Result = false; return(res); } }
internal static HandleRef getCPtr(ExecutionResponse obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; }