public ActionResult Index() { var model = new ErrorModel(); var httpException = RouteData.Values["httpException"] as HttpException; var httpCode = (httpException == null) ? 500 : httpException.GetHttpCode(); switch (httpCode) { case 403: Response.StatusCode = 403; model.Heading = "Forbidden"; model.Message = "You aren't authorised to access this page."; break; case 404: Response.StatusCode = 404; model.Heading = "Page not found"; model.Message = "We couldn't find the page you requested."; break; case 500: default: Response.StatusCode = 500; model.Heading = "Error"; model.Message = "Sorry, something went wrong. It's been logged."; break; } Response.TrySkipIisCustomErrors = true; return View(model); }
public ActionResult Error404() { var model = new ErrorModel { PageTitle = "Ошибка 404", Error = "Ошибка 404" }; return View(model); }
public DuplicatedItemException(string msg) : base() { this.error = new ErrorModel { type = "api/prob/duplicated-item", title = "Attempted to create duplicated item", detail = msg, status = System.Net.HttpStatusCode.Conflict }; }
public ClosedIssueException(string msg) : base() { this.error = new ErrorModel { type = "api/prob/closed-issue", title = "Closed issue", detail = msg, status = System.Net.HttpStatusCode.Forbidden }; }
public InvalidStateException(string msg) : base() { this.error = new ErrorModel { type = "api/prob/invalid-state", title = "Set Invalid State to Issue", detail = msg, status = System.Net.HttpStatusCode.Forbidden }; }
public NotFoundException(string msg) : base() { this.error = new ErrorModel { type = "api/prob/not-found", title = "Resource not found", detail = msg, status = System.Net.HttpStatusCode.NotFound }; }
public ActionResult Index(int statusCode, Exception exception, bool isAjaxRequet) { var model = new ErrorModel { HttpStatusCode = statusCode, Message = WebDavAppConfigManager.Instance.HttpErrors[statusCode], Exception = exception }; Response.StatusCode = statusCode; if (!isAjaxRequet) return View(model); var errorObject = new { statusCode = model.HttpStatusCode, message = model.Message }; return Json(errorObject, JsonRequestBehavior.AllowGet); }
public int InsertErrorLog(ErrorModel errorModel) { return(_iCommonRepository.InsertErrorLog(errorModel)); }
public async Task <IActionResult> GetUserAddressesAsync() { try { var currentUser = User.Identity.Name; if (currentUser != null) { AppUser appUser = await _userManager.FindByNameAsync(currentUser); if (appUser != null) { OperationResult operationResult_addresses = _uow.UserAddress.FindAll(x => x.UserId == appUser.Id); if (operationResult_addresses.IsSuccess) { List <UserAddress> userAddresses = (List <UserAddress>)operationResult_addresses.ReturnObject; List <UserAdressRES> userAdressRESs = userAddresses.Select(x => x.UserAdressDTtoRES()).ToList(); apiResponsive = new ApiResponsive() { IsSucces = true, ErrorContent = null, ReturnObject = userAdressRESs }; return(Ok(apiResponsive)); } ErrorModel errorModel1 = new ErrorModel() { ErrorCode = MessageNumber.AdresGetirirkenHata.ToString(), ErrorMessage = _localizer["AdresGetirirkenHata"] }; errorModels.Add(errorModel1); apiResponsive = new ApiResponsive() { IsSucces = false, ReturnObject = null, ErrorContent = errorModels }; return(BadRequest(apiResponsive)); } } ErrorModel errorModel2 = new ErrorModel() { ErrorCode = MessageNumber.KullaniciBulunamadi.ToString(), ErrorMessage = _localizer["KullaniciBulunamadi"] }; errorModels.Add(errorModel2); apiResponsive = new ApiResponsive() { IsSucces = false, ReturnObject = null, ErrorContent = errorModels }; return(BadRequest(apiResponsive)); } catch (Exception ex) { _logger.LogError($"Error in {nameof(GetUserAddressesAsync)} : {ex}"); ErrorModel errorModel2 = new ErrorModel() { ErrorCode = MessageNumber.BeklenmedikHata.ToString(), ErrorMessage = _localizer["BeklenmedikHata"] }; errorModels.Add(errorModel2); apiResponsive = new ApiResponsive() { IsSucces = false, ReturnObject = null, ErrorContent = errorModels }; return(BadRequest(apiResponsive)); } }
public UserRegisterResponseModel register(UserRegisterRequestModel userRegister, out ErrorModel errorModel) { errorModel = null; try { User userProvider = new User(); UserRegisterResponseModel userRegisterResponse = userProvider.register(userRegister.Email, userRegister.Password, userRegister.FirstName, userRegister.lastName, userRegister.Phone, userRegister.UserType, out errorModel); return(userRegisterResponse); } catch (Exception e) { return(null); } }
public ChangeOrderStatusResponseModel changePassword(ChangePasswordRequestModel changePasswordRequest, out ErrorModel errorModel) { errorModel = null; User user = new User(); try { return(user.changePassword(changePasswordRequest, out errorModel)); } catch { return(null); } }
public ActionResult Index(int errCode) { ErrorModel model = new ErrorModel(errCode); return(View(model)); }
/// <summary> /// Lists all of the available operations. /// </summary> /// <remarks> /// Lists all the available operations provided by Service Fabric SeaBreeze /// resource provider. /// </remarks> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorModelException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <IPage <OperationResult> > > ListWithHttpMessagesAsync(Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.ServiceFabricMesh/operations").ToString(); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorModel _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorModel>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <IPage <OperationResult> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Page <OperationResult> >(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public ActionResult ErrorList(ErrorModel model) { ErrorModel lstErrors = new ErrorModel(); lstErrors.Logger = model.Logger; lstErrors.Severity = model.Severity; lstErrors.Hours = model.Hours; lstErrors.ConStringId = model.ConStringId; lstErrors.HoursList = ((Common.HoursBeforeEnum[])Enum.GetValues(typeof(Common.HoursBeforeEnum))).Select(c => new SelectListItem() { Value = Convert.ToString((int)c), Text = c.ToString() }).ToList(); string ConnString = Enum.GetName(typeof(Common.ConnectionStringName), lstErrors.ConStringId); using (SqlConnection conn = new SqlConnection(GetConnectionString(ConnString))) { SqlCommand cmd = new SqlCommand("GetSeverityListByLogger"); SqlParameter param = new SqlParameter(); param.ParameterName = "@logger"; param.Value = model.Logger.Split('-')[1].Trim(); cmd.Parameters.Add(param); param = new SqlParameter(); param.ParameterName = "@applicationCode"; param.Value = model.ApplicationCode; cmd.Parameters.Add(param); cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn; conn.Open(); SqlDataAdapter MyDataAdapter = new SqlDataAdapter(); MyDataAdapter.SelectCommand = cmd; DataSet oDataset = new DataSet(); DataTable oDatatable = new DataTable(); cmd.ExecuteNonQuery(); MyDataAdapter.Fill(oDataset); oDatatable = oDataset.Tables[0]; conn.Close(); foreach (DataRow dr in oDatatable.Rows) { SelectListItem item = new SelectListItem(); item.Text = dr["Severity"].ToString(); item.Value = dr["Severity"].ToString(); lstErrors.SeverityList.Add(item); } } using (SqlConnection conn = new SqlConnection(GetConnectionString(ConnString))) { SqlCommand cmd = new SqlCommand("GetErrorList"); SqlParameter param = new SqlParameter(); param.ParameterName = "@logger"; param.Value = model.Logger.Split('-')[1].Trim(); cmd.Parameters.Add(param); param = new SqlParameter(); param.ParameterName = "@severity"; param.Value = model.Severity; cmd.Parameters.Add(param); param = new SqlParameter(); param.ParameterName = "@hours"; param.Value = model.Hours; cmd.Parameters.Add(param); param = new SqlParameter(); param.ParameterName = "@applicationCode"; param.Value = model.ApplicationCode; cmd.Parameters.Add(param); cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn; conn.Open(); SqlDataAdapter MyDataAdapter = new SqlDataAdapter(); MyDataAdapter.SelectCommand = cmd; DataSet oDataset = new DataSet(); DataTable oDatatable = new DataTable(); cmd.ExecuteNonQuery(); MyDataAdapter.Fill(oDataset); oDatatable = oDataset.Tables[0]; conn.Close(); foreach (DataRow dr in oDatatable.Rows) { Error Objerror = new Error(); Objerror.LogId = dr["LogId"].ToString(); Objerror.ApplicationCode = dr["ApplicationCode"].ToString(); Objerror.ComponentStatus = dr["ComponentStatus"].ToString(); Objerror.ErrorCode = dr["ErrorCode"].ToString(); Objerror.Exception = dr["Exception"].ToString(); Objerror.LogFile = dr["LogFile"].ToString(); Objerror.Identity = dr["Identity"].ToString(); Objerror.LogDate = Convert.ToDateTime(dr["LogDate"].ToString()); Objerror.Logger = dr["Logger"].ToString(); Objerror.Message = dr["Message"].ToString(); Objerror.MessageData = dr["MessageData"].ToString(); Objerror.Method = dr["Method"].ToString(); Objerror.Severity = dr["Severity"].ToString(); Objerror.StackTrace = dr["StackTrace"].ToString(); lstErrors.ErrorList.Add(Objerror); } } lstErrors.ApplicationList = GetApplicationList(lstErrors.ConStringId, model.ApplicationCode); lstErrors.ApplicationCode = model.ApplicationCode; return(View(lstErrors)); }
public async Task <HttpResponseMessage> Groups(GroupsDataModel model) { Thread.CurrentThread.CurrentCulture = culture; List <GroupsQueryModel> resultSeachModel = null; GroupsByIdModel resultSeachByIdModel = null; Grupos proxy = new Grupos(); try { if (!await Authentication.isAdmin(User, Request)) { Authentication auth = new Authentication(); if (!await auth.AccesRights(User.Identity.GetUserId(), "groups", model.type)) { return(Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized)); } auth = null; } using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { using (SqlConnection connection1 = new SqlConnection(connetionString)) { await connection1.OpenAsync(); if (model.type == 1) { resultSeachModel = new List <GroupsQueryModel>(); await proxy.SearchQuery(model.search, resultSeachModel, connection1); } else if (model.type == 2) { resultSeachByIdModel = new GroupsByIdModel(); await proxy.ById(model.byId, connection1, resultSeachByIdModel); } else if (model.type == 3) { await proxy.New(connection1, model.update); } else if (model.type == 4) { await proxy.Update(connection1, model.update); } else if (model.type == 5) { await proxy.UpdateIsActive(connection1, model.isActive); } } scope.Complete(); } } catch (TransactionAbortedException ex) { ErrorModel _errors = new ErrorModel(); _errors.message = ex.Message; return(Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError, _errors)); } catch (Exception ex) { ErrorModel _errors = new ErrorModel(); _errors.message = ex.Message; return(Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError, _errors)); } if (model.type == 1) { return(Request.CreateResponse(System.Net.HttpStatusCode.OK, resultSeachModel)); } else if (model.type == 2) { return(Request.CreateResponse(System.Net.HttpStatusCode.OK, resultSeachByIdModel)); } return(Request.CreateResponse(System.Net.HttpStatusCode.OK)); }
public ErrorActionResult(HttpRequestMessage request, HttpStatusCode statusCode, ErrorModel errors) { _response = request.CreateResponse(statusCode, errors); }
public CustomerNotificationResponseModel getNotificationsDataCustomer(int customerId, int capacity, out ErrorModel errorModel) { CustomerNotificationResponseModel customerNotificationResponseModel = null; errorModel = null; SqlConnection connection = null; try { using (connection = new SqlConnection(Database.getConnectionString())) { customerNotificationResponseModel = new CustomerNotificationResponseModel(); customerNotificationResponseModel.orderChange = new List <OrderStatusChangeNotification>(); SqlCommand command = new SqlCommand(SqlCommands.SP_customerNotification, connection); command.CommandType = System.Data.CommandType.StoredProcedure; #region parameters command.Parameters.AddWithValue("capacity", capacity); command.Parameters.AddWithValue("customerId", customerId); #endregion connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { customerNotificationResponseModel.istableAvailable = Convert.ToBoolean(reader["isTableAvailable"].ToString()); if (reader.isColumnExists("orderId")) { OrderStatusChangeNotification temp = new OrderStatusChangeNotification(); temp.orderId = Convert.ToInt32(reader["orderId"].ToString()); temp.statusId = Convert.ToInt32(reader["orderStatusId"].ToString()); temp.orderStatusTitle = reader["orderStatusTitle"].ToString(); customerNotificationResponseModel.orderChange.Add(temp); } } connection.Close(); command.Dispose(); } return(customerNotificationResponseModel); } catch (Exception e) { errorModel = new ErrorModel(); errorModel.ErrorMessage = e.Message; return(null); } finally { if (connection != null) { connection.Close(); } } }
public static Hashtable TaxDetails(Hashtable ht, string Type, string Req) { try { string[] words = null; string Data = Req; ReturnData.Clear(); if (Type == "Fill") { words = null; words = Req.Split('@'); for (int m = 0; words.Count() > m; m++) { Data = words[m].ToString(); if (Data == "Edit") { ht_param.Clear(); ht_param.Add("@ID", ht["ID"].ToString()); ht_param.Add("@Company_ID", HttpContext.Current.Session["Company_ID"].ToString()); ht_param.Add("@Branch_ID", HttpContext.Current.Session["Branch_ID"].ToString()); ht_param.Add("@login_id", HttpContext.Current.Session["Login_user_ID"].ToString()); ds = db.SysFetchDataInDataSet("[GET_ITEM_CATEGORY]", ht_param); if (ds.Tables.Count > 0) { _gstModel = ds.Tables[0].AsEnumerable() .Select(row => new ItemCategoryModel { ID = row["ID"].ToString(), NAME = row["NAME"].ToString(), CODE = row["CODE"].ToString(), ImageURL = row["ImageURL"].ToString(), IsActive = row["IsActive"].ToString() }).ToList(); } ReturnData["TaxData"] = serializer.Serialize(_gstModel); } } } if (Type == "Save") { _UserSaveModel.Clear(); ht_param.Clear(); ht_param.Add("@NAME", ht["NAME"].ToString()); ht_param.Add("@CODE", ht["CODE"].ToString()); ht_param.Add("@IsActive", ht["IsActive"].ToString()); ht_param.Add("@Company_ID", HttpContext.Current.Session["Company_ID"].ToString()); ht_param.Add("@Branch_ID", HttpContext.Current.Session["Branch_ID"].ToString()); ht_param.Add("@login_id", HttpContext.Current.Session["Login_user_ID"].ToString()); ds = db.SysFetchDataInDataSet("[SAVE_UPDATE_ITEM_CATEGORY]", ht_param); if (ds.Tables.Count > 0) { foreach (DataRow item in ds.Tables[0].Rows) { UserSaveModel _UserSaveModelDetails = new UserSaveModel(); _UserSaveModelDetails.CustomErrorState = item["CustomErrorState"].ToString(); _UserSaveModelDetails.CustomMessage = item["CustomMessage"].ToString(); _UserSaveModel.Add(_UserSaveModelDetails); } } ReturnData["Save"] = serializer.Serialize(_UserSaveModel); } if (Type == "Update") { _UserSaveModel.Clear(); ht_param.Clear(); ht_param.Add("@ID", ht["ID"]); ht_param.Add("@NAME", ht["NAME"].ToString()); ht_param.Add("@CODE", ht["CODE"].ToString()); ht_param.Add("@IsActive", ht["IsActive"].ToString()); ht_param.Add("@Company_ID", HttpContext.Current.Session["Company_ID"].ToString()); ht_param.Add("@Branch_ID", HttpContext.Current.Session["Branch_ID"].ToString()); ht_param.Add("@login_id", HttpContext.Current.Session["Login_user_ID"].ToString()); ds = db.SysFetchDataInDataSet("[SAVE_UPDATE_ITEM_CATEGORY]", ht_param); if (ds.Tables.Count > 0) { foreach (DataRow item in ds.Tables[0].Rows) { UserSaveModel _UserSaveModelDetails = new UserSaveModel(); _UserSaveModelDetails.CustomErrorState = item["CustomErrorState"].ToString(); _UserSaveModelDetails.CustomMessage = item["CustomMessage"].ToString(); _UserSaveModel.Add(_UserSaveModelDetails); } } ReturnData["Update"] = serializer.Serialize(_UserSaveModel); } _ErrorModel.Clear(); ErrorModel _error = new ErrorModel(); _error.Error = "false"; _error.ErrorMessage = "sucess"; _ErrorModel.Add(_error); ReturnData["ErrorDetail"] = serializer.Serialize(_ErrorModel); HttpContext.Current.Response.AppendHeader("ResponseHeader", "200"); } catch (Exception ex) { _ErrorModel.Clear(); ReturnData.Clear(); ErrorModel _error = new ErrorModel(); _error.Error = "true"; _error.ErrorMessage = "Some problem occurred please try again later"; _ErrorModel.Add(_error); ReturnData["ErrorDetail"] = serializer.Serialize(_ErrorModel); HttpContext.Current.Response.AppendHeader("ResponseHeader", "500"); } return(ReturnData); }
internal DuoError(ErrorModel model) { Code = model.Code; Message = model.Message; Detail = model.Message_Detail; }
/// <summary> /// Creates a new pet in the store. Duplicates are allowed /// </summary> /// <param name='pets'> /// Pets to add to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorModelException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <IList <Pet> > > AddPetWithHttpMessagesAsync(IList <Pet> pets, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (pets == null) { throw new ValidationException(ValidationRules.CannotBeNull, "pets"); } if (pets != null) { foreach (var element in pets) { if (element != null) { element.Validate(); } } } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("pets", pets); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "AddPet", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (pets != null) { _requestContent = SafeJsonConvert.SerializeObject(pets, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorModel _errorBody = SafeJsonConvert.DeserializeObject <ErrorModel>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <IList <Pet> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <IList <Pet> >(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Creates a list on mailchimp /// </summary> /// <param name="listId">The Id of the list to be add the merge field</param> /// <param name="mergeField">The model that contains all info about the merge field that will be created</param> /// <returns></returns> public MailChimpWrapperResponse <MergeFieldCreateResponseModel> Create(string listId, MergeFieldCreateModel mergeField) { try { // Initialize the RestRequest from RestSharp.Newtonsoft so the serializer will user Newtonsoft defaults. var request = new RestRequest(ResourcesEndpoints.MergeFieldCreate(listId), Method.POST); // Adds the resource request.AddHeader("content-type", "application/json"); request.JsonSerializer = new CustomNewtonsoftSerializer(new JsonSerializer() { NullValueHandling = NullValueHandling.Ignore, }); // Validates the object var validationContext = new ValidationContext(mergeField, serviceProvider: null, items: null); var validationResults = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(mergeField, validationContext, validationResults, false); if (isValid) { request.AddJsonBody(mergeField); // Execute the request var response = restClient.Execute(request); // If the request return ok, then return MailChimpWrapperResponse with deserialized object if (response.StatusCode == System.Net.HttpStatusCode.OK) { return new MailChimpWrapperResponse <MergeFieldCreateResponseModel> { objectRespose = JsonConvert.DeserializeObject <MergeFieldCreateResponseModel>(response.Content) } } ; // If an error occurs, encapsulates the error in MailChimpWrapperResponse var errorContent = JsonConvert.DeserializeObject <ErrorModel>(response.Content); return(new MailChimpWrapperResponse <MergeFieldCreateResponseModel> { hasErrors = true, error = errorContent }); } // If the object was not valid then creates and ErrorModel to send back var error = new ErrorModel { type = "Internal Method Error.", title = "One or more fields were not validated. Look in detail for more information", status = 0, detail = Util.GetValidationsErrors(validationResults) }; return(new MailChimpWrapperResponse <MergeFieldCreateResponseModel> { hasErrors = true, error = error }); } catch (Exception ex) { return(ErrorResponse <MergeFieldCreateResponseModel>(ex)); } }
/// <summary> /// Updates Or Adds the member by its email_addres based on MembersPutModel object /// </summary> /// <param name="listId">The Id of the list to be updated</param> /// <param name="member">The data to update or add if not exist</param> /// <returns></returns> public MailChimpWrapperResponse <MembersCreateResponseModel> Update(string listId, MembersPutModel member) { try { // Initialize the RestRequest from RestSharp.Newtonsoft so the serializer will user Newtonsoft defaults. var request = new RestRequest(ResourcesEndpoints.MembersUpdate(listId, member.email_address), Method.PUT); // Adds the resource request.AddHeader("content-type", "application/json"); request.JsonSerializer = new CustomNewtonsoftSerializer(new JsonSerializer() { NullValueHandling = NullValueHandling.Ignore, }); // Validates the object var validationContext = new ValidationContext(member, serviceProvider: null, items: null); var validationResults = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(member, validationContext, validationResults, false); if (isValid) { request.AddJsonBody(member); // Execute the request var response = restClient.Execute(request); // If the request return ok, then return MailChimpWrapperResponse with deserialized object if (response.StatusCode == System.Net.HttpStatusCode.OK) { return new MailChimpWrapperResponse <MembersCreateResponseModel> { objectRespose = JsonConvert.DeserializeObject <MembersCreateResponseModel>(response.Content) } } ; // If an error occurs, encapsulates the error in MailChimpWrapperResponse var errorContent = JsonConvert.DeserializeObject <ErrorModel>(response.Content); return(new MailChimpWrapperResponse <MembersCreateResponseModel> { hasErrors = true, error = errorContent }); } // If the object was not valid then creates and ErrorModel to send back var error = new ErrorModel { type = "Internal Method Error.", title = string.Format("Field {0} missing", validationResults[0]?.MemberNames.FirstOrDefault()), status = 0, detail = validationResults[0].ErrorMessage }; return(new MailChimpWrapperResponse <MembersCreateResponseModel> { hasErrors = true, error = error }); } catch (Exception ex) { return(ErrorResponse <MembersCreateResponseModel>(ex)); } }
public ActionResult GenericError(ErrorModel model) { return View(model); }
public ErrorModelEventArgs(ErrorModel val) : base() { Value = val; }
public List <eOfficeBranch> AdminSaveBranch(List <eOfficeBranch> listBranch, string userRequest, out ErrorModel errorModel) { List <eOfficeBranch> ret = null; errorModel = new ErrorModel(); try { DBHelper db = new DBHelper(GlobalInfo.PKG_TMS_SYSTEM + ".sp_save_branch", userRequest) .addParamOutput("oResult") .addParam("pUserName", userRequest) .addParam("pJson", JsonHelper.Serialize(listBranch)) .ExecuteStore(); ret = db.getList <eOfficeBranch>(); errorModel.ErrorCode = 1; errorModel.ErrorMsg = "Success"; } catch (Exception ex) { errorModel.ErrorCode = -1; errorModel.ErrorMsg = ex.Message; errorModel.ErrorDetail = ex.ToString(); } return(ret); }
public ErrorModelEventArgs(int severity, string msg) : base() { Value = new ErrorModel(severity,msg); }
public static Hashtable LoginDetails(Hashtable ht, string Type, string Req) { List <PermissionModel> _PermissionModelList = new List <PermissionModel>(); ReturnData.Clear(); try { if (Type == "Login") { if (Req == "NormalLogin") { ht_param.Clear(); ht_param.Add("@Email", ht["Email"].ToString()); ht_param.Add("@Password", ht["Password"].ToString()); ds = db.SysFetchDataInDataSet("[Getloginuser]", ht_param); if (ds.Tables[0].Rows.Count > 0) { string CustomErrorState = ds.Tables[0].Rows[0]["CustomErrorState"].ToString().Trim(); string CustomMessage = ds.Tables[0].Rows[0]["CustomMessage"].ToString().Trim(); if (CustomErrorState == "0") { _ErrorModel.Clear(); ReturnData.Clear(); ErrorModel _error = new ErrorModel(); _error.Error = "0"; _error.ErrorMessage = "Sucess"; _ErrorModel.Add(_error); ReturnData["ErrorDetail"] = serializer.Serialize(_ErrorModel); ht_param2.Clear(); ht_param2.Add("COMPANY_ID", ds.Tables[1].Rows[0]["COMPANY_ID"].ToString()); ht_param2.Add("BRANCH_ID", ds.Tables[1].Rows[0]["BRANCH_ID"].ToString()); ht_param2.Add("CONTACT_ID", ds.Tables[1].Rows[0]["CONTACT_ID"].ToString().Trim()); ht_param2.Add("COMPANY_LOGOPATH", ds.Tables[1].Rows[0]["COMPANY_LOGOPATH"].ToString().Trim()); ht_param2.Add("BRANCH_LOGOPATH", ds.Tables[1].Rows[0]["BRANCH_LOGOPATH"].ToString().Trim()); //ht_param2.Add("CONTACT_LOGOPATH", ds.Tables[1].Rows[0]["CONTACT_LOGOPATH"].ToString().Trim()); ht_param2.Add("COMPANY_NAME", ds.Tables[1].Rows[0]["COMPANY_NAME"].ToString().Trim()); ht_param2.Add("BRANCH_NAME", ds.Tables[1].Rows[0]["BRANCH_NAME"].ToString().Trim()); ht_param2.Add("CONTACT_NAME", ds.Tables[1].Rows[0]["CONTACT_NAME"].ToString().Trim()); ht_param2.Add("ROLEID", ds.Tables[1].Rows[0]["ROLEID"].ToString().Trim()); ht_param2.Add("IsAgent", ds.Tables[1].Rows[0]["IsAgent"].ToString().Trim()); //ht_param2.Add("CONTACT_TYPE", ds.Tables[1].Rows[0]["CONTACT_TYPE"].ToString().Trim()); HttpContext.Current.Session["Company_ID"] = ds.Tables[1].Rows[0]["COMPANY_ID"].ToString(); HttpContext.Current.Session["Branch_ID"] = ds.Tables[1].Rows[0]["BRANCH_ID"].ToString(); HttpContext.Current.Session["Login_user_ID"] = ds.Tables[1].Rows[0]["CONTACT_ID"].ToString(); HttpContext.Current.Session["ROLEID"] = ds.Tables[1].Rows[0]["ROLEID"].ToString(); //HttpContext.Current.Session["CONTACT_TYPE"] = ds.Tables[1].Rows[0]["CONTACT_TYPE"].ToString(); ds.Clear(); ht_param.Clear(); ht_param.Add("@UID", ht["Email"].ToString()); ht_param.Add("@PWD", ht["Password"].ToString()); ds = db.SysFetchDataInDataSet("[LOGIN_CHECK2]", ht_param); if (ds.Tables[0].Rows.Count > 0) { if (ds.Tables[0].Rows[0]["ERROR_ID"].ToString() == "0") { ht_param2.Add("MENU", ds.Tables[0].Rows[0]["MENU"].ToString().Trim()); } } serializer.MaxJsonLength = 1000000000; _PermissionModelList.Clear(); if (ds.Tables.Count >= 2) { _PermissionModelList = ds.Tables[1].AsEnumerable() .Select(row => new PermissionModel { Url = row["url"].ToString(), MenuID = row["ID"].ToString(), MenuName = row["MenuName"].ToString(), Role_ID = row["RoleID"].ToString(), B_Add = row["B_Add"].ToString(), B_Edit = row["B_Edit"].ToString(), B_Delete = row["B_Delete"].ToString(), B_View = row["B_View"].ToString(), Status = row["Status"].ToString(), }).ToList(); ReturnData["PagePermission"] = serializer.Serialize(_PermissionModelList); } ReturnData["Login"] = serializer.Serialize(ht_param2); } else if (CustomErrorState == "1") { _ErrorModel.Clear(); ReturnData.Clear(); ErrorModel _error = new ErrorModel(); _error.Error = "1"; _error.ErrorMessage = "Some problem occurred please try again later"; _ErrorModel.Add(_error); ReturnData["ErrorDetail"] = serializer.Serialize(_ErrorModel); HttpContext.Current.Response.AppendHeader("ResponseHeader", "500"); } else if (CustomErrorState == "2") { _ErrorModel.Clear(); ReturnData.Clear(); ErrorModel _error = new ErrorModel(); _error.Error = "2"; _error.ErrorMessage = CustomMessage; _ErrorModel.Add(_error); ReturnData["ErrorDetail"] = serializer.Serialize(_ErrorModel); HttpContext.Current.Response.AppendHeader("ResponseHeader", "500"); } } else { _ErrorModel.Clear(); ReturnData.Clear(); ErrorModel _error = new ErrorModel(); _error.Error = "2"; _error.ErrorMessage = "Some problem occurred please try again later"; _ErrorModel.Add(_error); ReturnData["ErrorDetail"] = serializer.Serialize(_ErrorModel); HttpContext.Current.Response.AppendHeader("ResponseHeader", "500"); } } } } catch (Exception ex) { _ErrorModel.Clear(); ReturnData.Clear(); ErrorModel _error = new ErrorModel(); _error.Error = "2"; _error.ErrorMessage = "Some problem occurred please try again later"; _ErrorModel.Add(_error); ReturnData["ErrorDetail"] = serializer.Serialize(_ErrorModel); HttpContext.Current.Response.AppendHeader("ResponseHeader", "500"); } return(ReturnData); }
// // GET: /Template/ public ActionResult Create(int tipstaffRecordID, int templateID) { try { //Get TipstaffRecord from warrantID TipstaffRecord tipstaffRecord = db.TipstaffRecord.Find(tipstaffRecordID); if (tipstaffRecord.caseStatus.sequence > 3) { TempData["UID"] = tipstaffRecord.UniqueRecordID; return(RedirectToAction("ClosedFile", "Error")); } //Get Template from templateID Template template = db.Templates.Find(templateID); if (template == null) { throw new FileLoadException(string.Format("No database record found for template reference {0}", templateID)); } //set fileOutput details WordFile fileOutput = new WordFile(tipstaffRecord, Server.MapPath("~/Documents/"), template); //Create XML object for Template XmlDocument xDoc = new XmlDocument(); //Merge Data xDoc.InnerXml = mergeData(template, tipstaffRecord, null); ////Save resulting document //xDoc.Save(fileOutput.fullName); //Save physical file //if (!System.IO.File.Exists(fileOutput.fullName)) throw new FileNotFoundException(string.Format("File {0} could not be created", fileOutput.fileName)); //Create and add a Document to TipstaffRecord Document doc = new Document(); doc.binaryFile = genericFunctions.ConvertToBytes(xDoc); doc.mimeType = "application/msword"; doc.fileName = fileOutput.fileName; doc.countryID = 244; //UK! doc.nationalityID = 27; doc.documentTypeID = 1; //generated doc.documentStatusID = 1; //generated doc.documentReference = template.templateName; doc.templateID = template.templateID; doc.createdOn = DateTime.Now; doc.createdBy = User.Identity.Name; tipstaffRecord.Documents.Add(doc); //Save Changes db.SaveChanges(); //Return saved document //return File(fileOutput.fullName, "application/doc", fileOutput.fileName); // return physical file return(File(doc.binaryFile, doc.mimeType, doc.fileName)); //return byte version } catch (DbEntityValidationException ex) { _logger.LogError(ex, $"DbEntityValidationException in TemplateController in Create method, for user {((CPrincipal)User).UserID}"); ErrorModel model = new ErrorModel(2); model.ErrorMessage = ex.Message; TempData["ErrorModel"] = model; return(RedirectToAction("IndexByModel", "Error", model ?? null)); } catch (Exception ex) { _logger.LogError(ex, $"Exception in TemplateController in Create method, for user {((CPrincipal)User).UserID}"); ErrorModel model = new ErrorModel(2); model.ErrorMessage = ex.Message; TempData["ErrorModel"] = model; return(RedirectToAction("IndexByModel", "Error", model ?? null)); //Note: working redirect to view with Model //Note: Working error redirect } }
public static Hashtable CompanyDetails(Hashtable ht, string Type, string Req) { try { string[] words = null; string Data = Req; ReturnData.Clear(); #region Fill if (Type == "Fill") { words = null; words = Req.Split('@'); for (int m = 0; words.Count() > m; m++) { Data = words[m].ToString(); if (Data == "Country") { _CountryModel.Clear(); ht_param.Clear(); ds = db.SysFetchDataInDataSet("[GetCountryList]", ht_param); if (ds.Tables.Count > 0) { foreach (DataRow item in ds.Tables[0].Rows) { CountryModel CountryModel_Detail = new CountryModel(); CountryModel_Detail.Name = item["NAME"].ToString(); CountryModel_Detail.COUNTRY_ID = Convert.ToInt32(item["COUNTRY_ID"].ToString()); _CountryModel.Add(CountryModel_Detail); } } ReturnData["Country"] = serializer.Serialize(_CountryModel); GetStateforDefaultCountry(_CountryModel[0].COUNTRY_ID.ToString()); } if (Data == "Edit") { _CountryModel.Clear(); ht_param.Clear(); ht_param.Add("@ID", ht["COMPANY_ID"].ToString()); ds = db.SysFetchDataInDataSet("[GetSelectedCompanyDetails]", ht_param); if (ds.Tables.Count > 0) { _companylist = ds.Tables[0].AsEnumerable() .Select(row => new CompanyModel { ID = row["ID"].ToString(), CompanyName = row["CompanyName"].ToString(), CEOName = row["CEOName"].ToString(), MobileNo = row["MobileNo"].ToString(), PhoneNo = row["PhoneNo"].ToString(), Email = row["Email"].ToString(), Password = "", Country = row["Country"].ToString(), City = row["City"].ToString(), State = row["State"].ToString(), CompanyType = row["CompanyType"].ToString(), Address = row["Address"].ToString(), WebsiteUrl = row["WebsiteUrl"].ToString(), LogoPath = row["LogoPath"].ToString(), IsActive = row["IsActive"].ToString() }).ToList(); } ReturnData["CompanyData"] = serializer.Serialize(_companylist); GetStateforDefaultCountry(_companylist[0].Country); } } } #endregion #region state if (Type == "State") { _CountryModel.Clear(); ht_param.Clear(); ht_param.Add("@COUNTRY_ID", ht["COUNTRY_ID"].ToString()); ds = db.SysFetchDataInDataSet("[GetStateList]", ht_param); if (ds.Tables.Count > 0) { foreach (DataRow item in ds.Tables[0].Rows) { CountryModel CountryModel_Detail = new CountryModel(); CountryModel_Detail.Name = item["NAME"].ToString(); CountryModel_Detail.COUNTRY_ID = Convert.ToInt32(item["LOCATION_ID"].ToString()); _CountryModel.Add(CountryModel_Detail); } } ReturnData["State"] = serializer.Serialize(_CountryModel); } #endregion #region Save if (Type == "Save") { _UserSaveModel.Clear(); ht_param.Clear(); ht_param.Add("@ID", ht["ID"]); ht_param.Add("@CompanyName", ht["CompanyName"].ToString()); ht_param.Add("@CEOName", ht["CEOName"].ToString()); ht_param.Add("@MobileNo", ht["MobileNo"].ToString()); ht_param.Add("@PhoneNo", ht["PhoneNo"].ToString()); ht_param.Add("@Email", ht["Email"].ToString()); ht_param.Add("@Password", ht["Password"].ToString()); //ht_param.Add("@Country", ht["Country"].ToString()); if (ht["Country"].ToString() == "") { ht_param.Add("@Country", DBNull.Value); } else { ht_param.Add("@Country", ht["Country"].ToString()); } //ht_param.Add("@State", ht["State"].ToString()); if (ht["State"].ToString() == "") { ht_param.Add("@State", DBNull.Value); } else { ht_param.Add("@State", ht["State"].ToString()); } ht_param.Add("@City", ht["City"].ToString()); ht_param.Add("@CompanyType", ht["CompanyType"].ToString()); ht_param.Add("@Address", ht["Address"].ToString()); ht_param.Add("@WebsiteUrl", ht["WebsiteUrl"].ToString()); ht_param.Add("@LogoPath", ht["Logo"].ToString()); ht_param.Add("@MODE", ht["MODE"].ToString()); ht_param.Add("@Login_user_ID", HttpContext.Current.Session["Login_user_ID"].ToString()); ds = db.SysFetchDataInDataSet("[INSERT_COMPANY_DETAILS]", ht_param); if (ds.Tables.Count > 0) { foreach (DataRow item in ds.Tables[0].Rows) { UserSaveModel _UserSaveModelDetails = new UserSaveModel(); _UserSaveModelDetails.CustomErrorState = item["CustomErrorState"].ToString(); _UserSaveModelDetails.CustomMessage = item["CustomMessage"].ToString(); _UserSaveModel.Add(_UserSaveModelDetails); } } ReturnData["Save"] = serializer.Serialize(_UserSaveModel); //ReturnData["Save"] = serializer.Serialize("saved successfully."); } #endregion #region Update if (Type == "Update") { _UserSaveModel.Clear(); ht_param.Clear(); ht_param.Add("@ID", ht["ID"]); ht_param.Add("@CompanyName", ht["CompanyName"].ToString()); ht_param.Add("@CEOName", ht["CEOName"].ToString()); ht_param.Add("@MobileNo", ht["MobileNo"].ToString()); ht_param.Add("@PhoneNo", ht["PhoneNo"].ToString()); ht_param.Add("@Email", ht["Email"].ToString()); ht_param.Add("@Password", ht["Password"].ToString()); //ht_param.Add("@Country", ht["Country"].ToString()); if (ht["Country"].ToString() == "") { ht_param.Add("@Country", DBNull.Value); } else { ht_param.Add("@Country", ht["Country"].ToString()); } //ht_param.Add("@State", ht["State"].ToString()); if (ht["State"].ToString() == "") { ht_param.Add("@State", DBNull.Value); } else { ht_param.Add("@State", ht["State"].ToString()); } ht_param.Add("@City", ht["City"].ToString()); ht_param.Add("@CompanyType", ht["CompanyType"].ToString()); ht_param.Add("@Address", ht["Address"].ToString()); ht_param.Add("@WebsiteUrl", ht["WebsiteUrl"].ToString()); ht_param.Add("@LogoPath", ht["Logo"].ToString()); ht_param.Add("@MODE", ht["MODE"].ToString()); ht_param.Add("@Login_user_ID", HttpContext.Current.Session["Login_user_ID"].ToString()); ds = db.SysFetchDataInDataSet("[INSERT_COMPANY_DETAILS]", ht_param); if (ds.Tables.Count > 0) { foreach (DataRow item in ds.Tables[0].Rows) { UserSaveModel _UserSaveModelDetails = new UserSaveModel(); _UserSaveModelDetails.CustomErrorState = item["CustomErrorState"].ToString(); _UserSaveModelDetails.CustomMessage = item["CustomMessage"].ToString(); _UserSaveModel.Add(_UserSaveModelDetails); } } ReturnData["Update"] = serializer.Serialize(_UserSaveModel); //ReturnData["Update"] = serializer.Serialize("updated successfully."); } #endregion _ErrorModel.Clear(); ErrorModel _error = new ErrorModel(); _error.Error = "false"; _error.ErrorMessage = "sucess"; _ErrorModel.Add(_error); ReturnData["ErrorDetail"] = serializer.Serialize(_ErrorModel); HttpContext.Current.Response.AppendHeader("ResponseHeader", "200"); } catch (Exception ex) { _ErrorModel.Clear(); ReturnData.Clear(); ErrorModel _error = new ErrorModel(); _error.Error = "true"; _error.ErrorMessage = "Some problem occurred please try again later"; _ErrorModel.Add(_error); ReturnData["ErrorDetail"] = serializer.Serialize(_ErrorModel); HttpContext.Current.Response.AppendHeader("ResponseHeader", "500"); } return(ReturnData); }
public GetTableResponseModel addTable(AddTableRequestModel addTableRequestModel, out ErrorModel errorModel) { errorModel = null; GetTableResponseModel getTableResponseModel = null; SqlConnection connection = null; try { using (connection = new SqlConnection(Database.getConnectionString())) { SqlCommand command = new SqlCommand(SqlCommands.SP_addTable, connection); command.CommandType = System.Data.CommandType.StoredProcedure; #region Command Parameters command.Parameters.AddWithValue("capacity", addTableRequestModel.capacity); #endregion connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { if (reader.isColumnExists("ErrorCode")) { errorModel = new ErrorModel(); errorModel.ErrorCode = reader["ErrorCode"].ToString(); errorModel.ErrorMessage = reader["ErrorMessage"].ToString(); } else { getTableResponseModel = new GetTableResponseModel(); getTableResponseModel.tableId = Convert.ToInt32(reader["tableId"]); getTableResponseModel.capacity = Convert.ToInt32(reader["capacity"]); getTableResponseModel.availability = Convert.ToBoolean(reader["availability"]); } command.Dispose(); return(getTableResponseModel); } return(null); } } catch (Exception exception) { errorModel = new ErrorModel(); errorModel.ErrorMessage = exception.Message; return(null); } finally { if (connection != null) { connection.Close(); } } }
public EditProfileResponseModel editProfile(EditProfileRequestModel editProfileRequestModel, out ErrorModel errorModel) { errorModel = null; User user = new User(); try { return(user.editProfile(editProfileRequestModel, out errorModel)); } catch { return(null); } }
public GetTableResponseModel deleteorModifyTable(TableDeleteRequestModel tableDeleteRequest, out ErrorModel errorModel) { errorModel = null; GetTableResponseModel getTableResponse = null; SqlConnection connection = null; try { using (connection = new SqlConnection(Database.getConnectionString())) { SqlCommand command = new SqlCommand(SqlCommands.SP_deleteorModifyTable, connection); command.CommandType = System.Data.CommandType.StoredProcedure; #region Commands Parameters command.Parameters.Add(new SqlParameter("@isDelete", System.Data.SqlDbType.Bit)); command.Parameters["@isDelete"].Value = tableDeleteRequest.isDelete; command.Parameters.Add(new SqlParameter("@tableId", System.Data.SqlDbType.Int)); command.Parameters["@tableId"].Value = tableDeleteRequest.tableId; #endregion connection.Open(); SqlDataReader reader = command.ExecuteReader(); getTableResponse = new GetTableResponseModel(); if (reader.Read()) { if (reader.isColumnExists("ErrorCode")) { errorModel = new ErrorModel(); errorModel.ErrorCode = reader["ErrorCode"].ToString(); errorModel.ErrorMessage = reader["ErrorMessage"].ToString(); } else { getTableResponse.tableId = Convert.ToInt32(reader["TableId"].ToString()); getTableResponse.capacity = Convert.ToInt32(reader["Capacity"].ToString()); getTableResponse.availability = Convert.ToBoolean(reader["Table Active"].ToString()); } } command.Dispose(); return(getTableResponse); } } catch (Exception exception) { errorModel = new ErrorModel(); errorModel.ErrorMessage = exception.Message; return(null); } finally { if (connection != null) { connection.Close(); } } }
public async Task <UserValidateDto> Login(UserValidateInputDto inputDto) { var user = await _userRepository.FetchAsync(x => new { x.Password, x.Salt, x.Name, x.Email, x.RoleId, x.Account, x.ID, x.Status }, x => x.Account == inputDto.Account); var log = new SysLoginLog() { ID = new Snowflake(1, 1).NextId(), Account = inputDto.Account, CreateTime = DateTime.Now, Device = "web", RemoteIpAddress = _userContext.RemoteIpAddress, Message = string.Empty, Succeed = false, UserId = user?.ID, UserName = user?.Name, }; if (user == null) { var errorModel = new ErrorModel(ErrorCode.NotFound, "用户名或密码错误"); log.Message = JsonConvert.SerializeObject(errorModel); throw new BusinessException(errorModel); } else { if (user.Status != 1) { var errorModel = new ErrorModel(ErrorCode.TooManyRequests, "账号已锁定"); log.Message = JsonConvert.SerializeObject(errorModel); await _loginLogRepository.InsertAsync(log); throw new BusinessException(errorModel); } var logins = await _loginLogRepository.SelectAsync(5, x => new { x.ID, x.Succeed, x.CreateTime }, x => x.UserId == user.ID, x => x.ID, false); var failLoginCount = logins.Count(x => x.Succeed == false); if (failLoginCount == 5) { var errorModel = new ErrorModel(ErrorCode.TooManyRequests, "连续登录失败次数超过5次,账号已锁定"); log.Message = JsonConvert.SerializeObject(errorModel); await _userRepository.UpdateAsync(new SysUser() { ID = user.ID, Status = 2 }, x => x.Status); throw new BusinessException(errorModel); } if (HashHelper.GetHashedString(HashType.MD5, inputDto.Password, user.Salt) != user.Password) { var errorModel = new ErrorModel(ErrorCode.NotFound, "用户名或密码错误"); log.Message = JsonConvert.SerializeObject(errorModel); await _loginLogRepository.InsertAsync(log); throw new BusinessException(errorModel); } if (string.IsNullOrEmpty(user.RoleId)) { var errorModel = new ErrorModel(ErrorCode.Forbidden, "未分配任务角色,请联系管理员"); log.Message = JsonConvert.SerializeObject(errorModel); await _loginLogRepository.InsertAsync(log); throw new BusinessException(errorModel); } } log.Message = "登录成功"; log.Succeed = true; await _loginLogRepository.InsertAsync(log); return(_mapper.Map <UserValidateDto>(user)); }
protected void DisplayError(string errorMessage) { TempData["Error"] = new ErrorModel { Message = errorMessage }; }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var endpoint = context.GetEndpoint(); if (endpoint == null) { await _next(context); return; } var requiredValues = ((RouteEndpoint)endpoint).RoutePattern.RequiredValues; if (requiredValues.Count() == 0) { await _next(context); return; } var controller = requiredValues["controller"]?.ToString().ToLower(); var action = requiredValues["action"]?.ToString().ToLower(); if (controller.IsNullOrWhiteSpace()) { await _next(context); return; } //判断Api是否需要认证 bool isNeedAuthentication = endpoint.Metadata.GetMetadata <IAllowAnonymous>() == null ? true : false; //Api不需要认证 if (isNeedAuthentication == false) { //如果是调用登录API、刷新token的Api,并且调用成功,需要保存accesstoken到cache if (controller == "account" && (action == "login" || action == "refreshaccesstoken")) { await SaveToken(context, _next); return; } //其他Api await _next(context); return; } //API需要认证 if (isNeedAuthentication == true) { //是修改密码,需要从cahce移除Token if (controller == "account" && action == "password") { await _next(context); if (StatusCodeChecker.Is2xx(context.Response.StatusCode)) { await RemoveToken(context); } return; } //是注销,需要判断是否主动注销 if (controller == "account" && action == "logout") { await _next(context); if (StatusCodeChecker.Is2xx(context.Response.StatusCode)) { //主动注销,从cahce移除token if (await CheckToken(context) == true) { await RemoveToken(context); } return; } } } //API需要认证,并且验证成功,需要检查accesstoken是否在缓存中。 if (StatusCodeChecker.Is2xx(context.Response.StatusCode)) { //需要先检查token是否是最新的,再走其它中间件 var result = await CheckToken(context); if (result) { await _next(context); return; } else { context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; var message = new ErrorModel(HttpStatusCode.Unauthorized, "账号已经在其他地方登录"); context.Response.ContentType = "application/json;charset=utf-8"; await context.Response.WriteAsync(message.ToString()); return; } } await _next(context); return; }
protected void AddValidationResult(string summaryErrorMessage, InvalidValue[] invalidValues) { ViewData["Error"] = new ErrorModel { Message = summaryErrorMessage }; AddValidationResults(invalidValues); }
public BusinessException(ErrorModel errorModel) : base(JsonConvert.SerializeObject(errorModel, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() })) { base.HResult = (int)errorModel.StatusCode; }
public ErrorModelTests() { model = new(); }
public ActionResult Error(string err) { var error = new ErrorModel { ErrorMessage = err }; return View(error); }
public List <eOfficeEmployee> AdminEmployeeGet(int?branchId, string titleCode, int?status, string userRequest, out ErrorModel errorModel) { errorModel = new ErrorModel(); List <eOfficeEmployee> ret = null; try { string stn = string.Format("{0}.{1}", GlobalInfo.PKG_TMS_SYSTEM, "sp_get_employee"); var it = new { BranchId = branchId, TitleCode = titleCode, Status = status }; string json = JsonHelper.SerializeAll(it); DBHelper db = new DBHelper(stn, userRequest) .addParamOutput("oResult") .addParam("pUserRequest", userRequest) .addParam("pJson", json) .ExecuteStore(); DataTable dt = db.getDataTable(); ret = DataUtils.ConvertDataList <eOfficeEmployee>(dt); errorModel.ErrorCode = ret != null ? 0 : 1; errorModel.ErrorMsg = errorModel.ErrorCode == 0 ? "Success" : "fail"; } catch (Exception ex) { errorModel.ErrorCode = -1; errorModel.ErrorMsg = ex.Message; errorModel.ErrorDetail = ex.ToString(); LogHelper.Current.WriteLogs(ex.ToString(), "AdminService.AdminEmployeeGet", userRequest); } return(ret); }
public ReserveTableResponseModel reserveTable(ReserveTableRequestModel reserveTableRequestModel, out ErrorModel errorModel) { errorModel = null; ReserveTableResponseModel response = null; SqlConnection connection = null; try { using (connection = new SqlConnection(Database.getConnectionString())) { SqlCommand command = new SqlCommand(SqlCommands.SP_reserveTable, connection); command.CommandType = System.Data.CommandType.StoredProcedure; #region Query Parameters command.Parameters.AddWithValue("@tableId", reserveTableRequestModel.tableId); command.Parameters.AddWithValue("@reservationDate", reserveTableRequestModel.reservationDate); command.Parameters.AddWithValue("@reservedBy", reserveTableRequestModel.reservedBy); command.Parameters.AddWithValue("@numberOfPeople", reserveTableRequestModel.numberOfPeople); command.Parameters.AddWithValue("@startTime", reserveTableRequestModel.startTime); command.Parameters.AddWithValue("endTime", reserveTableRequestModel.endTime); #endregion connection.Open(); SqlDataReader reader = command.ExecuteReader(); response = new ReserveTableResponseModel(); while (reader.Read()) { if (reader.isColumnExists("ErrorCode")) { errorModel = new ErrorModel(); errorModel.ErrorCode = reader["ErrorCode"].ToString(); errorModel.ErrorMessage = reader["ErrorMessage"].ToString(); } else { response.StatusCode = reader["StatusCode"].ToString(); response.StatusMessage = reader["StatusMessage"].ToString(); } } command.Dispose(); connection.Close(); } return(response); } catch (Exception exception) { errorModel = new ErrorModel(); errorModel.ErrorMessage = exception.Message; return(null); } finally { if (connection != null) { connection.Close(); } } }
public ActionResult Index(ErrorModel em) { ViewData = new ViewDataDictionary <ErrorModel>(em); return(View()); }
public ErrorDialog() { InitializeComponent(); ModelServiceLocator serviceLocator = this.FindResource<ModelServiceLocator>("serviceLocator"); this.model = serviceLocator.ErrorModel; }
public ActionResult AccessDenied() => View("Error", ErrorModel.CreateById(403));