/// <summary> /// Perform the Create operations on the selected table. /// This method will filter creations using the /// SqlQueryBuilder and the lookup conditions /// </summary> /// <param name="operationInput">The operation information being executed.</param> /// <returns>The result of the operation that was processed.</returns> public OperationResult CreateOperation(OperationInput operationInput) { OperationResult operationResult = new OperationResult(); // Use LogMethodExecution to add entry and exit tracing to a method. // When wrapped in a using statement, the exit point // is written during garbage collection. using (new LogMethodExecution(Globals.ConnectorName, "Create")) { // Each record processed must return the following 3 pieces of information. // Each piece of information should be added in the same order it was received. // The first piece of information would be whether or not the request was successful. // If the requested record that has a key that already exists this should not result in a failure. List<bool> successList = new List<bool>(); // The second piece of information is the number of records that have been processed. // If a duplicate key is detected when performing an insert then 0 rows should be added for the request. List<int> objectList = new List<int>(); // In the event of an error during processing the record, error information should be added here. // If no error occured a null placeholder for that record is expected. List<ErrorResult> errors = new List<ErrorResult>(); //Execute each of the inputs individually // **** Processing inputs individually is done because the // connector is responsible for error handling on each. // The connector must return results in the same order in which the // data entities were received, this allows for reprocessing of failed records. //Note: If the SupportsBulk flag is not set in the ActionDefinition // that corresponds to this operation, operationInput.Input // will always have always have a length of 1. foreach (DataEntity inputEntity in operationInput.Input) { try { //Use the query builder to parse input conditions SqlQueryBuilder queryBuilder = new SqlQueryBuilder( inputEntity, Globals.QueryType.Insert); //execute the create query int rowsEffected = _dataAccess.ExecuteNonQuery(queryBuilder.ToString()); //Add the result of the create to the result lists successList.Add(SetSuccessResult(operationInput.AllowMultipleObject, rowsEffected)); objectList.Add(rowsEffected); errors.Add(SetErrorResult(rowsEffected)); } catch (OleDbException oleDbException) { //Create a new error result for ole db specific exeptions ErrorResult errorResult = new ErrorResult(); var oleDbError = oleDbException.ErrorCode; //Look for a specific error code that occurs when attempting to duplicate a record. //This will tell ScribeOnline that an update is required rather than an Insert. if (oleDbError == -2147217873) { //this is the error code for a 'Violation in unique index' errorResult.Number = ErrorNumber.DuplicateUniqueKey; if (oleDbException.Errors[0] != null && oleDbException.Errors[0] != null) { var dbError = oleDbException.Errors[0]; errorResult.Description = dbError != null ? dbError.Message : oleDbException.Message; var error = oleDbException.Errors[1]; errorResult.Detail = error != null ? error.Message : oleDbException.StackTrace; } } else { errorResult.Description = oleDbException.Message; errorResult.Detail = oleDbException.StackTrace; errorResult.Number = oleDbError; } successList.Add(false); objectList.Add(0); errors.Add(errorResult); } catch (Exception exception) { //In the event of an exception do not stop performing //all operations simply log each individually. successList.Add(false); objectList.Add(0); errors.Add(new ErrorResult() { Description = exception.Message, Detail = exception.ToString() }); } } //Add the results from the operations to the operation result object operationResult.Success = successList.ToArray(); operationResult.ObjectsAffected = objectList.ToArray(); operationResult.ErrorInfo = errors.ToArray(); } return operationResult; }
public BulkImportResults Import(List<SubscriberDetail> subscribers, bool resubscribe) { List<object> reworkedSusbcribers = new List<object>(); string json = ""; foreach (SubscriberDetail subscriber in subscribers) { Dictionary<string, object> subscriberWithoutDate = new Dictionary<string, object>() { { "EmailAddress", subscriber.EmailAddress }, { "Name", subscriber.Name }, { "CustomFields", subscriber.CustomFields } }; reworkedSusbcribers.Add(subscriberWithoutDate); } try { json = HttpHelper.Post(string.Format("/subscribers/{0}/import.json", ListID), null, JavaScriptConvert.SerializeObject( new Dictionary<string, object>() { { "Subscribers", reworkedSusbcribers }, { "Resubscribe", resubscribe } } )); } catch (CreatesendException ex) { if (!ex.Data.Contains("ErrorResult") && ex.Data.Contains("ErrorResponse")) { ErrorResult<BulkImportResults> result = JavaScriptConvert.DeserializeObject<ErrorResult<BulkImportResults>>(ex.Data["ErrorResponse"].ToString()); ex.Data.Add("ErrorResult", result); } else if(ex.Data.Contains("ErrorResult")) { ErrorResult<BulkImportResults> result = new ErrorResult<BulkImportResults>((ErrorResult)ex.Data["ErrorResult"]); ex.Data["ErrorResult"] = result; } throw ex; } return JavaScriptConvert.DeserializeObject<BulkImportResults>(json); }
public ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string alternateButton1Label, ErrorResult resultIfAlternateButtonPressed, string message) { if (!policy.ShouldShowMessage(message)) { return ErrorResult.OK; } if (ErrorReport.IsOkToInteractWithUser) { var dlg = new ProblemNotificationDialog(message, UsageReporter.AppNameToUseInDialogs + " Problem") { ReoccurenceMessage = policy.ReoccurenceMessage }; if (!string.IsNullOrEmpty(alternateButton1Label)) { dlg.EnableAlternateButton1(alternateButton1Label, GetDialogResultForErrorResult(resultIfAlternateButtonPressed)); } return GetErrorResultForDialogResult(dlg.ShowDialog()); } else { throw new ErrorReport.ProblemNotificationSentToUserException(message); } }
public DefaultErrorEntry(ErrorResult value) : base(null) { Title = "Unknown Issue Occurred"; Summary = "This entry gets returned if there is no entry in the error map for an issue"; AddLine(value == null ? new DirectTextContent {BaseText = "[unknown issue]"} : new DirectTextContent {BaseText = value.GetType().ToString()}); }
public void ExecuteSearch_InvalidArgument_ThrowsException() { // Arrange var mocks = new MockRepository(); var host = mocks.DynamicMock<IHost>(); var expectedResult = new ErrorResult("test"); host.Expect(h => h.Execute(null)).IgnoreArguments().Return(expectedResult); var searchEngine = new SearchEngine(host); var searchTerms = new Dictionary<string, string>(); mocks.ReplayAll(); // Act, Assert Assert.Throws<Exception>(() => searchEngine.ExecuteSearch(searchTerms), "test"); mocks.VerifyAll(); }
public AbstractErrorEntry GetErrorEntry(ErrorResult issue) { try { if (issue == null) return null; var key = issue.GetType().ToString().Replace("Org.InCommon.InCert.Engine.Results.", ""); return !_errorMap.ContainsKey(key) ? new DefaultErrorEntry(issue) : _errorMap[key]; } catch (Exception e) { Log.Warn(e); return new DefaultErrorEntry(issue); } }
public ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string alternateButton1Label, ErrorResult resultIfAlternateButtonPressed, string message) { if (!policy.ShouldShowMessage(message)) { return ErrorResult.OK; } if (ErrorReport.IsOkToInteractWithUser) { Console.WriteLine(message); Console.WriteLine(policy.ReoccurenceMessage); return ErrorResult.OK; } throw new ErrorReport.ProblemNotificationSentToUserException(message); }
public ActionResult <CommonResponeModel> Create(RecruitmentPlanCreateRequestModel model) { var validator = new RecruitmentPlanCreateValidator(categoryRepository); var databaseObject = model.MapTo <RecruitmentPlan>(); //empty code if (string.IsNullOrEmpty(databaseObject.Code)) { var code = entityCenterRepository.GetCodeByEntity(nameof(RecruitmentPlan)); if (string.IsNullOrEmpty(code)) { Result = new ErrorResult(ActionType.Insert, AppGlobal.MakeCodeError); Data = model; return(GetCommonRespone()); } databaseObject.Code = code; } //check exist in db if (recruitmentPlanRepository.IsExistCode(databaseObject.Code)) { Result = new ErrorResult(ActionType.Insert, AppGlobal.ExistCodeError); return(GetCommonRespone()); } databaseObject.InitBeforeSave(RequestUsername, InitType.Create); int result = recruitmentPlanRepository.Insert(databaseObject); if (result > 0) { Result = new SuccessResultFactory().Factory(ActionType.Insert); Data = databaseObject; } else { Result = new ErrorResultFactory().Factory(ActionType.Insert); Data = databaseObject; } return(GetCommonRespone()); }
protected async Task <TResult> PerformOperationAsync <TResult>(OperationContext context, Func <SessionContext, Task <TResult> > operation, Func <string>?startMessageFactory = null, [CallerMemberName] string?caller = null) where TResult : ResultBase { var stopwatch = StopwatchSlim.Start(); TraceStartIfEnabled(context, caller !, startMessageFactory); try { var result = await performOperationCoreAsync(); TraceStopIfEnabled(context, result, stopwatch.Elapsed, caller !); return(result); } catch (Exception e) { // This can be only ClientCanRetryException. // Still tracing it explicitly. var error = new ErrorResult(e).AsResult <TResult>(); TraceStopIfEnabled(context, error, stopwatch.Elapsed, caller !); throw; } async Task <TResult> performOperationCoreAsync() { var sessionContext = await CreateSessionContextAsync(context, context.Token); if (!sessionContext) { return(new ErrorResult(sessionContext).AsResult <TResult>()); } try { return(await operation(sessionContext.Value)); } catch (ResultPropagationException error) { return(new ErrorResult(error).AsResult <TResult>()); } catch (Exception e) when(!(e is ClientCanRetryException)) { return(new ErrorResult(e).AsResult <TResult>()); } } }
public ActionResult <CommonResponeModel> SaveChange(CheckInOutDeviceSaveChangeRequestModel model) { var databaseObject = model.MapTo <CheckInOutDevice>(); int result = 0; if (model.Id > 0) { result = checkInOutDeviceRepository.Update(databaseObject); } else { //empty code if (string.IsNullOrEmpty(databaseObject.Code)) { var code = entityCenterRepository.GetCodeByEntity(nameof(CheckInOutDevice)); if (string.IsNullOrEmpty(code)) { Result = new ErrorResult(ActionType.Insert, AppGlobal.MakeCodeError); return(GetCommonRespone()); } databaseObject.Code = code; } //check exist in db if (checkInOutDeviceRepository.IsExistCode(databaseObject.Code)) { Result = new ErrorResult(ActionType.Insert, AppGlobal.ExistCodeError); return(GetCommonRespone()); } result = checkInOutDeviceRepository.Insert(databaseObject); } if (result > 0) { Result = new SuccessResult(ActionType.Edit, AppGlobal.SaveChangeSuccess); } else { Result = new ErrorResult(ActionType.Edit, AppGlobal.SaveChangeFalse); } return(GetCommonRespone()); }
public async Task <Result <object> > Remove(IdModel item, bool instantCommit = true) { try { var entity = _routeRepository.GetSingle(item.Id); if (entity != null) { if (await CheckUsersPermission(entity)) { if (await _userResolver.IsConfirmed()) { _routeRepository.Delete(entity); if (instantCommit) { await _routeRepository.Commit(); } return(new Result <object>()); } else { ErrorResult error = GenerateError("User is not confirmed", "", "", ErrorStatus.Forbidden); return(new Result <object>(error)); } } else { ErrorResult error = GenerateError("Action forbidden", "", "", ErrorStatus.Forbidden); return(new Result <object>(error)); } } else { ErrorResult error = GenerateError("Route not found", "Id", "Invalid identifier", ErrorStatus.ObjectNotFound); return(new Result <object>(error)); } } catch (Exception ex) { ErrorResult error = GenerateError(ex); return(new Result <object>(error)); } }
public async Task <IActionResult> Post([FromBody] Dictionary <string, string> tags) { var tag = tags.FirstOrDefault(); if (tag.Key is null) { return(ErrorResult .BadRequest() .ActionResult()); } var teamCloudInstance = await teamCloudRepository .GetAsync() .ConfigureAwait(false); if (teamCloudInstance is null) { return(ErrorResult .NotFound($"No TeamCloud Instance was found.") .ActionResult()); } if (teamCloudInstance.Tags.ContainsKey(tag.Key)) { return(ErrorResult .Conflict($"A Tag with the key '{tag.Key}' already exists on this TeamCloud Instance. Please try your request again with a unique key or call PUT to update the existing Tag.") .ActionResult()); } // TODO: return(new OkResult()); // var command = new ProjectUserCreateCommand(CurrentUser, newUser, ProjectId.Value); // var commandResult = await orchestrator // .InvokeAsync(command) // .ConfigureAwait(false); // if (commandResult.Links.TryGetValue("status", out var statusUrl)) // return StatusResult // .Accepted(commandResult.CommandId.ToString(), statusUrl, commandResult.RuntimeStatus.ToString(), commandResult.CustomStatus) // .ActionResult(); throw new Exception("This shoudn't happen, but we need to decide to do when it does."); }
private async Task <IActionResult> EnsureCurrentUserInternalAsync(Func <UserDocument, Task <IActionResult> > asyncCallback = null, Func <UserDocument, IActionResult> callback = null) { try { if (asyncCallback is null && callback is null) { throw new InvalidOperationException("asyncCallback or callback must have a value"); } if (!(asyncCallback is null || callback is null)) { throw new InvalidOperationException("Only one of asyncCallback or callback can hava a value"); } var user = await UserService .CurrentUserAsync() .ConfigureAwait(false); if (user is null) { return(ErrorResult .NotFound($"A User matching the current authenticated user was not found..") .ToActionResult()); } if (!(callback is null)) { return(callback(user)); } if (!(asyncCallback is null)) { return(await asyncCallback(user) .ConfigureAwait(false)); } throw new InvalidOperationException("asyncCallback or callback must have a value"); } catch (Exception exc) { return(ErrorResult .ServerError(exc) .ToActionResult()); } }
public IActionResult UpdateManagerHistoryIpfsHash([FromBody] ManagerHistoryIpfsHash data) { var errors = brokerValidator.ValidateUpdateManagerHistoryIpfsHash(CurrentUser, data); if (errors.Any()) { return(BadRequest(ErrorResult.GetResult(errors, ErrorCodes.ValidationError))); } var result = trustManagementService.UpdateManagerHistoryIpfsHash(data); if (!result.IsSuccess) { return(BadRequest(ErrorResult.GetResult(result))); } return(Ok()); }
public IActionResult ProcessInvestmentRequests(Guid investmentProgramId) { var errors = brokerValidator.ValidateProcessInvestmentRequests(CurrentUser, investmentProgramId); if (errors.Any()) { return(BadRequest(ErrorResult.GetResult(errors, ErrorCodes.ValidationError))); } var result = trustManagementService.ProcessInvestmentRequests(investmentProgramId); if (!result.IsSuccess) { return(BadRequest(ErrorResult.GetResult(result))); } return(Ok(result.Data)); }
public ErrorResult ImportTestWorkspace(string sourceDirectory) { ErrorResult errorResult = new ErrorResult(); string workspacesPath = GetWorkspacesPath(); int startIndexOfDirectoryName = sourceDirectory.LastIndexOf('\\'); string directoryName = sourceDirectory.Substring(startIndexOfDirectoryName + 1); if (Directory.Exists(workspacesPath + directoryName)) { errorResult.errorCode = ErrorCode.DupicateWorkspaceName; return(errorResult); } Directory.CreateDirectory(workspacesPath + directoryName); UtilityClass.CopyDirectory(sourceDirectory + "\\", workspacesPath + directoryName + "\\"); testWorkspaceAddRemoveListener.TestWorkspaceAdded(LoadTestWorkspace(directoryName)); errorResult.errorCode = ErrorCode.Success; return(errorResult); }
public IActionResult CreateManagerAccount([FromBody] NewManager request) { var errors = brokerValidator.ValidateCreateManagerAccount(CurrentUser, request); if (errors.Any()) { return(BadRequest(ErrorResult.GetResult(errors, ErrorCodes.ValidationError))); } var result = trustManagementService.CreateInvestmentProgram(request); if (!result.IsSuccess) { return(BadRequest(ErrorResult.GetResult(result))); } return(Ok(result.Data)); }
public async Task <IResult> Delete(TEntity entity) { IResult result; try { await _baseDal.Delete(entity); result = new SuccessResult("Deleting was succesed"); _identityId = _baseDal.SCOPE_IDENTY_ID; } catch (Exception ex) { result = new ErrorResult(ex.Message); } return(result); }
public IActionResult AccrueProfits([FromBody] InvestmentProgramAccrual accrual) { var errors = brokerValidator.ValidateAccrueProfits(CurrentUser, accrual); if (errors.Any()) { return(BadRequest(ErrorResult.GetResult(errors, ErrorCodes.ValidationError))); } var result = trustManagementService.AccrueProfits(accrual); if (!result.IsSuccess) { return(BadRequest(ErrorResult.GetResult(result))); } return(Ok()); }
public ActionResult <CommonResponeModel> Create(RoleCreateRequestModel model) { var databaseObject = model.MapTo <UserRole>(); databaseObject.InitBeforeSave(RequestUsername, InitType.Create); int result = roleRepository.Insert(databaseObject); if (result > 0) { Result = new SuccessResult(ActionType.Insert, AppGlobal.CreateSucess); } else { Result = new ErrorResult(ActionType.Insert, AppGlobal.CreateError); } return(GetCommonRespone()); }
public virtual async Task <IActionResult> Post([FromBody] ProductModel model) { if (!ModelState.IsValid) { var errorResult = new ErrorResult(ErrorMessage.ModelStateInvalid); return(BadRequest(errorResult)); } var product = model.ToEntity <Product>(); var _productService = EngineContext.Current.Resolve <IProductService>(); await _productService.InsertAsync(product); var result = new SuccessResult(SuccessMessage.ProductInserted); return(Ok(result)); }
public IActionResult ReevaluateManagerToken(Guid investmentProgramId, decimal investorLossShare) { if (!ModelState.IsValid) { return(BadRequest(ErrorResult.GetResult(ModelState))); } var errors = brokerValidator.ValidateReevaluateManagerToken(CurrentUser, investmentProgramId); if (errors.Any()) { return(BadRequest(ErrorResult.GetResult(errors, ErrorCodes.ValidationError))); } trustManagementService.ReevaluateManagerToken(investmentProgramId, investorLossShare); return(Ok()); }
public ActionResult <CommonResponeModel> GetItemsByEmployeeCode(string employeeCode) { if (string.IsNullOrEmpty(employeeCode)) { Result = new ErrorResult(ActionType.Select, AppGlobal.Error); } else { var result = this._employeeDayOffRepository.GetItemsByEmployeeCode(employeeCode); Data = result; Result = new SuccessResultFactory().Factory(ActionType.Select); } return(GetCommonRespone()); }
public async Task <IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return(BadRequest(ErrorResult.GetResult("Empty userId/code"))); } var user = await userManager.FindByIdAsync(userId); var result = await userManager.ConfirmEmailAsync(user, code); if (result.Succeeded) { return(BadRequest(ErrorResult.GetResult(result))); } return(Ok()); }
protected async Task <T> RunOperationAndConvertExceptionToErrorAsync <T>(Func <Task <T> > operation) where T : ResultBase { try { return(await WithOptionalTimeoutAsync(operation(), _timeout)); } catch (Exception ex) { var result = new ErrorResult(ex).AsResult <T>(); if (_context.Token.IsCancellationRequested && ResultBase.NonCriticalForCancellation(ex)) { result.IsCancelled = true; } return(result); } }
public IActionResult NewOpenTrades([FromBody] NewOpenTradesEvent trades) { if (!ModelState.IsValid) { return(BadRequest(ErrorResult.GetResult(ModelState))); } var errors = brokerValidator.ValidateNewOpenTrades(CurrentUser, trades); if (errors.Any()) { return(BadRequest(ErrorResult.GetResult(errors, ErrorCodes.ValidationError))); } tradesService.SaveNewOpenTrade(trades); return(Ok()); }
public IResult Get(IRequest request) { if (request.Url.Path.ToLower() != request.Url.Path) { return(new PlainTextResult("Asset paths must be lowercase", HttpStatusCode.BadRequest)); } var path = '~' + request.Url.Path; if (this.fileSystem.Exists(path)) { var fileStream = this.fileSystem.Open(path, FileMode.Open); var contentType = MimeMapping.GetMimeMapping(request.Url.Path); return(new FileStreamResult(contentType, fileStream)); } return(ErrorResult.NotFound()); }
public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (DomainException ex) { context.Response.StatusCode = 400; var result = new ErrorResult { Result = ex.Message }; var json = JsonConvert.SerializeObject(result); await context.Response.WriteAsync(json); } }
/// <summary> /// Creates an AS4 error referencing a given <paramref name="userMessage"/>. /// </summary> /// <param name="errorMessageId">The ebMS message identifier of this message unit.</param> /// <param name="userMessage">The AS4 user message to reference in the to be created error.</param> /// <param name="occurredError">The error that has happened during the step execution.</param> /// <param name="userMessageSendViaMultiHop"> /// Whether or not the user message was send in a multi-hop fashion or not. /// Setting this on <c>true</c> will result in an error with the referencing user message included in a RoutingInput element. /// </param> public static Error CreateFor( string errorMessageId, UserMessage userMessage, ErrorResult occurredError, bool userMessageSendViaMultiHop = false) { if (userMessageSendViaMultiHop) { var routedUserMessage = UserMessageMap.ConvertToRouting(userMessage); return(occurredError == null ? new Error(errorMessageId, userMessage?.MessageId, DateTimeOffset.Now, new ErrorLine[0], routedUserMessage) : new Error(errorMessageId, userMessage?.MessageId, DateTimeOffset.Now, new [] { ErrorLine.FromErrorResult(occurredError) }, routedUserMessage)); } return(occurredError == null ? new Error(errorMessageId, userMessage?.MessageId) : new Error(errorMessageId, userMessage?.MessageId, ErrorLine.FromErrorResult(occurredError))); }
public IActionResult CancelInvestmentRequest(Guid requestId) { var errors = investorValidator.ValidateCancelInvestmentRequest(CurrentUser, requestId); if (errors.Any()) { return(BadRequest(ErrorResult.GetResult(errors, ErrorCodes.ValidationError))); } var res = trustManagementService.CancelInvestmentRequest(requestId); if (!res.IsSuccess) { return(BadRequest(ErrorResult.GetResult(res.Errors))); } return(Ok()); }
private async Task <T> RunOperationAndConvertExceptionToErrorAsync <T>(Func <Task <T> > operation) where T : ResultBase { try { return(await operation()); } catch (Exception ex) { var result = new ErrorResult(ex).AsResult <T>(); if (Token.IsCancellationRequested && ResultBase.NonCriticalForCancellation(ex)) { result.IsCancelled = true; } return(result); } }
public IActionResult ProcessClosingProgram(Guid investmentProgramId, decimal managerBalance) { if (!ModelState.IsValid) { return(BadRequest(ErrorResult.GetResult(ModelState))); } var errors = brokerValidator.ValidateProcessClosingProgram(CurrentUser, investmentProgramId); if (errors.Any()) { return(BadRequest(ErrorResult.GetResult(errors, ErrorCodes.ValidationError))); } trustManagementService.ProcessClosingProgram(investmentProgramId, managerBalance); return(Ok()); }
Exception IErrorToExceptionConverter.ConvertTimeSeriesErrorToException(ErrorResult error) { switch (error.Code) { case ("AuthenticationFailed"): if (error.InnerError?.Code == "TokenExpired") { return(new TokenExpiredException(error.InnerError.Message)); } return(GenerateUnexpectedException(error)); case ("InvalidInput"): return(GetInvalidInputException(error)); default: return(GenerateUnexpectedException(error)); } }
public void ValidateAsResult() { var resultBaseType = typeof(ResultBase); IEnumerable <Type> resultTypes = AppDomain.CurrentDomain.GetAssemblies() .Where(assembly => assembly.FullName.Contains("BuildXL")) .SelectMany(assembly => assembly.GetTypes()) .Where(t => resultBaseType.IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract && !t.IsGenericType && t.FullName != resultBaseType.FullName && t.Name != "CustomError"); var testError = new ErrorResult(new Exception(nameof(ValidateAsResult))); foreach (Type resultType in resultTypes) { MethodInfo asResultMethod = typeof(ErrorResult).GetMethod(nameof(ErrorResult.AsResult)).MakeGenericMethod(new Type[] { resultType }); // testError.AsResult<resultType>(); asResultMethod.Invoke(testError, null); } }
public void OnActionExecuting(ActionExecutingContext context) { if (context.ModelState.IsValid) { return; } var errors = context .ModelState .Values .SelectMany(x => x.Errors.Select(e => e.ErrorMessage)) .ToList(); var result = ErrorResult .Create("00009", "Validation Errors", errors); context.Result = new BadRequestObjectResult(result); }
protected T RunOperationAndConvertExceptionToError <T>(Func <T> operation) where T : ResultBase { try { return(operation()); } catch (Exception ex) { var result = new ErrorResult(ex).AsResult <T>(); if (_context.Token.IsCancellationRequested && ResultBase.NonCriticalForCancellation(ex)) { result.IsCancelled = true; } return(result); } }
public ActionResult <CommonResponeModel> Update(RoleGroupDetailUpdateRequestModel model) { var databaseObject = model.MapTo <RoleGroupDetail>(); databaseObject.InitBeforeSave(RequestUsername, InitType.Create); int result = roleGroupDetailRepository.Update(databaseObject); if (result > 0) { Result = new SuccessResult(ActionType.Edit, AppGlobal.EditSuccess); } else { Result = new ErrorResult(ActionType.Edit, AppGlobal.EditError); } return(GetCommonRespone()); }
public RestApiException(int httpCode, string message, int errorCode) : base(httpCode, message) { ErrorResult = new ErrorResult { Code = errorCode, Desc = message }; }
/// <summary> /// Perform the Create operations on the selected table. /// This method will filter creations using the /// SqlQueryBuilder and the lookup conditions /// </summary> /// <param name="operationInput"></param> /// <returns></returns> public OperationResult CreateOperation(OperationInput operationInput) { OperationResult operationResult = new OperationResult(); // Use LogMethodExecution to add entry and exit tracing to a method. // When wrapped in a using statement, the exit point // is written during garbage collection. using (new LogMethodExecution(Globals.ConnectorName, "Create")) { List<bool> successList = new List<bool>(); List<int> objectList = new List<int>(); List<ErrorResult> errors = new List<ErrorResult>(); int index = 0; //Execute each of the inputs individually foreach (DataEntity inputEntity in operationInput.Input) { try { //Use the query builder to parse input conditions SqlQueryBuilder queryBuilder = new SqlQueryBuilder( inputEntity, null, Globals.OperationType.Create); //execute the create query int rowsEffected = _dataAccess.ExecuteNonQuery(queryBuilder.ToString()); //Add the result of the create to the result lists successList.Add(rowsEffected == 1); objectList.Add(rowsEffected); errors.Add(SetErrorResult(rowsEffected)); index++; } catch (OleDbException oleDbException) { //Create a new error result for ole db specific exeptions ErrorResult errorResult = new ErrorResult { Description = oleDbException.Message, Detail = oleDbException.StackTrace }; var oleDbError = oleDbException.ErrorCode; //Look for a specific error code that occurs when attempting to duplicate a record. //This will tell ScribeOnline that an update is required rather than an Insert. if (oleDbError == -2147217873) { //this is the error code for a 'Violation in unique index' errorResult.Number = ErrorNumber.DuplicateUniqueKey; } else { errorResult.Number = oleDbError; } successList.Add(false); objectList.Add(0); errors.Add(errorResult); } catch (Exception exception) { //In the event of an exception do not stop performing //all operations simply log each individually. successList.Add(false); objectList.Add(0); errors.Add(new ErrorResult() { Description = exception.Message, Detail = exception.ToString() }); } } //Add the results from the operations to the operation result object operationResult.Success = successList.ToArray(); operationResult.ObjectsAffected = objectList.ToArray(); operationResult.ErrorInfo = errors.ToArray(); } return operationResult; }
public OperationResult ExecuteOperation(OperationInput input) { this.product = "2700,2701,2702,2703,2704,2705,2706,2707,2708,2709,2734"; this.package = "pkgBorgCheck,pkgBorgVerify,pkgBorgMoveUpdate,pkgBorgGeoPoint,pkgBorgAppend,pkgBorgAppend,pkgBorgAppend,pkgBorgAppend,pkgBorgGeoCode,pkgIntAddressCheck,pkgIntGeoCode"; if (this.system.Contains("credit")) { this.serviceUri = new Uri(CheckInputSizeRequest(licensekey)); HttpWebRequest mykHttpWebRequest = null; HttpWebResponse mykHttpWebResponse = null; XmlDocument mykXMLDocument = null; XmlTextReader mykXMLReader = null; mykHttpWebRequest = WebRequest.Create(serviceUri) as HttpWebRequest; mykHttpWebRequest.Timeout = 60000; mykHttpWebRequest.ReadWriteTimeout = 60000; mykHttpWebRequest.Method = "GET"; mykHttpWebRequest.ContentType = "application/xml; charset=utf-8"; mykHttpWebRequest.Accept = "application/xml"; bool calloutSuccess = false; while (!calloutSuccess) { try { mykHttpWebResponse = (HttpWebResponse)mykHttpWebRequest.GetResponse(); calloutSuccess = true; } catch (WebException e) { calloutSuccess = false; } } mykXMLDocument = new XmlDocument(); mykXMLReader = new XmlTextReader(mykHttpWebResponse.GetResponseStream()); mykXMLDocument.Load(mykXMLReader); XmlNode krequestNode = mykXMLDocument.DocumentElement.ChildNodes[2]; int creditbalance; try { if (input.Input[0].ObjectDefinitionFullName.Contains("Personator")) { this.row++; this.counter++; creditbalance = int.Parse(krequestNode.InnerText); } else { this.row++; this.counter = this.counter + 20; creditbalance = int.Parse(krequestNode.InnerText); } } catch { Logger.Write(Logger.Severity.Info, "Data Results", "Empty List"); Scribe.Core.ConnectorApi.Exceptions.InvalidExecuteOperationException.ReferenceEquals("Data Results", "Empty List").ToString(); throw new System.ArgumentException("Data Results", "Empty List"); } if (creditbalance > this.counter) { this.IsConnected = true; Logger.Write(Logger.Severity.Info, "Credit Check Good", "Successful! Credit Balance: " + creditbalance + "On row: " + this.row); } else { if (this.geo > 0) { chargeGEO(); } if (this.IntGeo > 0) { chargeIntGeo(); } if (this.IntCheck > 0) { chargeIntCheck(); } if (this.check > 0) { chargeCheck(); } if (this.move > 0) { chargeMove(); } if (this.verify > 0) { chargeVerify(); } if (this.GeoBasic > 0) { chargeGeoCodeBasic(); } if ((this.appendaddress > 0) || (this.appendphone > 0) || (this.appendemail > 0) || (this.appendname > 0)) { chargeAppend(); } Logger.Write(Logger.Severity.Info, "Process Exception", " Not enough Credits for row: " + this.row + " Estimated Balance: " + (creditbalance - this.counter) + ", Please purchase more credits at http://www.melissadata.com/dqt/credits.htm"); this.IsConnected = false; throw new Scribe.Core.ConnectorApi.Exceptions.FatalErrorException("Processing Exception: Not enough Credits for row: " + this.row + " Estimated Balance: " + (creditbalance - this.counter) + ", Please purchase more credits at http://www.melissadata.com/dqt/credits.htm"); } } ErrorResult[] ErrorResultArray = new ErrorResult[input.Input.Length]; int[] ObjectsAffectedArray = new int[input.Input.Length]; bool[] SuccessArray = new bool[input.Input.Length]; var outputEntityArray = new DataEntity[input.Input.Length]; if (input.Input[0].ObjectDefinitionFullName.Contains("Personator") || input.Input[0].ObjectDefinitionFullName.Contains("BulkPersonator")) { System.ServiceModel.BasicHttpBinding myBinding = new System.ServiceModel.BasicHttpBinding(); myBinding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport; myBinding.MaxReceivedMessageSize = 900000000; System.ServiceModel.EndpointAddress myEndpointAddress = new System.ServiceModel.EndpointAddress("https://personator.melissadata.net/v3/SOAP/ContactVerify"); SOAP.ServicemdContactVerifySOAPClient client = new SOAP.ServicemdContactVerifySOAPClient(myBinding, myEndpointAddress); SOAP.Request request = new SOAP.Request(); request.CustomerID = licensekey; int numLoops = 0; if ((input.Input.Length % 100) == 0) { numLoops = (int)(input.Input.Length / 100); } else { numLoops = (int)(input.Input.Length / 100) + 1; } for (int i = 0; i < numLoops; i++) { DataEntity data = null; int floorDiv = (int)(input.Input.Length / 100); int innerCount = 0; request.Records = new SOAP.RequestRecord[((i < floorDiv) ? 100 : input.Input.Length % 100)]; for (int j = 0; j < ((i < floorDiv) ? 100 : input.Input.Length % 100); j++) { request.Records[j] = new SOAP.RequestRecord(); data = input.Input[innerCount]; if (data.Properties.ContainsKey("Input_RecordID")) { if (data.Properties["Input_RecordID"] == null) { request.Records[j].RecordID = ""; } else { request.Records[j].RecordID = data.Properties["Input_RecordID"].ToString(); } } if (data.Properties.ContainsKey("Input_City")) { if (data.Properties["Input_City"] == null) { request.Records[j].City = ""; } else { request.Records[j].City = data.Properties["Input_City"].ToString(); } } if (data.Properties.ContainsKey("Input_State")) { if (data.Properties["Input_State"] == null) { request.Records[j].State = ""; } else { request.Records[j].State = data.Properties["Input_State"].ToString(); } } if (data.Properties.ContainsKey("Input_PostalCode")) { if (data.Properties["Input_PostalCode"] == null) { request.Records[j].PostalCode = ""; } else { request.Records[j].PostalCode = data.Properties["Input_PostalCode"].ToString(); } } if ((data.Properties.ContainsKey("Setting_Columns"))) { string Columns = data.Properties["Setting_Columns"].ToString(); string[] cols; char[] charcolSeparators = new char[] { ',' }; cols = Columns.Split(charcolSeparators, 8, StringSplitOptions.RemoveEmptyEntries); for (int c = 0; c < cols.Length; c++) { if ((data.Properties.ContainsKey("Setting_Columns")) && !cols[c].ToString().Trim().ToLower().Equals("grpaddressdetails") && (!cols[c].ToString().Trim().ToLower().Equals("grpcensus")) && (!cols[c].ToString().Trim().ToLower().Equals("grpgeocode")) && (!cols[c].ToString().Trim().ToLower().Equals("grpnamedetails")) && (!cols[c].ToString().Trim().ToLower().Equals("grpparsedaddress")) && (!cols[c].ToString().Trim().ToLower().Equals("grpparsedemail")) && (!cols[c].ToString().Trim().ToLower().Equals("grpparsedphone")) && (!cols[c].ToString().Trim().ToLower().Equals("grpall")) && (!cols[c].ToString().Trim().ToLower().Equals("grpdemographicbasic"))) { throw new Scribe.Core.ConnectorApi.Exceptions.InvalidExecuteOperationException("Invalid Action, action must be either ({blank}, GrpAddressDetails, GrpCensus, GrpGeocode, GrpNameDetails, GrpParsedAddress, GrpParsedEmail, GrpParsedPhone, GrpAll"); } else { request.Columns = (!data.Properties.ContainsKey("Setting_Columns") ? "" : data.Properties["Setting_Columns"].ToString()); } } } if (data.Properties.ContainsKey("Setting_Actions")) { if (data.Properties["Setting_Actions"] == null) { request.Actions = "check"; } else { request.Actions = data.Properties["Setting_Actions"].ToString(); } } else { request.Actions = "check"; } if ((data.Properties.ContainsKey("Setting_Actions"))) { string Actions = data.Properties["Setting_Actions"].ToString(); string[] act; char[] charSeparators = new char[] { ',' }; act = Actions.Split(charSeparators, 4, StringSplitOptions.RemoveEmptyEntries); for (int k = 0; k < act.Length; k++) { if ((data.Properties.ContainsKey("Setting_Actions")) && !act[k].ToString().Trim().ToLower().Equals("append") && (!act[k].ToString().Trim().ToLower().Equals("check")) && (!act[k].ToString().Trim().ToLower().Equals("verify")) && (!act[k].ToString().Trim().ToLower().Equals("move"))) { throw new Scribe.Core.ConnectorApi.Exceptions.InvalidExecuteOperationException("Invalid Action, action must be either (Check, Verify, Append, Move"); } else { request.Actions = (!data.Properties.ContainsKey("Setting_Actions") ? "Check" : data.Properties["Setting_Actions"].ToString()); } } } if ((data.Properties.ContainsKey("Setting_AdvancedAddressCorrection")) && (!data.Properties["Setting_AdvancedAddressCorrection"].ToString().Trim().ToLower().Equals("on") && (!data.Properties["Setting_AdvancedAddressCorrection"].ToString().Trim().ToLower().Equals("off")))) { throw new Scribe.Core.ConnectorApi.Exceptions.InvalidExecuteOperationException("Invalid AdvancedAddressCorrection Property, action must be either (on, off"); } else { request.Options = request.Options + "AdvancedAddressCorrection:" + (!data.Properties.ContainsKey("Setting_AdvancedAddressCorrection") ? "off;" : data.Properties["Setting_AdvancedAddressCorrection"].ToString() + ";"); } if ((data.Properties.ContainsKey("Setting_CentricHint")) && (!data.Properties["Setting_CentricHint"].ToString().Trim().ToLower().Equals("auto")) && (!data.Properties["Setting_CentricHint"].ToString().Trim().ToLower().Equals("address")) && (!data.Properties["Setting_CentricHint"].ToString().Trim().ToLower().Equals("phone")) && (!data.Properties["Setting_CentricHint"].ToString().Trim().ToLower().Equals("email"))) { throw new Scribe.Core.ConnectorApi.Exceptions.InvalidExecuteOperationException("Invalid CentricHint Property, action must be either (auto, address, phone, email"); } else { request.Options = request.Options + "CentricHint:" + (!data.Properties.ContainsKey("Setting_CentricHint") ? "off;" : data.Properties["Setting_CentricHint"].ToString() + ";"); } if ((data.Properties.ContainsKey("Setting_Append")) && (!data.Properties["Setting_Append"].ToString().Trim().ToLower().Equals("blank")) && (!data.Properties["Setting_Append"].ToString().Trim().ToLower().Equals("checkerror")) && (!data.Properties["Setting_Append"].ToString().Trim().ToLower().Equals("always"))) { throw new Scribe.Core.ConnectorApi.Exceptions.InvalidExecuteOperationException("Invalid Append Property, action must be either (checkerror, blank, always"); } else { request.Options = request.Options + "Append:" + (!data.Properties.ContainsKey("Setting_Append") ? "Always;" : data.Properties["Setting_Append"].ToString() + ";"); } if ((data.Properties.ContainsKey("Setting_UsePreferredCity")) && (!data.Properties["Setting_UsePreferredCity"].ToString().Trim().ToLower().Equals("on")) && (!data.Properties["Setting_UsePreferredCity"].ToString().Trim().ToLower().Equals("off"))) { throw new Scribe.Core.ConnectorApi.Exceptions.InvalidExecuteOperationException("Invalid Append Property, action must be either (off, on)"); } else { request.Options = request.Options + "UsePreferredCity:" + (!data.Properties.ContainsKey("Setting_UsePreferredCity") ? "off;" : data.Properties["Setting_UsePreferredCity"].ToString() + ";"); } if (data.Properties.ContainsKey("Input_AddressLine2")) { if (data.Properties["Input_AddressLine2"] == null) { request.Records[j].AddressLine2 = ""; } else { request.Records[j].AddressLine2 = data.Properties["Input_AddressLine2"].ToString(); } } if (data.Properties.ContainsKey("Input_Country")) { if (data.Properties["Input_Country"] == null) { request.Records[j].Country = ""; } else { request.Records[j].Country = data.Properties["Input_Country"].ToString(); } } if (data.Properties.ContainsKey("Input_CompanyName")) { if (data.Properties["Input_CompanyName"] == null) { request.Records[j].CompanyName = ""; } else { request.Records[j].CompanyName = data.Properties["Input_CompanyName"].ToString(); } } if (data.Properties.ContainsKey("Input_FullName")) { if (data.Properties["Input_FullName"] == null) { request.Records[j].FullName = ""; } else { request.Records[j].FullName = data.Properties["Input_FullName"].ToString(); } } if (data.Properties.ContainsKey("Input_LastName")) { if (data.Properties["Input_LastName"] == null) { request.Records[j].LastName = ""; } else { request.Records[j].LastName = data.Properties["Input_LastName"].ToString(); } } if (data.Properties.ContainsKey("Input_PhoneNumber")) { if (data.Properties["Input_PhoneNumber"] == null) { request.Records[j].PhoneNumber = ""; } else { request.Records[j].PhoneNumber = data.Properties["Input_PhoneNumber"].ToString(); } } if (data.Properties.ContainsKey("Input_AddressLine1")) { if (data.Properties["Input_AddressLine1"] == null) { request.Records[j].AddressLine1 = ""; } else { request.Records[j].City = request.Records[j].City != null ? request.Records[j].City.Trim() : ""; request.Records[j].State = request.Records[j].State != null ? request.Records[j].State.Trim() : ""; request.Records[j].PostalCode = request.Records[j].PostalCode != null ? request.Records[j].PostalCode.Trim() : ""; request.Records[j].FreeForm = request.Records[j].FreeForm != null ? request.Records[j].FreeForm.Trim() : ""; if (request.Records[j].City == "" && request.Records[j].State == "" && request.Records[j].PostalCode == "" && request.Records[j].FreeForm == "") { request.Records[j].AddressLine1 = ""; request.Records[j].FreeForm = data.Properties["Input_AddressLine1"].ToString(); } else { request.Records[j].AddressLine1 = data.Properties["Input_AddressLine1"].ToString(); } } } if (data.Properties.ContainsKey("Input_FreeForm")) { if (data.Properties["Input_FreeForm"] == null) { request.Records[j].FreeForm = ""; } else { request.Records[j].AddressLine1 = ""; request.Records[j].FreeForm = data.Properties["Input_FreeForm"].ToString(); } } if (data.Properties.ContainsKey("Input_EmailAddress")) { if (data.Properties["Input_EmailAddress"] == null) { request.Records[j].EmailAddress = ""; } else { request.Records[j].EmailAddress = data.Properties["Input_EmailAddress"].ToString(); } } if (data.Properties.ContainsKey("Setting_Columns")) { if (data.Properties["Setting_Columns"] == null) { request.Columns = ""; } else { request.Columns = data.Properties["Setting_Columns"].ToString(); } } if (request.Records[j].PostalCode == "" && request.Records[j].State == "" && request.Records[j].City == "" && request.Records[j].FreeForm == "") { throw new Scribe.Core.ConnectorApi.Exceptions.InvalidExecuteOperationException("City, State or Zipcode or Freeform required."); } innerCount++; } this.serviceUri = new Uri(RequestToken(licensekey, this.product, this.package, ((i < floorDiv) ? 100 : input.Input.Length % 100).ToString())); HttpWebRequest myeHttpWebRequest = null; HttpWebResponse myeHttpWebResponse = null; XmlDocument myXMLDocument = null; XmlTextReader myXMLReader = null; myeHttpWebRequest = WebRequest.Create(serviceUri) as HttpWebRequest; myeHttpWebRequest.Timeout = 60000; myeHttpWebRequest.ReadWriteTimeout = 60000; myeHttpWebRequest.Method = "GET"; myeHttpWebRequest.ContentType = "application/xml; charset=utf-8"; myeHttpWebRequest.Accept = "application/xml"; bool success = false; while (!success) { try { myeHttpWebResponse = (HttpWebResponse)myeHttpWebRequest.GetResponse(); success = true; } catch (WebException e) { success = false; } } myXMLDocument = new XmlDocument(); myXMLReader = new XmlTextReader(myeHttpWebResponse.GetResponseStream()); myXMLDocument.Load(myXMLReader); XmlNode resultNode = myXMLDocument.DocumentElement.ChildNodes[0]; XmlNode tokenNode = myXMLDocument.DocumentElement.ChildNodes[1]; if (resultNode.InnerText.Contains("TS01") || resultNode.InnerText.Contains("TS02")) { request.CustomerID = tokenNode.InnerText; Logger.Write(Logger.Severity.Info, "Connection Results", "Token Successful"); } else { Logger.Write(Logger.Severity.Info, "Connection Results", "Token Successful"); } SOAP.Response response = null; while (response == null) { try { response = client.doContactVerify(request); } catch (Exception e) { } } for (int l = 0; l < response.Records.Length; l++) { List<PropertyInfo> responseProperties = response.Records[l].GetType().GetProperties().ToList(); var output = new DataEntity(input.Input[100 * i + l].ObjectDefinitionFullName); if ((response.Records[l].Results.Contains("AS"))) { this.check++; } if (response.Records[l].Results.Contains("GS05") || response.Records[l].Results.Contains("GS06")) { this.geo++; } if (response.Records[l].Results.Contains("GS01")) { this.GeoBasic++; } if (response.Records[l].Results.Contains("VR")) { this.verify++; } if (response.Records[l].Results.Contains("AS12")) { this.move++; } if (response.Records[l].Results.Contains("DA10")) { this.appendname++; } if (response.Records[l].Results.Contains("DA00")) { this.appendaddress++; } if (response.Records[l].Results.Contains("DA30")) { this.appendphone++; } if (response.Records[l].Results.Contains("DA40")) { this.appendemail++; } foreach (PropertyInfo property in responseProperties) { string getValue = property.GetValue(response.Records[l], null) != null ? property.GetValue(response.Records[l], null).ToString() : ""; output.Properties["MD_" + property.Name] = getValue; } outputEntityArray[i * 100 + l] = output; } } ErrorResultArray = new ErrorResult[input.Input.Length]; ObjectsAffectedArray = new int[input.Input.Length]; SuccessArray = new bool[input.Input.Length]; for (int x = 0; x < input.Input.Length; x++) { ErrorResultArray[x] = new ErrorResult(); ObjectsAffectedArray[x] = 1; SuccessArray[x] = true; } } if (input.Input[0].ObjectDefinitionFullName.Contains("Global_Address_Verification") || input.Input[0].ObjectDefinitionFullName.Contains("BulkGlobal")) { System.ServiceModel.BasicHttpBinding myBinding = new System.ServiceModel.BasicHttpBinding(); myBinding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport; myBinding.MaxReceivedMessageSize = 900000000; System.ServiceModel.EndpointAddress myEndpointAddress = new System.ServiceModel.EndpointAddress("https://address.melissadata.net/v3/SOAP/GlobalAddress"); SOAP3.AddressCheckSoapClient client = new SOAP3.AddressCheckSoapClient(myBinding, myEndpointAddress); SOAP3.Request request = new SOAP3.Request(); request.CustomerID = licensekey; int numLoops = 0; if ((input.Input.Length % 100) == 0) { numLoops = (int)(input.Input.Length / 100); } else { numLoops = (int)(input.Input.Length / 100) + 1; } for (int i = 0; i < numLoops; i++) { DataEntity data = null; int floorDiv = (int)(input.Input.Length / 100); int innerCount = 0; request.Records = new SOAP3.RequestRecord[((i < floorDiv) ? 100 : input.Input.Length % 100)]; for (int j = 0; j < ((i < floorDiv) ? 100 : input.Input.Length % 100); j++) { request.Records[j] = new SOAP3.RequestRecord(); data = input.Input[innerCount]; if (data.Properties.ContainsKey("Input_RecordID")) { if (data.Properties["Input_RecordID"] == null) { request.Records[j].RecordID = ""; } else { request.Records[j].RecordID = data.Properties["Input_RecordID"].ToString(); } } if (data.Properties.ContainsKey("Input_Organization")) { if (data.Properties["Input_Organization"] == null) { request.Records[j].Organization = ""; } else { request.Records[j].Organization = data.Properties["Input_Organization"].ToString(); } } if (data.Properties.ContainsKey("Input_AddressLine1")) { if (data.Properties["Input_AddressLine1"] == null) { request.Records[j].AddressLine1 = ""; } else { request.Records[j].AddressLine1 = data.Properties["Input_AddressLine1"].ToString(); } } if (data.Properties.ContainsKey("Input_AddressLine2")) { if (data.Properties["Input_AddressLine2"] == null) { request.Records[j].AddressLine2 = ""; } else { request.Records[j].AddressLine2 = data.Properties["Input_AddressLine2"].ToString(); } } if (data.Properties.ContainsKey("Input_AddressLine3")) { if (data.Properties["Input_AddressLine3"] == null) { request.Records[j].AddressLine3 = ""; } else { request.Records[j].AddressLine3 = data.Properties["Input_AddressLine3"].ToString(); } } if (data.Properties.ContainsKey("Input_AddressLine4")) { if (data.Properties["Input_AddressLine4"] == null) { request.Records[j].AddressLine4 = ""; } else { request.Records[j].AddressLine4 = data.Properties["Input_AddressLine4"].ToString(); } } if (data.Properties.ContainsKey("Input_AddressLine5")) { if (data.Properties["Input_AddressLine5"] == null) { request.Records[j].AddressLine5 = ""; } else { request.Records[j].AddressLine5 = data.Properties["Input_AddressLine5"].ToString(); } } if (data.Properties.ContainsKey("Input_AddressLine6")) { if (data.Properties["Input_AddressLine6"] == null) { request.Records[j].AddressLine6 = ""; } else { request.Records[j].AddressLine6 = data.Properties["Input_AddressLine6"].ToString(); } } if (data.Properties.ContainsKey("Input_AddressLine7")) { if (data.Properties["Input_AddressLine7"] == null) { request.Records[j].AddressLine7 = ""; } else { request.Records[j].AddressLine7 = data.Properties["Input_AddressLine7"].ToString(); } } if (data.Properties.ContainsKey("Input_AddressLine8")) { if (data.Properties["Input_AddressLine8"] == null) { request.Records[j].AddressLine8 = ""; } else { request.Records[j].AddressLine8 = data.Properties["Input_AddressLine8"].ToString(); } } if (data.Properties.ContainsKey("Input_DoubleDependentLocality")) { if (data.Properties["Input_DoubleDependentLocality"] == null) { request.Records[j].DoubleDependentLocality = ""; } else { request.Records[j].DoubleDependentLocality = data.Properties["Input_DoubleDependentLocality"].ToString(); } } if (data.Properties.ContainsKey("Input_DependentLocality")) { if (data.Properties["Input_DependentLocality"] == null) { request.Records[j].DependentLocality = ""; } else { request.Records[j].DependentLocality = data.Properties["Input_DependentLocality"].ToString(); } } if (data.Properties.ContainsKey("Input_Locality")) { if (data.Properties["Input_Locality"] == null) { request.Records[j].Locality = ""; } else { request.Records[j].Locality = data.Properties["Input_Locality"].ToString(); } } if (data.Properties.ContainsKey("Input_SubAdministrativeArea")) { if (data.Properties["Input_SubAdministrativeArea"] == null) { request.Records[j].SubAdministrativeArea = ""; } else { request.Records[j].SubAdministrativeArea = data.Properties["Input_SubAdministrativeArea"].ToString(); } } if (data.Properties.ContainsKey("Input_AdministrativeArea")) { if (data.Properties["Input_AdministrativeArea"] == null) { request.Records[j].AdministrativeArea = ""; } else { request.Records[j].AdministrativeArea = data.Properties["Input_AdministrativeArea"].ToString(); } } if (data.Properties.ContainsKey("Input_PostalCode")) { if (data.Properties["Input_PostalCode"] == null) { request.Records[j].PostalCode = ""; } else { request.Records[j].PostalCode = data.Properties["Input_PostalCode"].ToString(); } } if (data.Properties.ContainsKey("Input_SubNationalArea")) { if (data.Properties["Input_SubNationalArea"] == null) { request.Records[j].SubNationalArea = ""; } else { request.Records[j].SubNationalArea = data.Properties["Input_SubNationalArea"].ToString(); } } if (data.Properties.ContainsKey("Input_Country")) { if (data.Properties["Input_Country"] == null) { request.Records[j].Country = ""; } else { request.Records[j].Country = data.Properties["Input_Country"].ToString(); } } if (data.Properties.ContainsKey("Setting_DeliveryLines")) { if (data.Properties["Setting_DeliveryLines"] == null) { request.Records[j].Country = ""; } else { request.Records[j].Country = data.Properties["Setting_DeliveryLines"].ToString(); } } if ((data.Properties.ContainsKey("Setting_DeliveryLines")) && (!data.Properties["Setting_DeliveryLines"].ToString().Trim().ToLower().Equals("on") && (!data.Properties["Setting_DeliveryLines"].ToString().Trim().ToLower().Equals("off")))) { throw new Scribe.Core.ConnectorApi.Exceptions.InvalidExecuteOperationException("Invalid DeliveryLines Property, action must be either (on, off"); } else { request.Options = request.Options + "DeliveryLines:" + (!data.Properties.ContainsKey("Setting_DeliveryLines") ? "off;" : data.Properties["Setting_DeliveryLines"].ToString() + ";"); } if ((data.Properties.ContainsKey("Setting_LineSeparator")) && (!data.Properties["Setting_LineSeparator"].ToString().Trim().ToLower().Equals("semicolon") && (!data.Properties["Setting_DeliveryLines"].ToString().Trim().ToLower().Equals("pipe") && (!data.Properties["Setting_LineSeparator"].ToString().Trim().ToLower().Equals("cr") && (!data.Properties["Setting_LineSeparator"].ToString().Trim().ToLower().Equals("lf") && (!data.Properties["Setting_LineSeparator"].ToString().Trim().ToLower().Equals("crlf") && (!data.Properties["Setting_LineSeparator"].ToString().Trim().ToLower().Equals("tab") && (!data.Properties["Setting_LineSeparator"].ToString().Trim().ToLower().Equals("br"))))))))) { throw new Scribe.Core.ConnectorApi.Exceptions.InvalidExecuteOperationException("Invalid LineSeparator Property, action must be either (semicolon (default), pipe, cr, lf, crlf, tab, br (line break)"); } else { request.Options = request.Options + "LineSeparator:" + (!data.Properties.ContainsKey("LineSeparator") ? "SEMICOLON;" : data.Properties["Setting_DeliveryLines"].ToString() + ";"); } if ((data.Properties.ContainsKey("Setting_OutputScript")) && (!data.Properties["Setting_OutputScript"].ToString().Trim().ToLower().Equals("nochange") && (!data.Properties["Setting_OutputScript"].ToString().Trim().ToLower().Equals("latn")) && (!data.Properties["Setting_OutputScript"].ToString().Trim().ToLower().Equals("native")))) { throw new Scribe.Core.ConnectorApi.Exceptions.InvalidExecuteOperationException("Invalid LineSeparator Property, action must be either (nochange (default), latn, native"); } else { request.Options = request.Options + "OutputScript:" + (!data.Properties.ContainsKey("Setting_OutputScript") ? "nochange;" : data.Properties["Setting_OutputScript"].ToString() + ";"); } if ((data.Properties.ContainsKey("Setting_CountryOfOrigin"))) { request.Options = request.Options + "CountryOfOrigin:" + data.Properties["Setting_CountryOfOrigin"].ToString() + ";"; } innerCount++; } this.serviceUri = new Uri(RequestToken(licensekey, this.product, this.package, ((i < floorDiv) ? 100 : input.Input.Length % 100).ToString())); HttpWebRequest myeHttpWebRequest = null; HttpWebResponse myeHttpWebResponse = null; XmlDocument myXMLDocument = null; XmlTextReader myXMLReader = null; myeHttpWebRequest = WebRequest.Create(serviceUri) as HttpWebRequest; myeHttpWebRequest.Timeout = 60000; myeHttpWebRequest.ReadWriteTimeout = 60000; myeHttpWebRequest.Method = "GET"; myeHttpWebRequest.ContentType = "application/xml; charset=utf-8"; myeHttpWebRequest.Accept = "application/xml"; bool success = false; while (!success) { try { myeHttpWebResponse = (HttpWebResponse)myeHttpWebRequest.GetResponse(); success = true; } catch (WebException e) { success = false; } } myXMLDocument = new XmlDocument(); myXMLReader = new XmlTextReader(myeHttpWebResponse.GetResponseStream()); myXMLDocument.Load(myXMLReader); XmlNode resultNode = myXMLDocument.DocumentElement.ChildNodes[0]; XmlNode tokenNode = myXMLDocument.DocumentElement.ChildNodes[1]; if (resultNode.InnerText.Contains("TS01") || resultNode.InnerText.Contains("TS02")) { request.CustomerID = tokenNode.InnerText; Logger.Write(Logger.Severity.Info, "Connection Results", "Token Successful"); } SOAP3.Response response = client.doGlobalAddress(request); for (int l = 0; l < response.Records.Length; l++) { List<PropertyInfo> responseProperties = response.Records[l].GetType().GetProperties().ToList(); var output = new DataEntity(input.Input[100 * i + l].ObjectDefinitionFullName); if ((response.Records[l].Results.Contains("AV"))) { this.IntCheck++; } if (response.Records[l].Results.Contains("GS")) { this.IntGeo++; } foreach (PropertyInfo property in responseProperties) { string getValue = property.GetValue(response.Records[l], null) != null ? property.GetValue(response.Records[l], null).ToString() : ""; output.Properties["MD_" + property.Name] = getValue; } outputEntityArray[i * 100 + l] = output; } } ErrorResultArray = new ErrorResult[input.Input.Length]; ObjectsAffectedArray = new int[input.Input.Length]; SuccessArray = new bool[input.Input.Length]; for (int x = 0; x < input.Input.Length; x++) { ErrorResultArray[x] = new ErrorResult(); ObjectsAffectedArray[x] = 1; SuccessArray[x] = true; } } foreach (var entity in outputEntityArray) { bulkQueue.Enqueue(entity); } return new OperationResult(input.Input.Length) { ErrorInfo = ErrorResultArray, ObjectsAffected = ObjectsAffectedArray, Output = outputEntityArray, Success = SuccessArray }; }
public static PacketContent NewErrorResult(string clientInvokeId,string error = "") { var result = new ErrorResult(error, clientInvokeId); return new PacketContent(Generate(result)); }
public ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string alternateButton1Label, ErrorResult resultIfAlternateButtonPressed, string message) { return policy.ShouldShowMessage(message) && ErrorReporter.ReportException(new Exception(message), m_registryKey, m_supportEmailAddress, m_parentForm, false) ? ErrorResult.Abort : ErrorResult.Ignore; }
private static DialogResult GetDialogResultForErrorResult(ErrorResult errorResult) { DialogResult dialogResult; switch (errorResult) { case ErrorResult.Abort: dialogResult = DialogResult.Abort; break; case ErrorResult.Cancel: dialogResult = DialogResult.Cancel; break; case ErrorResult.Ignore: dialogResult = DialogResult.Ignore; break; case ErrorResult.No: dialogResult = DialogResult.No; break; case ErrorResult.None: dialogResult = DialogResult.None; break; case ErrorResult.OK: dialogResult = DialogResult.OK; break; case ErrorResult.Retry: dialogResult = DialogResult.Retry; break; case ErrorResult.Yes: dialogResult = DialogResult.Yes; break; default: throw new ArgumentOutOfRangeException(String.Format("Can't convert ErrorResult {0} to DialogResult Type", errorResult)); } return dialogResult; }
public RestApiException(ErrorResult errorResult) { ErrorResult = errorResult; }
public static ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string alternateButton1Label, ErrorResult resultIfAlternateButtonPressed, string messageFmt, params object[] args) { var message = string.Format(messageFmt, args); if (s_justRecordNonFatalMessagesForTesting) { s_previousNonFatalMessage = message; return ErrorResult.OK; } return _errorReporter.NotifyUserOfProblem(policy, alternateButton1Label, resultIfAlternateButtonPressed, message); }
/// <summary> /// Perform the Delete operations on the selected table. /// This method will filter deletes using the SqlQueryBuilder and the lookup conditions /// </summary> /// <param name="operationInput">The operation information being executed.</param> /// <returns>The result of the operation that was processed.</returns> public OperationResult DeleteOperation(OperationInput operationInput) { OperationResult operationResult = new OperationResult(); // Use LogMethodExecution to add entry and exit tracing to a method. // When wrapped in a using statement, the exit point // is written during garbage collection. using (new LogMethodExecution(Globals.ConnectorName, "Delete")) { // Each record processed must return the following 3 pieces of information. // Each piece of information should be added in the same order it was received. // The first piece of information would be whether or not the request was successful. // If the requested record does not exist it should not result in a failure. List<bool> successList = new List<bool>(); // The second piece of information is the number of records that have been processed. // If a delete is attempted on a record that does not exist then 0 rows should be reported here. List<int> objectList = new List<int>(); // In the event of an error during processing the record, error information should be added here. // If no error occured a null placeholder for that record is expected. List<ErrorResult> errors = new List<ErrorResult>(); int index = 0; // Execute each of the inputs individually // **** Processing inputs individually is done because the // connector is responsible for error handling on each. // The connector must return results in the same order in which the // data entities were received, this allows for reprocessing of failed records. //Note: If the SupportsBulk flag is not set in the ActionDefinition // that corresponds to this operation, operationInput.Input // will always have always have a length of 1. foreach (DataEntity inputEntity in operationInput.Input) { try { // Process the number of rows that will be deleted. ValidateRowCount(inputEntity, operationInput.LookupCondition[index], operationInput.AllowMultipleObject); // Use the query builder to parse input conditions. var query = new SqlQueryBuilder(inputEntity, operationInput.LookupCondition[index], Globals.QueryType.Delete); // Execute the query generated from the operation input. int rowCount = _dataAccess.ExecuteNonQuery(query.ToString()); // Add a the result to the result list. successList.Add(SetSuccessResult(operationInput.AllowMultipleObject, rowCount)); objectList.Add(rowCount); errors.Add(SetErrorResult(rowCount)); index++; } catch (ArgumentException argumentException) { // This will catch a filter that returns multiple rows // when only one is expected. var errorResult = new ErrorResult() { Description = argumentException.Message, Number = ErrorCodes.TooManyRowsReturned.Number }; errors.Add(errorResult); successList.Add(false); objectList.Add(0); } catch (Exception exception) { // In the event of an exception do not stop performing // all operations simply log each individually successList.Add(false); objectList.Add(0); errors.Add(new ErrorResult() { Description = exception.Message, Detail = exception.ToString() }); } } //Add the results from the operations to the operation result object operationResult.Success = successList.ToArray(); operationResult.ObjectsAffected = objectList.ToArray(); operationResult.ErrorInfo = errors.ToArray(); } return operationResult; }
/// <summary> /// Set the error result of the operation bassed on how many rows have been deleted /// </summary> /// <param name="rowsEffected"></param> /// <returns></returns> private ErrorResult SetErrorResult(int rowsEffected) { ErrorResult errorResult = new ErrorResult(); if (rowsEffected == 0) { errorResult.Number = ErrorCodes.NoRowsFound.Number; errorResult.Description = ErrorCodes.NoRowsFound.Description; } return errorResult; }