private BaseResponseModel CreateLinksForRepository(BaseResponseModel model) { string controllerName = (nameof(RepositoryController)).Replace("Controller", ""); if (!HttpContext.Request.RouteValues.TryGetValue("version", out var version)) { version = ApiVersion.Default; } if (!string.IsNullOrEmpty(_linkGenerator.GetPathByAction(HttpContext, nameof(GetById), controllerName, new { version = version.ToString() }))) { model.Links.Add( new LinkModel { Href = _linkGenerator.GetPathByAction(HttpContext, nameof(GetById), controllerName, new { version = version.ToString() }), Method = HttpMethod.Get.ToString(), Description = "Get Repository's information" }); } model.Links.Add( new LinkModel { Href = _linkGenerator.GetPathByAction(HttpContext, nameof(GetListById), controllerName, new { version = version.ToString() }), Method = HttpMethod.Get.ToString(), Description = "Get Repository list" }); return(model); }
public async Task <ActionResult <AspNetRolesReadModel> > Add([FromBody] AspNetUsersCreateModel createModel, CancellationToken cancellationToken) { var user = new NesopsUser { UserName = createModel.UserName }; var userRoles = new List <string>() { "ActiveUser" }; var result = await _authorizeService.CreateUserAsync(user, createModel.Password, userRoles); if (result.Succeeded) { return(Ok(new BaseResponseModel <object> { message = "Create User Successful", code = 200 })); } var responseModel = new BaseResponseModel <object> { message = "Create User Fail", code = 400 }; foreach (var err in result.Errors) { responseModel.SetError(err.Code, err.Description); } return(BadRequest(responseModel)); }
public static IActionResult ToActionResult(this BaseResponseModel responseModel) { return(new ObjectResult(responseModel) { StatusCode = responseModel.StatusCode }); }
public IActionResult Login([FromBody] LoginRequestModel model) { var result = new BaseResponseModel(); if (!ModelState.IsValid) { result.IsError = true; result.ErrorDetail = ModelState.FillModelStateError(); return(Ok(result)); } var user = _userRepository.LoginControl(model.Key, model.Password, _cryptoService); if (user == null) { result.IsError = true; result.ErrorDetail = "Login error (invalid Password,Mail or Username)"; return(Ok(result)); } result.Data = new { Token = _tokenService.GenerateToken(user, _appSettings) }; return(Ok(result)); }
public async Task <BaseResponseModel> Drop(int id) { BaseResponseModel response = new BaseResponseModel(); AffectedField affectedField = await Load(id, response); if (affectedField != null) { if (affectedField.Metric.Count == 0) { Database.AffectedField.Remove(affectedField); await Database.SaveChangesAsync(); response.Message = "Affected field was successfully deleted!"; } else { response.Success = false; response.Message = "Cannot delete affected field, because some metrics use this field!"; } } return(response); }
public async void SaveShopping(SaveShoppingRequest saveShoppingRequest, Action success, Action <BaseResponseModel> failed) { bool IsNetwork = true;//await DependencyService.Get<IMediaService>().CheckNewworkConnectivity(); if (IsNetwork) { var url = string.Format("{0}saveshoppinglist.php", _settingsManager.ApiHost); await Task.Factory.StartNew(() => { var result = _apiProvider.Post <BaseResponseModel, SaveShoppingRequest>(url, saveShoppingRequest).Result; if (result.IsSuccessful) { if (success != null) { saveShoppingResponse = result.Result; success.Invoke(); } } else { failed.Invoke(result.Result); } }); } else { UserDialogs.Instance.HideLoading(); UserDialogs.Instance.Alert(error, null, "OK"); } }
private static Task HandleExceptionAsync(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; context.Response.StatusCode = 200; var result = new BaseResponseModel { Header = new ResponseHeader { ResultCode = "4953", Message = "A system error has occurred" } }; var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = new List <JsonConverter> { new StringEnumConverter() }, Formatting = Formatting.Indented }; return(context.Response.WriteAsync(JsonConvert.SerializeObject(result, settings))); }
public async Task <BaseResponseModel> Edit(AffectedFieldModel request) { BaseResponseModel response = new BaseResponseModel(); if (request.Validate()) { AffectedField affectedField = await Load(request.Id, response); if (affectedField != null) { affectedField.Name = request.Name; affectedField.Description = request.Description; await Database.SaveChangesAsync(); response.Message = "Affected field was successfully edited!"; } } else { response.Success = false; response.Message = "Some of the required properties is not present!"; } return(response); }
private string UpdateResponse(object data, int ID) { BaseResponseModel response = jsonHelper.FromJson <BaseResponseModel>(data.ToString()); if (!string.IsNullOrEmpty(jsonHelper.ErrorMessage)) { return(jsonHelper.ErrorMessage); } string result = "Error - No changes made"; List <BaseResponseModel> existingResponse = responseService.GetResponses(); BaseResponseModel responseMatch = new BaseResponseModel(); if (existingResponse != null) { responseMatch = existingResponse.Find(o => o.ResponseID.Equals(ID)); if (responseMatch != null) //If response is found { response.ResponseID = responseMatch.ResponseID; if (responseService.UpdateResponse(response)) { result = "Successfully updated response"; } } } return(result); }
public async Task <BaseResponseModel> CreateSnapshot(int id, int projectMetricId, ProjectMetric projectMetric = null) { BaseResponseModel response = new BaseResponseModel { Message = "Creating of a snapshot ended successfully. For more detailed result check project metric log." }; try { projectMetric = projectMetric ?? await _projectMetricService.Load(projectMetricId, response); if (projectMetric != null) { await _jazzService.CreateSnapshot(projectMetric); await Database.SaveChangesAsync(); } } catch (Exception e) { response.Success = false; response.Message = "Creating of a snapshot was not successfull! Please try again later."; await _helperService.SaveErrorToDB(new AppErrorModel(e, message : "task - all projects", module : "ProjectService", function : "CreateSnapshots")); projectMetric.ProjectMetricLog.Add(new ProjectMetricLog($"Within processing of snapshot for project metric #{projectMetric.Id} occured and error!")); } return(response); }
public async Task <BaseResponseModel> Edit(ProjectModel request) { BaseResponseModel response = new BaseResponseModel(); if (request.Validate()) { Project project = await Load(request.Id, response); if (project != null) { project.Name = request.Name; project.Description = request.Description; await Database.SaveChangesAsync(); response.Message = "Project was successfully edited!"; } } else { response.Success = false; response.Message = "Some of the required properties is not present!"; } return(response); }
/// <summary> /// ulozi chybu do db, pokud zapsani do DB selze, zasle mail s chybou na email dany dle DB /// </summary> /// <param name="value">prijaty objekt, obsahujici info o chybe</param> /// <param name="exceptionRound">opakovany zapis chyby po vyjimce</param> /// <returns>objekt s informaci o vysledku</returns> public async Task <BaseResponseModel> SaveErrorToDB(AppErrorModel value, int exceptionRound = 1) { BaseResponseModel model = new BaseResponseModel(); try { await _appErrorService.Create(value); } catch (Exception e) { model.Success = false; model.Message = "Error wasn't processed."; if (exceptionRound < 3) //spadne to 3x? tak do emailu a pokud ani to nepujde, tak do souboru { await SaveErrorToDB(value, exceptionRound + 1); } else { await _emailService.SendEmail("Error occured at logging to DB", $"Exception with log:{Environment.NewLine}\n{e.ParseException()}{Environment.NewLine}\nOriginal exception (JSON):{Environment.NewLine}\n{JsonConvert.SerializeObject(value)}", await _settingService.GetSettingValue(ErrorEmailScope, ErrorEmailName)); } } return(model); }
private async void OnDownloadButton_Clicked(object obj) { _isEnabled = true; var isDataDownloaded = Prefs.GetCurrentState("isDataDownloaded"); if (isDataDownloaded != null) { entireResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <BaseResponseModel>(isDataDownloaded); DownloadButtonText = "ALREADY DOWNLOADED"; } else { IsVisibled = true; if (CrossConnectivity.Current.IsConnected) { await GetDownloadData(); } else { IsVisibled = false; await App.Current.MainPage.DisplayAlert("Alert", "Check your Internet Connection", "ok"); } } NotifyPropertyChanged(); }
public BaseResponseModel Delete(int id) { var vm = new BaseResponseModel(); // Get existing user var user = UserService.GetUserById(id); if (user == null) { throw new HttpException(404, "User not found."); } // Check permissions if (!CurrentUser.HasPermission(Permission.EditUsers)) { throw new HttpException(401, "You do not have permissions to complete this action."); } UserService.DeleteUser(user); LogService.CreateLog(new Log { Category = LogCategory.Application, IpAddress = GetClientIp(ControllerContext.Request), User = CurrentUser, Level = LogLevel.Info, Message = "User " + user.Email + " (ID #" + user.Id + ") was deleted." }); return(new BaseResponseModel { Success = true }); }
public async Task <BaseResponseModel> PartialEdit(int id, List <PatchModel> request) { BaseResponseModel response = new BaseResponseModel(); AppError appError = await Load(id, response); if (appError != null) { foreach (var item in request) { if (string.Compare(item.PropertyName, "solved", true) == 0) { appError.Solved = Convert.ToBoolean(item.Value); } else if (string.Compare(item.PropertyName, "deleted", true) == 0) { appError.Deleted = Convert.ToBoolean(item.Value); } } await Database.SaveChangesAsync(); response.Message = "App error was successfully edited!"; } return(response); }
public async Task <BaseResponseModel> Edit(UserModel request) { BaseResponseModel response = new BaseResponseModel(); if (request.ValidateEdit()) { if (ValidateEmail(request.Email, response) && await CheckLanguage(request.LanguageId, response)) { User user = await Load(request.Id, response); if (user != null) { user.FirstName = request.Firstname; user.LastName = request.Lastname; user.Email = request.Email; user.UseLdaplogin = request.UseLdaplogin; user.LdapUrl = request.UseLdaplogin ? request.LdapUrl : null; user.LanguageId = request.LanguageId; await Database.SaveChangesAsync(); response.Message = "User was successfully edited!"; } } } else { response.Success = false; response.Message = "Some of the required properties is not present!"; } return(response); }
private BaseResponseModel ValidationAuthor(AuthorModel author) { BaseResponseModel report = new BaseResponseModel(); if (author == null) { report.Message.Add("Author model is empty."); return(report); } if (string.IsNullOrEmpty(author.Name) || string.IsNullOrWhiteSpace(author.Name)) { report.Message.Add("Author name is empty."); return(report); } if (author.DateBirth >= author.DateDeath) { report.Message.Add("Invalid dates range."); return(report); } report.IsValid = true; return(report); }
public ResponseTokenModel Login(RequestLoginModel request) { try { string result = HttpUtils.PostRequest(AppConfigMoel.URL + ConstantsValue.HTTP_LOGIN_URI, JsonConvert.SerializeObject(request)); BaseResponseModel responseModel = JsonConvert.DeserializeObject <BaseResponseModel>(result); if (responseModel != null) { if (responseModel.code.Equals("200")) { ResponseTokenModel response = JsonConvert.DeserializeObject <ResponseTokenModel>(responseModel.data.ToString()); return(response); } else { return(null); } } return(null); } catch (Exception) { throw; } }
public BaseController(ILogger <BaseController> logger, IUserIdentity _userIdentity) { result = new BaseResponseModel(); ds = new DataSeed(logger); _logger = logger; userIdentity = _userIdentity; }
public async Task <HttpResponseMessage> Payment([FromBody] AccrualLoanModel model) { if (CurrentUser.UserData.UserType == Common.Enum.Enum.UserType.Membership) { var orginalModel = _paymentSystemService.GetAccrualLoanById(model.Id); if (orginalModel.Membership.Id != CurrentUser.UserData.Id) { var responseModel = new BaseResponseModel { ReturnCode = (int)Active.False, Message = "You cannot pay another member's bill!", }; var dataAsJson = JsonConvert.SerializeObject(responseModel, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var response = Request.CreateResponse(HttpStatusCode.Unauthorized); response.Content = new StringContent(dataAsJson, Encoding.UTF8, "application/json"); return(response); } } model.CreatedBy = CurrentUser.Id; var result = _paymentSystemService.Payment(model); return(await this.ReturnSuccessModel(result)); }
public List <ResponseUserInfoModel> SearchUser(RequestUserModel request) { try { string url = AppConfigMoel.URL + ConstantsValue.HTTP_SEARCH_USER_RUI; string str = url + "?name={0}&controllerCode={1}&payStatus={2}"; str = String.Format(str, request.name, request.controllerCode, request.status); string result = HttpUtils.GetRequest(str, AppConfigMoel.token); BaseResponseModel responseModel = JsonConvert.DeserializeObject <BaseResponseModel>(result); if (responseModel != null) { if (responseModel.code.Equals("200")) { var arrdata = Newtonsoft.Json.Linq.JArray.Parse(responseModel.data.ToString()); List <ResponseUserInfoModel> obj2 = arrdata.ToObject <List <ResponseUserInfoModel> >(); // List<ResponseUserInfoModel> obj2 = new List<ResponseUserInfoModel>(); // obj2.Add(new ResponseUserInfoModel()); Console.Write("11"); return(obj2); } else { return(null); } } return(null); } catch (Exception) { throw; } }
private BaseResponseModel CreateLinksForIdentity(BaseResponseModel model) { var controllerName = nameof(IdentityController) .Replace("Controller", ""); if (!HttpContext.Request.RouteValues.TryGetValue("version", out var version)) { version = ApiVersion.Default; } model.Links.Add( new LinkModel { Href = _linkGenerator.GetPathByAction( HttpContext, nameof(GetToken), controllerName, new { version = version?.ToString() } ), Method = HttpMethod.Get.ToString(), Description = "Get Identity's information" }); return(model); }
private async Task <bool> DeleteCSV(int ID) { bool result = false; string fileName = null; BaseResponseModel CSVResponse = responseService.GetSurveyFilename(ID); if (CSVResponse != null) { fileName = CSVResponse.ResponseCSV.Split("/").Last(); } try { CloudAppendBlob CSV = CONTAINER.GetAppendBlobReference(fileName); if (CSV != null) { await CSV.DeleteAsync(); result = true; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception Caught - " + ex.Message); result = false; } return(result); }
public async Task <BaseResponseModel> Drop(int id) { BaseResponseModel response = new BaseResponseModel(); ProjectMetric projectMetric = await Load(id, response); if (projectMetric != null) { foreach (var item in projectMetric.ProjectMetricSnapshot) { Database.ProjectMetricColumnValue.RemoveRange(item.ProjectMetricColumnValue); } Database.ProjectMetricLog.RemoveRange(projectMetric.ProjectMetricLog); Database.ProjectMetricSnapshot.RemoveRange(projectMetric.ProjectMetricSnapshot); Database.ProjectMetric.Remove(projectMetric); await Database.SaveChangesAsync(); response.Message = "Project metric was successfully deleted!"; } return(response); }
public List <ResponseUserInfoModel> GetAllUsers() { try { string url = AppConfigMoel.URL + ConstantsValue.HTTP_SEARCH_USER_URI; url = url + "?name=&controllerCode=&payStatus="; string result = HttpUtils.GetRequest(url, AppConfigMoel.token); BaseResponseModel responseModel = JsonConvert.DeserializeObject <BaseResponseModel>(result); if (responseModel != null) { if (responseModel.code.Equals("200")) { var arrdata = Newtonsoft.Json.Linq.JArray.Parse(responseModel.data.ToString()); List <ResponseUserInfoModel> obj2 = arrdata.ToObject <List <ResponseUserInfoModel> >(); return(obj2); } else { return(null); } } return(null); } catch (Exception) { throw; } }
private BaseResponseModel ValidationPrintingEdition(PrintingEditionModel printingEdition) { BaseResponseModel report = new BaseResponseModel(); if (printingEdition == null) { report.Message.Add(_sendNullMsg); } if (string.IsNullOrEmpty(printingEdition.Name) || string.IsNullOrWhiteSpace(printingEdition.Name)) { report.Message.Add(_titleOfPublicationMsg); } if (printingEdition.Price < 0) { report.Message.Add(_negativePriceMsg); } if (!Enum.IsDefined(typeof(Status), printingEdition.Status)) { report.Message.Add(_StatusMsg); } if (!Enum.IsDefined(typeof(Currency), printingEdition.Currency)) { report.Message.Add(_currencyMsg); } if (!Enum.IsDefined(typeof(Types), printingEdition.Type)) { report.Message.Add(_typeMsg); } return(report); }
public ResponseInformationModel GetInformation() { try { string result = HttpUtils.GetRequest(AppConfigMoel.URL + ConstantsValue.HTTP_INFORMATION_GET, AppConfigMoel.token); BaseResponseModel responseModel = JsonConvert.DeserializeObject <BaseResponseModel>(result); if (responseModel != null) { if (responseModel.code.Equals("200")) { ResponseInformationModel response = JsonConvert.DeserializeObject <ResponseInformationModel>(responseModel.data.ToString()); return(response); } else { return(null); } } return(null); } catch (Exception) { throw; } }
public async Task <BaseResponseModel> Edit(MetricTypeModel request) { BaseResponseModel response = new BaseResponseModel(); if (request.Validate()) { MetricType metricType = await Load(request.Id, response); if (metricType != null) { metricType.Name = request.Name; metricType.Description = request.Description; await Database.SaveChangesAsync(); response.Message = "Metric type was successfully edited!"; } } else { response.Success = false; response.Message = "Some of the required properties is not present!"; } return(response); }
public async Task <BaseResponseModel> Drop(int id) { BaseResponseModel response = new BaseResponseModel(); MetricType metricType = await Load(id, response); if (metricType != null) { if (metricType.Metric.Count == 0) { Database.MetricType.Remove(metricType); await Database.SaveChangesAsync(); response.Message = "Metric type was successfully deleted!"; } else { response.Success = false; response.Message = "Cannot delete metric type, because some metrics use this type!"; } } return(response); }
public async Task <BaseResponseModel> Drop(int id) { BaseResponseModel response = new BaseResponseModel(); Project project = await Load(id, response, true, false); if (project != null) { if (project.ProjectMetric.Count == 0) { Database.ProjectUser.RemoveRange(project.ProjectUser); Database.Project.Remove(project); await Database.SaveChangesAsync(); response.Message = "Project was successfully deleted!"; } else { response.Success = false; response.Message = "Cannot delete project, because this project defined has metrics!"; } } return(response); }
/// <summary></summary> /// <param name="JsonData"></param> /// <param name="resultEntity"></param> /// <returns></returns> protected bool Vertify(string JsonData, BaseResponseModel resultEntity) { if (ValidateRequest(JsonData, resultEntity) == true) //签名验证 { if (ModelVerification() == true) { return true; } else { resultEntity._StatusCode = TripEBuy.Common.StatusCode.SYSTEM_EXCEPTION; resultEntity._StatusCode.Description = ValidateFailMessage(); return false; } } else { resultEntity._StatusCode = TripEBuy.Common.StatusCode.SIGN_EXCEPTION; return false; } }
/// <summary> /// 验证 /// </summary> /// <param name=""></param> /// <param name="dicParams"></param> /// <param name="resultEntity"></param> /// <returns></returns> protected bool Vertify(Dictionary<string, string> dicParams, BaseResponseModel resultEntity) { bool result = true; if (dicParams == null || dicParams.Count == 0) { result = false; resultEntity._StatusCode = TripEBuy.Common.StatusCode.SYSTEM_EXCEPTION; } else { SortedDictionary<string, string> sortedDicParams = new SortedDictionary<string, string>(); string sign = string.Empty; foreach (string key in dicParams.Keys) { if (key != "sign") { sortedDicParams.Add(key, dicParams[key].ToString2()); } else { sign = dicParams[key].ToString2(); } } string linkString = string.Empty; string localSign = TripEBuy.Common.Sign.GetSign(sortedDicParams, ref linkString); if (localSign != sign.ToUpper().Trim()) { //验签失败 result = false; //resultEntity.ReturnCode = "SIGN ERROR"; //resultEntity.ReturnMsg = "签名错误!"; resultEntity._StatusCode = TripEBuy.Common.StatusCode.SYSTEM_EXCEPTION; } } return result; }
/// <summary></summary> /// <param name="JsonData"></param> /// <param name="resultEntity"></param> /// <returns></returns> protected bool ValidateRequest(string JsonData, BaseResponseModel resultEntity) { if (ConfigHelper.GetInstance().SignVerificationInd == "N") { return true; } Dictionary<string, object> dicParams = new Dictionary<string, object>(); dicParams = ConvertHelper.ToDictionary(JsonData); return Vertify(dicParams, resultEntity); }
/// <summary></summary> /// <param name="context"></param> /// <param name="resultEntity"></param> /// <returns></returns> protected bool Vertify(HttpControllerContext context, BaseResponseModel resultEntity) { if (ConfigHelper.GetInstance().SignVerificationInd == "N") { return true; } Dictionary<string, string> dicParams = new Dictionary<string, string>(); if (context.Request.Method == HttpMethod.Get) { List<KeyValuePair<string, string>> list = context.Request.GetQueryNameValuePairs().ToList(); for (int i = 0; i < list.Count; i++) { dicParams.Add(list[i].Key, list[i].Value); } } else if (context.Request.Method == HttpMethod.Post) { HttpContextBase contextbase = (HttpContextBase)context.Request.Properties["MS_HttpContext"]; if (contextbase.Request.Form != null) { foreach (string key in contextbase.Request.Form.AllKeys) { dicParams.Add(key, contextbase.Request.Form[key]); } } } return Vertify(dicParams, resultEntity); }