public static void ConfigureExceptionHandler(this IApplicationBuilder appBuilder, ILoggerFactory loggerFactory)
        {
            appBuilder.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                    context.Response.ContentType = "application/json";

                    var contextFeature = context.Features.Get <IExceptionHandlerFeature>();
                    if (contextFeature != null)
                    {
                        var _logger = loggerFactory.CreateLogger(typeof(Startup));
                        var error   = new ErrorDetail
                        {
                            ErrorMessage = "Internal Server Error",
                            StatusCode   = context.Response.StatusCode
                        }.ToString();

                        _logger.LogError($"Exception:{contextFeature.Error}");
                        await context.Response.WriteAsync(error);
                    }
                });
            });
        }
Exemplo n.º 2
0
        private void OnException(Exception ex)
        {
            ErrorDetail detail = new ErrorDetail();

            detail.ErrorMessage = ex.ToString();
            log.Error(detail.ErrorMessage);
        }
Exemplo n.º 3
0
 public void Error(ErrorDetail detail)
 {
     if (_service != null)
     {
         _service.Error(detail);
     }
 }
        public ActionResult AddWeekDays([Bind(Include = "WeekDayName,CbuWeekDay")] tb_WeekDay WeekDay)
        {
            Error error = new Error();

            error.errCode = ErrorDetail.Success;
            error.errMsg  = ErrorDetail.GetMsg(error.errCode);
            List <string> errs = new List <string>();

            if (ModelState.IsValid)
            {
                db.tb_WeekDay.Add(WeekDay);
                try
                {
                    db.SaveChanges();
                }
                catch (DbEntityValidationException ex)
                {
                    error.errCode = ErrorDetail.DataImportError;
                    error.errMsg  = ErrorDetail.GetMsg(error.errCode);
                    foreach (DbEntityValidationResult validationError in ex.EntityValidationErrors)
                    {
                        error.errMsg += ". Object: " + validationError.Entry.Entity.ToString();
                        foreach (DbValidationError err in validationError.ValidationErrors)
                        {
                            error.errMsg += ". " + err.ErrorMessage;
                        }
                    }
                    errs.Add("Error #" + error.errCode.ToString() + "!" + error.errMsg);
                    TempData["ErrorList"] = errs;
                }
            }

            return(RedirectToAction("AdminImportCBU", "Account", null));
            //return View(WeekDay);
        }
 public static MethodResult <TResult> MapMethodResult <TSource, TResult>(
     this MethodResult <TSource> @this,
     Func <TResult> onSuccessFunction,
     ErrorDetail errorDetail
     ) => @this.IsSuccess
     ? MethodResult <TResult> .Ok(onSuccessFunction())
     : MethodResult <TResult> .Fail(errorDetail);
        public async Task <IActionResult> Approve([FromRoute] string id)
        {
            try
            {
                await _service.ApproveAsync(id);

                return(Ok());
            }
            catch (DeliveryNotFoundException e)
            {
                _logger.LogWarning("Delivered {Id} can not be found", id);
                var error = new ErrorDetail("delivery_not_found", $"Delivered {id} can not be found");
                return(NotFound(error));
            }
            catch (DeliveryOperationInvalidForStatusException e)
            {
                _logger.LogWarning("Delivered {Id} are not valid for approval", id);
                var error = new ErrorDetail("delivery_operation_invalid", $"Delivery {id} can not be approved because of its current state {e.CurrentState}. Only delivery in status created can be approved");
                return(Conflict(error));
            }
            catch (DeliveryTimeElapsedException e)
            {
                _logger.LogWarning("Delivered {Id} is too late for approval", id);
                var error = new ErrorDetail("delivery_time_elapsed", $"Delivery {id} can not be approved because of its start time {e.StartTime} is in the past");
                return(Conflict(error));
            }
        }
Exemplo n.º 7
0
        public void LoadLog(ErrorDetail eDetail)
        {
            logDetail = eDetail;

            PopulateLog(eDetail.logSprite, eDetail.logString);
            logType.color = ColorOfLog(eDetail.errorType);
        }
Exemplo n.º 8
0
        public static ErrorResponse ToErrorResponse(this ModelStateDictionary modelState)
        {
            if (modelState is null)
            {
                throw new ArgumentNullException(paramName: nameof(modelState));
            }

            var modelValidationErrors = new List <ErrorDetail>();

            foreach (KeyValuePair <string, ModelStateEntry> modelEntry in modelState)
            {
                foreach (var modelError in modelEntry.Value.Errors)
                {
                    var error = new ErrorDetail(message: modelError.ErrorMessage, target: modelEntry.Key);
                    modelValidationErrors.Add(error);
                }
                ;
            }

            var errorResponse = new ErrorResponse("Model state is invalid", ExceptionCode.UnprocessableEntity.ToString());

            errorResponse.Details = modelValidationErrors;

            return(errorResponse);
        }
Exemplo n.º 9
0
        public void ErrorNotHandle(int code)
        {
            var contextFeature = HttpContext.Features.Get <IStatusCodeReExecuteFeature>();

            int    status;
            string title;
            string message;
            string origen = contextFeature.OriginalPath;

            switch (code)
            {
            case 404:
                status  = code;
                title   = "Not Found";
                message = "El recurso no existe: " + origen;
                break;

            default:
                status  = (int)HttpStatusCode.InternalServerError;
                title   = "Internal Server Error";
                message = "Error interno generado en la ruta:" + origen;
                break;
            }

            var error = new ErrorDetail
            {
                Status  = status,
                Title   = title,
                Message = message
            }.ToString();

            Response.StatusCode  = status;
            Response.ContentType = "application/json";
            Response.WriteAsync(error);
        }
Exemplo n.º 10
0
        public int DeleteSession(string sessionID)
        {
            Guid session = new Guid(sessionID);
            ISessionProducerContract contract = new ProducerSessionContract();

            try
            {
                return(contract.Delete(session));
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateException ex)
            {
                var msg = "Failed to Delete session " + sessionID + ", UpdateException: " + ex.Message + ", InnerException: " + ex.InnerException;
                Debug.WriteLine(msg, GetType().Name);
                var detail = new ErrorDetail(ErrorDetail.Codes.JOB_STATE_ERROR, msg);
                //throw new WebFaultException<ErrorDetail>(detail, System.Net.HttpStatusCode.BadRequest);
                throw;
            }
            catch (Exception ex)
            {
                var msg = "Failed to Delete session " + sessionID + ", " + ex + ": " + ex.Message + ", InnerException: " + ex.InnerException;
                Debug.WriteLine(msg, GetType().Name);
                var detail = new ErrorDetail(ErrorDetail.Codes.JOB_STATE_ERROR, msg);
                throw new WebFaultException <ErrorDetail>(detail, System.Net.HttpStatusCode.BadRequest);
            }
        }
     /// <summary>
     ///     Action method for the ViewRClientException, creates the Exception Message, which is Json serialized
     /// </summary>
     /// <returns></returns>
     private Action ViewRClientExceptionAction(Exception viewRException)
     {
         return (() =>
         {
             LogException(viewRException);
 
             ViewRClientException currentException = viewRException as ViewRClientException;
 
             ExceptionMessageUI exceptionMessageUI = new ExceptionMessageUI();
 
             exceptionMessageUI.ErrorType = currentException.ErrorTypeDetail;
 
             exceptionMessageUI.ErrorDetailList = new List<ErrorDetail>();
 
             foreach (ClientError clientError in currentException.ClientErrorEntity)
             {
                 ErrorDetail errorDetail = new ErrorDetail();
 
                 errorDetail.ErrorCode = clientError.ErrorCode;
 
                 errorDetail.ErrorMessage = clientError.ErrorMessage;
 
                 exceptionMessageUI.ErrorDetailList.Add(errorDetail);
             }
 
             globalHttpContextMessage = JsonConvert.SerializeObject(exceptionMessageUI, Formatting.Indented);
         });
     }
Exemplo n.º 12
0
        public string DeleteSessionGeneratorResults(string sessionid, string generatorid)
        {
            Guid sessionGuid   = new Guid(sessionid);
            Guid generatorGuid = new Guid(generatorid);

            string output = "Failed to Delete Generator";

            try
            {
                output = DataMarshal.DeleteGenerator(generatorGuid) ? "Generator has been successfully deleted"
                    : output;
            }
            catch (Exception ex)
            {
                var msg = "Failed to Delete Generator: " + generatorid + ", UpdateException: "
                          + ex.Message + ", InnerException: " + ex.InnerException + ", StackTrace: " + ex.StackTrace.ToString();
                Debug.WriteLine(msg, "SessionResource.DeleteSessionGeneratorResults");
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.DATAFORMAT_ERROR,
                    String.Format("Failed to Delete Generator")
                    );
                throw new WebFaultException <ErrorDetail>(detail, System.Net.HttpStatusCode.BadRequest);
            }

            return(output);
        }
Exemplo n.º 13
0
        public Stream StartSessionGeneratorResults(string sessionid, string generatorid, string pagenum)
        {
            bool verbose  = JobQueryParameters.GetVerbose(false);
            int  page     = 0;
            int  sub_page = QueryParameters_GetPage(1);
            int  rpp      = QueryParameters_GetPageSize(1000);

            Int32.TryParse(pagenum, out page);

            Guid sessionGuid   = new Guid(sessionid);
            Guid generatorGuid = new Guid(generatorid);

            string json = "";

            List <Dictionary <string, object> > joblist = null;

            try
            {
                joblist = DataMarshal.GetGeneratorPage(generatorGuid, page, sub_page, rpp, verbose);
                json    = Newtonsoft.Json.JsonConvert.SerializeObject(joblist);
            }
            catch (Exception ex)
            {
                var msg = "Failed to get page: " + pagenum + ", UpdateException: "
                          + ex.Message + ", InnerException: " + ex.InnerException + ", StackTrace: " + ex.StackTrace.ToString();
                Debug.WriteLine(msg, "SessionResource.StartSessionGeneratorResults");
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.DATAFORMAT_ERROR,
                    String.Format("Failed to get page")
                    );
                throw new WebFaultException <ErrorDetail>(detail, System.Net.HttpStatusCode.BadRequest);
            }

            return(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)));
        }
Exemplo n.º 14
0
        /// <summary>
        ///  Copy session to a new session with the desired job state.
        /// </summary>
        /// <param name="sessionID"></param>
        /// <returns>Json session's new Guid and new jobs Count numbers</returns>
        public Stream CopySession(string sessionid)
        {
            string state = QueryParameters_GetData("error", "state");

            Dictionary <string, string> d = null;

            ISessionProducerContract contract = new ProducerSessionContract();

            try
            {
                Debug.WriteLine("Copying Session, jobs with state: " + state, "SessionResource.CopySession");
                d = contract.Copy(new Guid(sessionid), state);
            }
            catch (Exception ex)
            {
                var msg = "Failed to Copy session: " + sessionid + ", UpdateException: "
                          + ex.Message + ", InnerException: " + ex.InnerException + ", StackTrace: " + ex.StackTrace.ToString();
                Debug.WriteLine(msg, "SessionResource.CopySession");
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.DATAFORMAT_ERROR,
                    String.Format("Couldn't Copy Session")
                    );
                throw new WebFaultException <ErrorDetail>(detail, System.Net.HttpStatusCode.BadRequest);
            }

            string json = Newtonsoft.Json.JsonConvert.SerializeObject(d);

            return(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)));

            //return new MemoryStream(System.Text.Encoding.UTF8.GetBytes(result ?? ""));
        }
Exemplo n.º 15
0
        public int DeleteSession(string sessionID)
        {
            Guid session = new Guid(sessionID);
            ISessionProducerContract contract = new AspenSessionProducerContract();

            try
            {
                return(contract.Delete(session));
            }
            catch (System.Data.UpdateException ex)
            {
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.JOB_STATE_ERROR,
                    "Failed to Delete session " + sessionID + ", " + ex.Message + ", InnerException: " + ex.InnerException
                    );
                throw new WebFaultException <ErrorDetail>(detail, System.Net.HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.JOB_STATE_ERROR,
                    "Failed to Delete session " + sessionID + ", " + ex.Message +
                    ", Inner Exception: " + ex.InnerException
                    );
                throw new WebFaultException <ErrorDetail>(detail, System.Net.HttpStatusCode.BadRequest);
            }
        }
Exemplo n.º 16
0
        public static string GetJSON(HttpWebRequest req)
        {
            try
            {
                HttpWebResponse res = req.GetResponse() as HttpWebResponse;

                StreamReader streamReader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                return(streamReader.ReadToEnd());
            }
            catch (WebException wE)
            {
                using (HttpWebResponse eR = wE.Response as HttpWebResponse)
                {
                    if (eR == null)
                    {
                        throw;
                    }

                    ErrorDetail newError = FromJSONStream <ErrorDetail>(new StreamReader(eR.GetResponseStream()));

                    switch (eR.StatusCode)
                    {
                    case HttpStatusCode.InternalServerError:        //500
                    case HttpStatusCode.NotFound:                   //404
                    default:
                        throw new D3Exception(string.Format("Response Status: {0} {1}. {2}", (int)eR.StatusCode, eR.StatusCode, newError.Reason), newError, req.RequestUri.ToString(), wE);
                    }
                }
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// GET: Returns resource representation of Simulation
        /// </summary>
        /// <param name="name">Simulation name</param>
        /// <returns>Get Version of Simulation</returns>
        public Simulation GetSimulation(string nameOrID)
        {
            Guid simulationid = Guid.Empty;
            bool isGuid       = Guid.TryParse(nameOrID, out simulationid);

            Debug.WriteLine("Find simulation: " + nameOrID, this.GetType().Name);
            Simulation sim = null;

            try
            {
                sim = DataMarshal.GetSimulation(nameOrID, isGuid);

                /*if (sim == null)
                 * {
                 *  var detail = new ErrorDetail(
                 *      ErrorDetail.Codes.DATAFORMAT_ERROR,
                 *      String.Format("simulation \"{0}\" does not exist", nameOrID)
                 *  );
                 *  throw new WebFaultException<ErrorDetail>(detail,
                 *      System.Net.HttpStatusCode.NotFound);
                 * }
                 * return sim;*/
            }
            catch (Exception ex)
            {
                Debug.WriteLine("No simulation " + nameOrID, this.GetType().Name);
                Debug.WriteLine(ex.ToString());
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.DATAFORMAT_ERROR,
                    "No simulation " + nameOrID + ", traceback: " + ex.StackTrace.ToString()
                    );
                throw new WebFaultException <ErrorDetail>(detail, System.Net.HttpStatusCode.NotFound);
            }
            return(sim);
        }
            public CreateCohortWithOtherPartyControllerTestFixture()
            {
                var autoFixture = new Fixture();

                CommitmentsApiClientMock = new Mock <ICommitmentsApiClient>();
                ErrorDetail = new ErrorDetail("field1", "error message");

                MapperResult    = new CreateCohortWithOtherPartyRequest();
                ModelMapperMock = new Mock <IModelMapper>();
                ModelMapperMock
                .Setup(x => x.Map <CreateCohortWithOtherPartyRequest>(It.IsAny <object>()))
                .ReturnsAsync(() => MapperResult);

                MessageViewModel = autoFixture.Create <MessageViewModel>();
                ModelMapperMock.Setup(x => x.Map <MessageViewModel>(It.IsAny <object>()))
                .ReturnsAsync(() => MessageViewModel);

                Sut = new CohortController(
                    CommitmentsApiClientMock.Object, Mock.Of <ILogger <CohortController> >(),
                    Mock.Of <ILinkGenerator>(),
                    ModelMapperMock.Object,
                    Mock.Of <IAuthorizationService>(),
                    Mock.Of <IEncodingService>()
                    );
            }
Exemplo n.º 19
0
        public static int GetPageSize(int val)
        {
            string param = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["rpp"];

            if (string.IsNullOrEmpty(param))
            {
                return(val);
            }

            if (!Int32.TryParse(param, out val))
            {
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.QUERYPARAM_ERROR,
                    "page size failed to parse as int"
                    );
                throw new WebFaultException <ErrorDetail>(detail,
                                                          System.Net.HttpStatusCode.BadRequest);
            }

            if (val == -1)
            {
                val = 2000;
            }
            if (val > 2000)
            {
                Debug.WriteLine("Exceed page size", "QueryParameters");
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.DATABOUNDS_ERROR,
                    String.Format("Exceeded page size maximum: {0} > 2000", val)
                    );
                throw new WebFaultException <ErrorDetail>(detail, System.Net.HttpStatusCode.BadRequest);
            }
            return(val);
        }
Exemplo n.º 20
0
 public async Task SaveExceptionAsync(ErrorDetail ex)
 {
     await _db.ExecuteScalarAsync <int>(
         $@"INSERT INTO {_options.ErrorLogTableName} 
     (id, host, ""user"", exception_type, status_code, message, stacktrace, time_utc, detail_json) 
     VALUES(@Id, @Host, @User, @ExceptionType, @StatusCode, @Message, @StackTrace, @TimeUtc, JSON(@DetailJson))", ex);
 }
Exemplo n.º 21
0
        public bool Validate(string nameOrID)
        {
            Guid simulationId = Guid.Empty;
            bool isGuid       = Guid.TryParse(nameOrID, out simulationId);

            bool all = SimulationQueryParameters.GetRecurse(false);
            ISimulationProducerContract contract = null;

            try
            {
                contract = ProducerSimulationContract.Get(nameOrID);
            }
            catch (Exception ex)
            {
                string msg = String.Format("Failed to Get Simulation {0}: {1} {2}",
                                           nameOrID, ex.Message, ex.StackTrace.ToString());
                if (ex.InnerException != null)
                {
                    msg += String.Format("    InnerException:    {0} {1}",
                                         ex.InnerException.Message, ex.InnerException.StackTrace.ToString());
                }
                Debug.WriteLine(msg, this.GetType().Name);
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.DATAFORMAT_ERROR,
                    msg
                    );
                throw new WebFaultException <ErrorDetail>(detail,
                                                          System.Net.HttpStatusCode.InternalServerError);
            }
            return(isGuid ? contract.Validate() : contract.ValidateAll());
        }
Exemplo n.º 22
0
        /// <summary>
        /// Saves the screenshot.
        /// </summary>
        /// <param name="errorDetail">The error detail.</param>
        /// <param name="folder">The folder.</param>
        /// <param name="title">The title.</param>
        /// <returns>Path to the screenshot</returns>
        public string SaveScreenshot(ErrorDetail errorDetail, string folder, string title)
        {
            var fileName        = string.Format(CultureInfo.CurrentCulture, "{0}_{1}_{2}.png", title, errorDetail.DateTime.ToString("yyyy-MM-dd HH-mm-ss-fff", CultureInfo.CurrentCulture), "browser");
            var correctFileName = Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(CultureInfo.CurrentCulture), string.Empty));

            correctFileName = Regex.Replace(correctFileName, "[^0-9a-zA-Z._]+", "_");
            correctFileName = NameHelper.ShortenFileName(folder, correctFileName, "_", 255);

            var filePath = Path.Combine(folder, correctFileName);

            try
            {
                errorDetail.Screenshot.SaveAsFile(filePath, ScreenshotImageFormat.Png);
                FilesHelper.WaitForFileOfGivenName(BaseConfiguration.ShortTimeout, correctFileName, folder);
                Logger.Error(CultureInfo.CurrentCulture, "Test failed: screenshot saved to {0}.", filePath);
                Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "##teamcity[publishArtifacts '{0}']", filePath));
                return(filePath);
            }
            catch (NullReferenceException)
            {
                Logger.Error("Test failed but was unable to get webngDriver screenshot.");
            }

            return(null);
        }
Exemplo n.º 23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
            .ConfigureApiBehaviorOptions(setup =>
            {
                setup.InvalidModelStateResponseFactory = context =>
                {
                    var problemDetails = new ErrorDetail()
                    {
                        StatusCode = StatusCodes.Status422UnprocessableEntity,
                        Massage    = "²ÎÊý´íÎó"
                    };

                    return(new UnprocessableEntityObjectResult(problemDetails)
                    {
                        ContentTypes = { "application/problem+json" }
                    });
                };
            });

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddSingleton <FutrueContext>();
            services.AddTransient <IRoleRepository, RoleRepository>();
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IPermissionRepository, PermissionRepository>();
        }
Exemplo n.º 24
0
        public Stream GetStagedInputFile(string name, string inputName)
        {
            OutgoingWebResponseContext ctx = WebOperationContext.Current.OutgoingResponse;
            var e = DataMarshal.GetStagedInputFile(name, inputName);

            if (e == null)
            {
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.DATAFORMAT_ERROR,
                    String.Format("simulation \"{0}\" input \"{1}\" does not exist", name, inputName)
                    );
                throw new WebFaultException <ErrorDetail>(detail,
                                                          System.Net.HttpStatusCode.NotFound);
            }
            if (e.Content == null)
            {
                return(new MemoryStream());
            }
            ctx.ContentType = "text/plain";
            if (e.InputFileType != null && e.InputFileType.Type != null)
            {
                ctx.ContentType = e.InputFileType.Type;
            }
            ctx.StatusCode = System.Net.HttpStatusCode.OK;
            return(new MemoryStream(e.Content));
        }
Exemplo n.º 25
0
        /// <summary>
        /// Constructor. Takes the service client object representing the protected item
        /// and converts it in to the PS protected item model
        /// </summary>
        /// <param name="protectedItemResource">Service client object representing the protected item resource</param>
        /// <param name="containerName">Name of the container associated with this protected item</param>
        /// <param name="containerType">Type of the container associated with this protected item</param>
        /// <param name="policyName">Name of the protection policy associated with this protected item</param>
        public AzureWorkloadSAPHanaDatabaseProtectedItem(CrrModel.ProtectedItemResource protectedItemResource,
                                                         string containerName, ContainerType containerType, string policyName)
            : base(protectedItemResource, containerName, containerType, policyName)
        {
            CrrModel.AzureVmWorkloadSAPHanaDatabaseProtectedItem protectedItem = (CrrModel.AzureVmWorkloadSAPHanaDatabaseProtectedItem)protectedItemResource.Properties;
            FriendlyName = protectedItem.FriendlyName;
            ServerName   = protectedItem.ServerName;
            ParentName   = protectedItem.ParentName;
            ParentType   = protectedItem.ParentType;

            if (protectedItem.LastBackupErrorDetail != null)
            {
                LastBackupErrorDetail = new ErrorDetail(protectedItem.LastBackupErrorDetail.Code, protectedItem.LastBackupErrorDetail.Message, protectedItem.LastBackupErrorDetail.Recommendations);
            }

            ProtectedItemDataSourceId = protectedItem.ProtectedItemDataSourceId;
            ProtectedItemHealthStatus = protectedItem.ProtectedItemHealthStatus;
            LastBackupStatus          = protectedItem.LastBackupStatus;
            LastBackupTime            = protectedItem.LastBackupTime;
            ProtectionState           =
                EnumUtils.GetEnum <ItemProtectionState>(protectedItem.ProtectionState.ToString());
            ProtectionStatus = EnumUtils.GetEnum <ItemProtectionStatus>(protectedItem.ProtectionStatus);
            DateOfPurge      = null;
            DeleteState      = EnumUtils.GetEnum <ItemDeleteState>("NotDeleted");
            if (protectedItem.IsScheduledForDeferredDelete.HasValue)
            {
                DateOfPurge = protectedItem.DeferredDeleteTimeInUTC.Value.AddDays(14);
                DeleteState = EnumUtils.GetEnum <ItemDeleteState>("ToBeDeleted");
            }
        }
Exemplo n.º 26
0
        public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILogger logger)
        {
            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    context.Response.StatusCode  = 500;
                    context.Response.ContentType = "application/json";

                    var contextFeature = context.Features.Get <IExceptionHandlerFeature>();

                    if (contextFeature != null)
                    {
                        var errorDetails = new ErrorDetail()
                        {
                            StatusCode = context.Response.StatusCode,
                            Message    = "Internal Server Error."
                        };
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(errorDetails));

                        logger.LogError(String.Format("Stacktrace of error: {0}", contextFeature.Error.StackTrace.ToString()));
                    }
                });
            });
        }
Exemplo n.º 27
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            if (error is FaultException <ErrorMessage> )
            {
                return;
            }
            var runtime = RuntimeFactory.Current;
            var tracer  = runtime.GetTracer();
            FaultException <ErrorMessage> faultException;

            if (tracer != null)
            {
                faultException = new FaultException <ErrorMessage>(new ErrorMessage
                {
                    Message       = error.Message,
                    FaultLocation = tracer.GetCallstack().ErrorPath,
                    TicketNumber  = runtime.InstanceId,
                    Detail        = ErrorDetail.GetDetails(error)
                }, error.Message);
            }
            else
            {
                faultException = new FaultException <ErrorMessage>(new ErrorMessage
                {
                    Message = error.Message,
                    Detail  = ErrorDetail.GetDetails(error)
                }, error.Message);
            }
            var messageFault = faultException.CreateMessageFault();

            fault = Message.CreateMessage(version, messageFault, "http://stardustframework.com/messaging/fault");
        }
Exemplo n.º 28
0
        internal static ResourceGroupExportResult DeserializeResourceGroupExportResult(JsonElement element)
        {
            Optional <object>      template = default;
            Optional <ErrorDetail> error    = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("template"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    template = property.Value.GetObject();
                    continue;
                }
                if (property.NameEquals("error"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    error = ErrorDetail.DeserializeErrorDetail(property.Value);
                    continue;
                }
            }
            return(new ResourceGroupExportResult(template.Value, error.Value));
        }
Exemplo n.º 29
0
        public Stream GetJobResources()
        {
            int    page       = JobQueryParameters.GetPage(1);
            int    rpp        = JobQueryParameters.GetPageSize(1000);
            bool   verbose    = JobQueryParameters.GetVerbose(false);
            Guid   sessionID  = JobQueryParameters.GetSessionId();
            string simulation = JobQueryParameters.GetSimulationName();
            string state      = JobQueryParameters.GetState();
            string order      = JobQueryParameters.GetOrder();
            Guid   consumerID = JobQueryParameters.GetConsumerId();

            Debug.WriteLine(String.Format("get job resources {0},{1}", page, rpp), this.GetType().Name);
            List <Dictionary <string, Object> > jobs = null;

            try
            {
                jobs = DataMarshal.GetJobs(sessionID, simulation, consumerID, state, order, page, rpp, verbose);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("EXCEPTION: {0}   {1}", ex, ex.Message), this.GetType().Name);
                Debug.WriteLine("Stack Trace: " + ex.StackTrace, this.GetType().Name);
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.DATAFORMAT_ERROR,
                    "Get Jobs Query Failed\n\nMessage: " + ex.Message + "\n\n\nStack Trace: " + ex.StackTrace
                    );
                throw new WebFaultException <ErrorDetail>(detail, System.Net.HttpStatusCode.BadRequest);
            }
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(jobs);

            return(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)));
        }
Exemplo n.º 30
0
        public Stream GetJob(string id)
        {
            bool verbose = JobQueryParameters.GetVerbose(false);

            Debug.WriteLine("GET job: " + id, this.GetType().Name);

            int myid = Convert.ToInt32(id);
            Dictionary <string, Object> d;

            try
            {
                d = DataMarshal.GetJobDict(myid, verbose);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("EXCEPTION: {0}   {1}", ex, ex.Message), this.GetType().Name);
                Debug.WriteLine("Stack Trace: " + ex.StackTrace, this.GetType().Name);
                var detail = new ErrorDetail(
                    ErrorDetail.Codes.DATAFORMAT_ERROR,
                    "No Job.Id=" + id
                    );
                throw new WebFaultException <ErrorDetail>(detail, System.Net.HttpStatusCode.NotFound);
            }
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(d);

            return(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)));
        }
Exemplo n.º 31
0
 public void RegisterError(ErrorDetail errorDetail)
 {
     Debug.WriteLine(string.Format("({0},{1}): {2}", errorDetail.Line, errorDetail.Column, errorDetail.Message));
     Errors.Add(errorDetail);
 }
Exemplo n.º 32
0
 public void RegisterError(int? line, int? column, string message)
 {
     var errorDetail = new ErrorDetail { Message = message, Line = line, Column = column };
     RegisterError(errorDetail);
 }
Exemplo n.º 33
0
        private void WriteSourceCode(TextWriter writer, ErrorDetail error, string[] compilationLines)
        {
            if (String.IsNullOrEmpty(error.Location.FileName) || !error.Location.LineNumber.HasValue)
            {
                writer.Write("&lt;Source Not Available&gt;");
                return;
            }

            string[] lines;
            if(error.Location.InGeneratedSource)
            {
                lines = compilationLines;
            }
            else if (File.Exists(error.Location.FileName))
            {
                // Super hacky!
                lines = File.ReadAllLines(error.Location.FileName);
            }
            else
            {
                writer.Write("&lt;Source Not Available&gt;");
                return;
            }

            string line = lines[error.Location.LineNumber.Value];
            writer.Write(String.Format("{0}:{1}", error.Location.LineNumber.Value, WebUtility.HtmlEncode(line)));
        }
Exemplo n.º 34
0
 public void Error(string message, GherkinBufferPosition errorPosition, Exception exception)
 {
     var errorDetail = new ErrorDetail
                           {
                               Message = message,
                               Line = errorPosition.Line + 1,
                               Column = errorPosition.LinePosition + 1
                           };
     errors.Add(errorDetail);
 }