예제 #1
0
        private static Task HandleException(HttpContext context, Exception exception)
        {
            HttpStatusCode code;
            object         response = exception.Message;

            switch (exception)
            {
            case EntityValidationException _:
                code     = HttpStatusCode.BadRequest;
                response = new ErrorMessageModel($"Requisição inválida: {exception.Message}");
                break;

            case NotFoundException _:
                code     = HttpStatusCode.NotFound;
                response = new ErrorMessageModel("Registro não encontrado");
                break;

            default:
                code     = HttpStatusCode.InternalServerError;
                response = new ErrorMessageModel($"Erro: {exception.Message}");
                break;
            }

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = Convert.ToInt32(code);

            return(context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            })));
        }
        private async Task <ExcelResponseModel> GetValidationResults(string fileName)
        {
            var data = await _excelReader.ReadFromExcel(fileName);

            List <ErrorMessageModel> errorMessageModels = new List <ErrorMessageModel>();

            if (data == null)
            {
                throw new InvalidOperationException();
            }

            // performing the validation here

            if (data.Rows.Count == 0)
            {
                throw new IndexOutOfRangeException();
            }

            int row = 0;

            foreach (DataRow dataRow in data.Rows)
            {
                var errorMessageModel = new ErrorMessageModel(row);

                if (dataRow[0].ToString() == "vimal")
                {
                    errorMessageModel.ErrorMessagees.Add("Colum [0] can't have value vimal");
                }
                errorMessageModels.Add(errorMessageModel);
                row++;
                /// contine with other checks over here;
            }
            return(new ExcelResponseModel(errorMessageModels));
        }
        /// <summary>
        /// 请求获取access_token
        /// </summary>
        /// <param name="appid">微信公众号的appid</param>
        /// <param name="appSecret">微信公众号的appSecret</param>
        /// <returns></returns>
        public static CommonMessage TryGetAccessToken(string appid, string appSecret)
        {
            var requstAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";

            requstAccessTokenUrl = string.Format(requstAccessTokenUrl, appid, appSecret);
            var           jsonResult    = HttpHelper.GetWebContent(requstAccessTokenUrl);
            CommonMessage commonMessage = null;

            if (jsonResult.Contains("errcode"))//出现错误
            {
                ErrorMessageModel errorModel = JsonHelper.DeserializeJsonToObject <ErrorMessageModel>(jsonResult);
                if (null != errorModel)
                {
                    commonMessage = CommonMessage.Error(CodeMessageEnum.FaildGotAccessToken + ",原因:" + errorModel.Errmsg, (int)StateCode.InvalidCode);
                }
                else
                {
                    commonMessage = CommonMessage.Error(CodeMessageEnum.FaildGotAccessToken);
                }
            }
            else
            {
                ShareAccessToken shareAccessTokenModel = JsonHelper.DeserializeJsonToObject <ShareAccessToken>(jsonResult);
                if (null != shareAccessTokenModel)
                {
                    SessionHelper.SetSession(CodeMessageEnum.ShareAuthorizationAccessToken, shareAccessTokenModel.Access_token, true);
                    commonMessage = CommonMessage.Success(shareAccessTokenModel.Access_token);
                }
                else
                {
                    commonMessage = CommonMessage.Error("反序列化对象中出现错误");
                }
            }
            return(commonMessage);
        }
        /// <summary>
        /// 请求获取JspaiTicket
        /// </summary>
        /// <param name="access_token">调用微信获取到的token</param>
        /// <returns></returns>
        public static CommonMessage TryGetJsApiTicket(string access_token)
        {
            var requstJsApiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi";

            requstJsApiUrl = string.Format(requstJsApiUrl, access_token);
            var           jsonResult    = HttpHelper.GetWebContent(requstJsApiUrl);
            CommonMessage commonMessage = null;

            if (jsonResult.Contains("ticket"))//出现错误
            {
                ShareJsTicket jsApiTicketModel = JsonHelper.DeserializeJsonToObject <ShareJsTicket>(jsonResult);
                if (null != jsApiTicketModel)
                {
                    SessionHelper.SetSession(CodeMessageEnum.ShareJsapiTicket, jsApiTicketModel.Ticket, true);
                    commonMessage = CommonMessage.Success(jsApiTicketModel.Ticket);
                }
                else
                {
                    commonMessage = CommonMessage.Error("反序列化对象中出现错误");
                }
            }
            else
            {
                ErrorMessageModel errorModel = JsonHelper.DeserializeJsonToObject <ErrorMessageModel>(jsonResult);
                if (null != errorModel)
                {
                    commonMessage = CommonMessage.Error(CodeMessageEnum.FaildGotJsApiTicket + ",原因:" + errorModel.Errmsg, (int)StateCode.InvalidCode);
                }
                else
                {
                    commonMessage = CommonMessage.Error(CodeMessageEnum.FaildGotJsApiTicket);
                }
            }
            return(commonMessage);
        }
예제 #5
0
        /// <summary>
        /// 无效访问,请求参数错误等
        /// </summary>
        /// <returns></returns>
        public IActionResult Bad(string message = "")
        {
            var error = new ErrorMessageModel();

            error.Title   = "500";
            error.Message = string.IsNullOrWhiteSpace(message) ? "无效请求,请从正规途径访问" : message;
            return(RedirectToAction("Error", "Home", error));
        }
예제 #6
0
        /// <summary>
        /// 请求的数据不存在
        /// </summary>
        /// <returns></returns>
        public IActionResult Empty(string message = "")
        {
            var error = new ErrorMessageModel();

            error.Title   = "404";
            error.Message = string.IsNullOrWhiteSpace(message) ? "请求的数据不存在" : message;
            return(RedirectToAction("Error", "Home", error));
        }
예제 #7
0
 public async Task <JsonResult> ErrorMessage([FromBody] ErrorMessageModel payload)
 {
     //Also add cert to call
     if (Request.Headers.TryGetValue("X-Kammarkollegiet-InterpreterService-Event", out var type))
     {
         await _hubContext.Clients.All.SendAsync("IncommingCall", $"[{type}]:: Failure for this callid:{payload.CallId} when trying to using this type:{payload.NotificationType}");
     }
     return(new JsonResult("Success"));
 }
        public static Tuple <string, string> ToFileError(this ErrorMessageModel err, string filePath)
        {
            string fileName  = !string.IsNullOrWhiteSpace(filePath) ? Path.GetFileName(filePath) : null;
            string caption   = err.Caption.Replace("%FILENAME%", fileName).Replace("%FILEPATH%", filePath);
            string shortText = err.ShortText.Replace("%FILENAME%", fileName).Replace("%FILEPATH%", filePath);
            Tuple <string, string> result = new Tuple <string, string>(caption, shortText);

            return(result);
        }
예제 #9
0
        public static ErrorMessageModel ToErrorMessage(this Exception exception, string caption, Dictionary <string, string> values)
        {
            StringBuilder shortText    = new StringBuilder();
            Type          t            = exception.GetType();
            ValueStrings  valueStrings = ValueStrings.FromDictionary(values);

            if (typeof(IOException).IsAssignableFrom(t))
            {
                IOException io      = (IOException)exception;
                bool        hasPath = !string.IsNullOrEmpty(valueStrings.FilePath);
                if (hasPath && typeof(FileNotFoundException).IsAssignableFrom(t))
                {
                    shortText.Append($"File by path '{valueStrings.FilePath}' does not exists.");
                }
                else if (hasPath && typeof(DirectoryNotFoundException).IsAssignableFrom(t))
                {
                    shortText.Append($"Directory by path '{valueStrings.FilePath}' does not exists.");
                }
                else if (hasPath && typeof(DriveNotFoundException).IsAssignableFrom(t))
                {
                    shortText.Append($"Drive by path '{valueStrings.FilePath}' does not exists.");
                }
                else if (hasPath && typeof(EndOfStreamException).IsAssignableFrom(t))
                {
                    shortText.Append($"Unexpected end of stream in file '{valueStrings.FilePath}': {exception.Message}");
                }
                else if (hasPath && typeof(FileLoadException).IsAssignableFrom(t))
                {
                    shortText.Append($"Failed to load file '{valueStrings.FilePath}:'{Environment.NewLine}{exception.Message}");
                }
                else if (hasPath && typeof(PathTooLongException).IsAssignableFrom(t))
                {
                    shortText.Append($"The path '{valueStrings.FilePath}' is too long:{Environment.NewLine}{exception.Message}");
                }
                else
                {
                    shortText.Append(exception.Message);
                }
            }
            else if (typeof(UnauthorizedAccessException).IsAssignableFrom(t))
            {
                shortText.Append($"You do not have permissions to access the file/path '{valueStrings.FilePath}'");
            }
            else
            {
                shortText.Append(exception.Message);
            }
            ErrorMessageModel result = new ErrorMessageModel(caption, shortText.ToString())
            {
                Details = exception.ToHumanReadable(values)
            };

            return(result);
        }
예제 #10
0
        public override void Handle(ExceptionHandlerContext context)
        {
            var message = new ErrorMessageModel();
            var now     = DateTime.Now;

            message.LogId   = now.Hour * 10000 + now.Minute * 100 + now.Second;
            message.Message = context.Exception.InnerException?.Message ?? context.Exception.Message;

            var response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(message));

            context.Result = new ResponseMessageResult(response);
        }
예제 #11
0
        public async Task <ActionResult> Login(string userName, string userPwd, string btnStudent)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.Timeout = new TimeSpan(0, 2, 0);
                    var req       = new HttpRequestMessage(HttpMethod.Post, ApiUriHelper.GetBaseUri() + "security/login");
                    var loginType = (btnStudent == null) ? "AdminLogin" : "StudentLogin";
                    req.Content = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >()
                    {
                        new KeyValuePair <string, string>("username", userName),
                        new KeyValuePair <string, string>("password", userPwd),
                        new KeyValuePair <string, string>("requestType", loginType)
                    });
                    var respond = await client.SendAsync(req);

                    var token = respond.Content.ReadAsStringAsync().Result.Trim('"');

                    if (respond.IsSuccessStatusCode)
                    {
                        UserSession session = new UserSession();
                        var         isAdmin = (btnStudent == null);
                        session.SetUser(token, isAdmin);
                        respond.Dispose();
                        return(loginType == "AdminLogin" ? RedirectToAction("courses", "aasadmin") :
                               RedirectToAction("index", "aasstudent"));
                    }
                    else
                    {
                        var error = new ErrorMessageModel()
                        {
                            Error        = "Login fail",
                            ErrorMessage = "username or password invalid"
                        };
                        return(View("Index", error));
                    }
                }
            }
            catch (Exception ex)
            {
                var error = new ErrorMessageModel()
                {
                    Error        = "Login fail",
                    ErrorMessage = ex.Message
                };
                return(View("Index", error));
            }
        }
예제 #12
0
        public ActionResult DeleteEmploymentDetails(int Id)
        {
            var  userName = System.Web.HttpContext.Current.User.Identity.Name.Split('|')[0];
            bool data     = _IEmployementService.DeleteEmploymnetDetail(Id, userName);

            TempData["Message"] = new ErrorMessageModel()
            {
                MessageType = "success",
                //Message = "Record deleted successfully."
                Message = "Employment details deleted successfully!!"
            };
            return(RedirectToAction("Index"));
            // return Json(new { result = data }, JsonRequestBehavior.AllowGet);
        }
예제 #13
0
    public static async Task <bool> UploadErrorMessageAsync(ErrorMessageModel model)
    {
        bool result = true;

        try
        {
            var reply = await WorkflowsQueryServiceUtility.InvokeWorkflowQueryServiceAsync((client) =>
                                                                                           client.CreateOrUpdateErrorMessageAsync(model.ToCreateOrUpdateRequest()));

            reply.StatusReply.CheckErrors();
        }
        catch (Exception ex)
        {
            ShowErrorMessageDialogue(ex);
            result = false;
        }
        return(result);
    }
예제 #14
0
    public static async Task <ErrorMessageModel> GetMoreInformationAsync(ErrorMessageModel model)
    {
        ErrorMessageModel result = model;

        try
        {
            var reply = await WorkflowsQueryServiceUtility.InvokeWorkflowQueryServiceAsync((client) =>
                                                                                           client.GetErrorMessageAsync(model.ToGetRequest()));

            result = reply.FromDataContract();
        }
        catch (UserFacingException ex)
        {
            result.Suggestion = GetMessage(ex.ErrorCode, ex.Parameters);
        }
        catch (Exception)
        {
            result.Suggestion = GetMessage(ErrorCode.ServerUnavailableMsg);
        }
        return(result);
    }
예제 #15
0
        /// <summary>
        /// apply your validations inside the method
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private ExcelUploadResponseModel ApplyValidation(DataTable data)
        {
            List <ErrorMessageModel> errorMessageModels = new List <ErrorMessageModel>();

            if (data == null)
            {
                throw new InvalidOperationException();
            }

            // performing the validation here

            if (data.Rows.Count == 0)
            {
                throw new IndexOutOfRangeException();
            }

            int row = 0;

            foreach (DataRow dataRow in data.Rows)
            {
                bool isPassed          = true;
                var  errorMessageModel = new ErrorMessageModel(row);

                if (dataRow[0].ToString() != "vimal")
                {
                    errorMessageModel.ErrorMessagees.Add("Coulm 0 should have value vimal");
                    isPassed = false;
                }

                /// contine with other checks over here;
                row++;
                if (isPassed)
                {
                    continue;
                }
                errorMessageModels.Add(errorMessageModel);
            }

            return(new ExcelUploadResponseModel(errorMessageModels));
        }
        public ActionResult WXAuthorizedCallBack()
        {
            CommonMessage commonMessage = null;
            string        code          = StringHelper.GetRequest("code");         //获取code                          微信授权成功后参数
            string        state         = StringHelper.GetRequest("state");        //获取state                       微信授权成功后参数
            string        isReturnData  = StringHelper.GetRequest("isReturnData"); //获取isReturnData  自定义参数
            string        scope         = StringHelper.GetRequest("scope");        //获取scope                       自定义参数
            string        returnUrl     = StringHelper.GetRequest("returnUrl");    //获取returnUrl           自定义参数

            if ("" == code)
            {
                commonMessage = CommonMessage.Error(CodeMessageEnum.AuthorizationFailed);
            }

            var accessToken = SessionHelper.GetSession(CodeMessageEnum.AuthorizationAccessToken);//检查session中是否存在
            var openId      = SessionHelper.GetSession(CodeMessageEnum.AuthorizationOpenId);

            if ("" == accessToken)//不存在缓存的access_token
            {
                var getAccessCodeUri = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code ";

                getAccessCodeUri = string.Format(getAccessCodeUri, WChatAppid, WChatAppSecret, code);
                string jsonResult = HttpHelper.GetWebContent(getAccessCodeUri);
                if (jsonResult.Contains("errcode"))//出现错误
                {
                    ErrorMessageModel errorModel = JsonHelper.DeserializeJsonToObject <ErrorMessageModel>(jsonResult);
                    if (null != errorModel)
                    {
                        commonMessage = CommonMessage.Error(CodeMessageEnum.FaildGotAccessToken + ",原因:" + errorModel.Errmsg, (int)StateCode.InvalidCode);
                    }
                    else
                    {
                        commonMessage = CommonMessage.Error(CodeMessageEnum.FaildGotAccessToken);
                    }
                }
                else
                {
                    AccessTokenModel accessModel = JsonHelper.DeserializeJsonToObject <AccessTokenModel>(jsonResult);
                    if (null != accessModel)
                    {
                        //缓存access_token
                        accessToken = accessModel.AccessToken;
                        openId      = accessModel.Openid;
                        SessionHelper.SetSession(CodeMessageEnum.AuthorizationAccessToken, accessModel.AccessToken, true);
                        SessionHelper.SetSession(CodeMessageEnum.AuthorizationOpenId, accessModel.AccessToken, true);
                    }
                    else
                    {
                        commonMessage = CommonMessage.Error("反序列化对象中出现错误");
                    }
                }
            }
            if ("0" == isReturnData && "snsapi_base" == scope)
            {
                commonMessage = CommonMessage.Success(openId, "ok");
                return(Content(commonMessage.ToString(), "application/json"));
            }
            if ("1" == isReturnData && "snsapi_base" == scope)
            {
                commonMessage = CommonMessage.Success(null, "ok");
                //TODO 将数据存起来

                return(Content(commonMessage.ToString(), "application/json"));
            }
            if ("" != accessToken)
            {
                var getUserInforUri = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN ";
                getUserInforUri = string.Format(getUserInforUri, accessToken, openId);
                string resultContent = HttpHelper.GetWebContent(getUserInforUri);
                if (resultContent.Contains("errcode"))//出现错误
                {
                    ErrorMessageModel errorModel = JsonHelper.DeserializeJsonToObject <ErrorMessageModel>(resultContent);
                    if (null != errorModel)
                    {
                        commonMessage = CommonMessage.Error(CodeMessageEnum.FaildGotAccessToken + ",原因:" + errorModel.Errmsg, (int)StateCode.InvalidCode);
                    }
                    else
                    {
                        commonMessage = CommonMessage.Error(CodeMessageEnum.FaildGotAccessToken);
                    }
                }
                else
                {
                    UserinfoModel userModel = JsonHelper.DeserializeJsonToObject <UserinfoModel>(resultContent);
                    if (null != userModel)
                    {
                        if ("0" == isReturnData && "snsapi_userinfo" == scope)
                        {
                            commonMessage = CommonMessage.Success(userModel, "ok");
                            ////TODO 将数据存起来
                        }
                        else
                        {
                            commonMessage = CommonMessage.Success(null, "ok");
                        }
                    }
                    else
                    {
                        commonMessage = CommonMessage.Error("反序列化对象中出现错误");
                    }
                }
            }
            else
            {
                commonMessage = CommonMessage.Error(CodeMessageEnum.FaildGotAccessToken);
            }
            return(Content(commonMessage.ToString(), "application/json"));
        }
        /// <summary>
        /// apply your validations inside the method
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private ExcelUploadResponseModel ApplyValidation(DataTable data)
        {
            IRepository <Product> productRepository = new ProductRepository(_unitOfWork);
            IRepository <Packet>  packetRepsitory   = new PacketRepository(_unitOfWork);

            List <ErrorMessageModel> errorMessageModels = new List <ErrorMessageModel>();

            if (data == null)
            {
                throw new InvalidOperationException();
            }

            // performing the validation here

            if (data.Rows.Count == 0)
            {
                throw new IndexOutOfRangeException();
            }

            var products = productRepository.GetAll();
            var packets  = packetRepsitory.GetAll();

            var inputData = data.ToListof <InputDataModelV1>();
            int row       = 0;
            int count     = inputData.Count();

            List <ProductDetail> productDetailsList = new List <ProductDetail>();

            inputData.RemoveAll((inputModel) =>
            {
                bool canDelete        = false;
                var errorMessageModel = new ErrorMessageModel(row);
                var packet            = packets.FirstOrDefault(p => p.PacketCode.Equals(inputModel.Packet, StringComparison.InvariantCultureIgnoreCase));
                if (packet == null)
                {
                    errorMessageModel.ErrorMessagees.Add($" Row {row}, packet code {inputModel.Packet} does not exists");
                    canDelete = true;
                }
                var product = products.FirstOrDefault(p => p.ProductCode.Equals(inputModel.Product, StringComparison.InvariantCultureIgnoreCase));
                if (product == null)
                {
                    errorMessageModel.ErrorMessagees.Add($" Row {row}, product code {inputModel.Packet} does not exists");
                    canDelete = true;
                }

                row++;
                if (canDelete)
                {
                    errorMessageModels.Add(errorMessageModel);
                }
                else
                {
                    productDetailsList.Add(new ProductDetail
                    {
                        ProductId = product.ProductId,
                        PacketId  = packet.PacketId
                                    //add the other values over here
                    });
                }

                return(canDelete);
            });

            if (productDetailsList.Count() == count)
            {
                IRepository <ProductDetail> productDetailrepository = new ProductDetailRepository(_unitOfWork);

                productDetailsList.ForEach(detaiils =>
                {
                    productDetailrepository.Insert(detaiils);
                });
                _unitOfWork.SaveChanges();
                return(new ExcelUploadResponseModel(null));
            }

            return(new ExcelUploadResponseModel(errorMessageModels));
            //save functionality here
        }
예제 #18
0
        public ActionResult Index(EmployementModel employementModel)
        {
            bool   status   = false;
            string userName = null;

            try
            {
                ModelState.Remove("ReasonForLeave");
                if (ModelState.IsValid)
                {
                    employementModel.UserId = Convert.ToInt32(System.Web.HttpContext.Current.User.Identity.Name.Split('|')[1]);
                    userName = System.Web.HttpContext.Current.User.Identity.Name.Split('|')[0];

                    var employmentList = EmploymentDetailList(Convert.ToInt32(System.Web.HttpContext.Current.User.Identity.Name.Split('|')[1]));

                    var numberOfEmployment = _IEmploymentCountService.GetEmploymentCountByUserId((int)employementModel.UserId);

                    #region commented Validation for Employee count
                    //==================As Per Comment of EnBoard_ Comments 01-11-2017.docx=====================

                    /*
                     * if (numberOfEmployment != null)
                     * {
                     *  if (numberOfEmployment.NumberOfEmployments == null || employmentList.Count >= numberOfEmployment.NumberOfEmployments)
                     *  {
                     *      TempData["EmployementModel"] = employementModel;
                     *      TempData["Message"] = new ErrorMessageModel()
                     *      {
                     *          MessageType = "error",
                     *          Message = "You cannot add employments more than you specified in Number Of Employments!"
                     *      };
                     *      return RedirectToAction("Index");
                     *  }
                     * }
                     * else
                     * {
                     *  TempData["EmployementModel"] = employementModel;
                     *  TempData["Message"] = new ErrorMessageModel()
                     *  {
                     *      MessageType = "error",
                     *      Message = "Please add Number Of Employemnts!"
                     *  };
                     *  return RedirectToAction("Index");
                     * }
                     */
                    //==================End As Per Comment of EnBoard_ Comments 01-11-2017.docx=====================
                    #endregion


                    if (employmentList.Count != 0 && employmentList.Any(x => x.IsCurrentEmployment == true) && employementModel.IsCurrentEmployment == true)
                    {
                        TempData["EmployementModel"] = employementModel;
                        TempData["Message"]          = new ErrorMessageModel()
                        {
                            MessageType = "error",
                            Message     = "Current employment is already added."
                        };
                        return(RedirectToAction("Index"));
                    }

                    #region Employee Can join same company more than one time

                    /*
                     * if (employmentList.Any(x => x.CompanyName == employementModel.CompanyName))
                     * {
                     *  TempData["EmployementModel"] = employementModel;
                     *  TempData["Message"] = new ErrorMessageModel()
                     *  {
                     *      MessageType = "error",
                     *      Message = "This employment is already exist."
                     *  };
                     *  return RedirectToAction("Index");
                     *
                     * }
                     */
                    #endregion Employee Can join same company more than one time
                    if (employementModel.FromDate.HasValue && employementModel.ToDate.HasValue)
                    {
                        if (employementModel.FromDate.Value >= employementModel.ToDate.Value)
                        {
                            TempData["EmployementModel"] = employementModel;
                            TempData["Message"]          = new ErrorMessageModel()
                            {
                                MessageType = "error",
                                Message     = "Relieving date cannot be less than or equal to date of joining."
                            };
                            return(RedirectToAction("Index"));
                        }
                    }

                    if (employmentList != null)
                    {
                        var overlappedRecord = employmentList.Where(u => Convert.ToDateTime(u.FromDate) <= Convert.ToDateTime(employementModel.ToDate) && Convert.ToDateTime(employementModel.FromDate) <= Convert.ToDateTime(u.ToDate) && u.IsActive == true).ToList();

                        if (overlappedRecord.Count > 0)
                        {
                            TempData["EmployementModel"] = employementModel;
                            TempData["Message"]          = new ErrorMessageModel()
                            {
                                MessageType = "error",
                                Message     = "Employment duration should not fall between previous or current employment duration."
                            };
                            return(RedirectToAction("Index"));
                        }
                    }

                    employementModel.UpdatedBy   = userName;
                    employementModel.UpdatedDate = DateTime.UtcNow;

                    Mapper.CreateMap <EmployementModel, Data.EmploymentDetail>();
                    var EmployDetail = Mapper.Map <EmployementModel, Data.EmploymentDetail>(employementModel);


                    if (EmployDetail.CreatedBy == null || EmployDetail.CreatedBy == "")
                    {
                        EmployDetail.CreatedBy = userName;
                    }
                    if (EmployDetail.CreatedDate == DateTime.MinValue || EmployDetail.CreatedDate == null)
                    {
                        EmployDetail.CreatedDate = DateTime.UtcNow;
                    }

                    if (EmployDetail.UpdatedBy == null || EmployDetail.UpdatedBy == "")
                    {
                        EmployDetail.UpdatedBy = userName;
                    }
                    if (EmployDetail.UpdatedDate == DateTime.MinValue || EmployDetail.UpdatedDate == null)
                    {
                        EmployDetail.UpdatedDate = DateTime.UtcNow;
                    }

                    EmployDetail.EmployementNo = _IEmployementService.GetLatestEmploymentNo(Convert.ToInt32(employementModel.UserId));
                    EmployDetail.IsActive      = true;

                    EmployDetail.CompanyCountryID = _ICountryService.GetAll(null, null, "").Where(i => i.Country == "Other").Select(x => x.CountryID).FirstOrDefault();
                    EmployDetail.CompanyStateID   = _IStateService.GetAll(null, null, "").Where(i => i.State == "Other").Select(x => x.StateID).FirstOrDefault();
                    EmployDetail.CompanyCityID    = _ICityService.GetAll(null, null, "").Where(i => i.City == "Other").Select(x => x.CityID).FirstOrDefault();

                    if (employementModel.IsCurrentEmployment == false)
                    {
                        EmployDetail.ReasonForLeave = employementModel.ReasonForLeave;
                    }

                    status = _IEmployementService.Insert(EmployDetail, null, "");

                    if (status != true)
                    {
                        TempData["Message"] = new ErrorMessageModel()
                        {
                            MessageType = "success",
                            Message     = "Employement details added successfully for" + employementModel.CompanyName + "!!"
                        };
                        return(RedirectToAction("Index"));
                    }
                }
                else
                {
                    TempData["EmployementModel"] = employementModel;
                    TempData["Message"]          = new ErrorMessageModel()
                    {
                        MessageType = "error",
                        Message     = "Please fill mandetory details for " + employementModel.CompanyName
                    };
                }
            }
            catch (Exception ex)
            {
                TempData["EmployementModel"] = employementModel;
                TempData["Message"]          = new ErrorMessageModel()
                {
                    MessageType = "error",
                    Message     = "Something went wrong for" + employementModel.CompanyName
                };
            }
            return(RedirectToAction("Index"));
        }
예제 #19
0
        public ActionResult EditSave(EmployementModel employementModel)
        {
            bool   status   = false;
            string userName = null;

            try
            {
                ModelState.Remove("ReasonForLeave");
                if (ModelState.IsValid)
                {
                    employementModel.UserId = Convert.ToInt32(System.Web.HttpContext.Current.User.Identity.Name.Split('|')[1]);
                    userName = System.Web.HttpContext.Current.User.Identity.Name.Split('|')[0];

                    var employmentList = EmploymentDetailList(Convert.ToInt32(System.Web.HttpContext.Current.User.Identity.Name.Split('|')[1]));

                    employementModel.UpdatedBy   = userName;
                    employementModel.UpdatedDate = DateTime.UtcNow;

                    Mapper.CreateMap <EmployementModel, Data.EmploymentDetail>();
                    var EmployDetail = Mapper.Map <EmployementModel, Data.EmploymentDetail>(employementModel);

                    if (employementModel.FromDate.HasValue && employementModel.ToDate.HasValue)
                    {
                        if (employementModel.FromDate.Value >= employementModel.ToDate.Value)
                        {
                            TempData["Message"] = new ErrorMessageModel()
                            {
                                MessageType = "error",
                                Message     = "Relieving date cannot be less than or equal to date of joining."
                            };
                            return(RedirectToAction("Index"));
                        }
                    }
                    if (employmentList.Where(y => y.EmploymentDetID != employementModel.EmploymentDetID).Any(x => (x.FromDate <= employementModel.FromDate && x.ToDate >= employementModel.FromDate) || (x.FromDate <= employementModel.ToDate && x.ToDate >= employementModel.ToDate)))
                    {
                        TempData["Message"] = new ErrorMessageModel()
                        {
                            MessageType = "error",
                            Message     = "Employment duration should not fall between previous or current employment duration."
                        };
                        return(RedirectToAction("Index"));
                    }

                    if (EmployDetail.UpdatedBy == null || EmployDetail.UpdatedBy == "")
                    {
                        EmployDetail.UpdatedBy = userName;
                    }
                    if (EmployDetail.UpdatedDate == DateTime.MinValue || EmployDetail.UpdatedDate == null)
                    {
                        EmployDetail.UpdatedDate = DateTime.UtcNow;
                    }

                    EmployDetail.IsActive         = true;
                    EmployDetail.CompanyCountryID = _ICountryService.GetAll(null, null, "").Where(i => i.Country == "Other").Select(x => x.CountryID).FirstOrDefault();
                    EmployDetail.CompanyStateID   = _IStateService.GetAll(null, null, "").Where(i => i.State == "Other").Select(x => x.StateID).FirstOrDefault();
                    EmployDetail.CompanyCityID    = _ICityService.GetAll(null, null, "").Where(i => i.City == "Other").Select(x => x.CityID).FirstOrDefault();

                    if (employementModel.IsCurrentEmployment == false)
                    {
                        EmployDetail.ReasonForLeave = employementModel.ReasonForLeave;
                    }

                    status = _IEmployementService.Update(EmployDetail, null, "");
                    TempData["Message"] = new ErrorMessageModel()
                    {
                        MessageType = "success",
                        Message     = "Employment details updated successfully for " + employementModel.CompanyName + "!!"
                    };

                    if (status != true)
                    {
                        TempData["Message"] = new ErrorMessageModel()
                        {
                            MessageType = "error",
                            Message     = "Something went wrong for" + employementModel.CompanyName
                        };
                        return(RedirectToAction("Index"));
                    }
                }
            }
            catch (Exception ex)
            {
                TempData["Message"] = new ErrorMessageModel()
                {
                    MessageType = "error",
                    Message     = "Something went wrong for" + employementModel.CompanyName
                };
            }
            return(RedirectToAction("Index"));
        }