コード例 #1
0
        public virtual JsonResult Crear(CentroCosto entidad)
        {
            var jsonResponse = new JsonResponse { Success = false };

            if (ModelState.IsValid)
            {
                try
                {
                    entidad.UsuarioCreacion = UsuarioActual.IdUsuario.ToString();
                    entidad.UsuarioModificacion = UsuarioActual.IdUsuario.ToString();
                    CentroCostoBL.Instancia.Add(entidad);

                    jsonResponse.Success = true;
                    jsonResponse.Message = "Se Proceso con éxito";
                }
                catch (Exception ex)
                {
                    logger.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace));
                    jsonResponse.Message = "Ocurrio un error, por favor intente de nuevo o más tarde.";
                }
            }
            else
            {
                jsonResponse.Message = "Por favor ingrese todos los campos requeridos";
            }
            return Json(jsonResponse, JsonRequestBehavior.AllowGet);
        }
コード例 #2
0
 public static void EnableCors(this IPipelines pipelines, CorsConfiguration corsConfiguration)
 {
     pipelines.AfterRequest.AddItemToEndOfPipeline(ctx =>
     {
         UpdateResponseHeaders(ctx.Request, ctx.Response, corsConfiguration);
     });
     pipelines.OnError.AddItemToEndOfPipeline((ctx, exception) =>
     {
         if (exception == null)
         {
             // Nothing to serialize, just return default 500 response
             return HttpStatusCode.InternalServerError;
         }
         Response response;
         if (ctx.Request.Headers.Accept.Any(x => x.Item1.ToLowerInvariant().Contains("application/json")))
         {
             // Return the exception detail as JSON
             response = new JsonResponse(new ExceptionDetailObject(exception),
                 new DefaultJsonSerializer()) {StatusCode = HttpStatusCode.InternalServerError};
         }
         else
         {
             // Return the exception message as text/plain
             response = new TextResponse(HttpStatusCode.InternalServerError, exception.Message);
         }
         UpdateResponseHeaders(ctx.Request, response, corsConfiguration);
         return response;
     });
 }
コード例 #3
0
ファイル: AjaxFileManager.aspx.cs プロジェクト: Cycli/Cycli
    public static JsonResponse AppendFile(string path)
    {
        JsonResponse response = new JsonResponse()
        {
            Data = string.Empty,
            Success = false,
            Message = ""
        };
        //check rights
        if (!Security.IsAuthorizedTo(Rights.CreateNewPosts))
        {
            response.Success = false;
            response.Message = "Access denied";
            return response;
        }

        var file = BlogService.GetFile(path);
        if (file != null)
        {
            if (file.IsImage)
            {
                var imagePath = string.Format("<img src=\"{0}\" />", file.AsImage.ImageUrl);
                response.Success = true;
                response.Data = imagePath;
            }
            else
            {
                var filePath = string.Format("<p><a href=\"{1}\" >{0}</a></p>", file.FileDescription, file.FileDownloadPath);
                response.Success = true;
                response.Data = filePath;
            }
        }
        return response;
    }
コード例 #4
0
        public void AddPerson()
        {
            var person = new Person
            {
                Name = "Ben",
                Surname = "Joubert",
                CellNo = "081568975481",
                RegistrationId = "asdflkjwer879234lkjdf",
                CanSendNotification = true,
                CreatedDate = DateTime.Now
            };
            response = client.AddPerson(person);

            var person2 = new Person
            {
                Name = "Robert",
                Surname = "Kleinhans",
                CellNo = "0815689745481",
                RegistrationId = "asdj395wer879234lkjdf",
                CanSendNotification = true,
                CreatedDate = DateTime.Now
            };
            response = client.AddPerson(person2);

            Assert.IsTrue(response.IsSuccessFull);
        }
コード例 #5
0
        public ActionResult GetRegions(string id)
        {
            string regionid = Request.Form["regionid"];

            JsonResponse result = new JsonResponse();            
            Country c = Country.FindByBvin(id);
            if ((c != null))
            {
                StringBuilder sb = new StringBuilder();
                result.Regions = string.Empty;

                foreach (Region r in c.Regions)
                {
                    sb.Append("<option ");
                    if (r.Abbreviation == regionid)
                    {
                        sb.Append(" selected=\"selected\" ");
                    }
                    sb.Append(" value=\"" + r.Abbreviation + "\">" + r.Name + "</option>");
                }

                result.Regions = sb.ToString();
            }

            return new JsonResult() { Data = result };
        }
コード例 #6
0
        public virtual JsonResult BuscarIDCargo(string nombre)
        {
            var jsonResponse = new JsonResponse {Success = false};
            if (ModelState.IsValid)
            {
                try
                {
                    string[] name = nombre.Split('-');
                    //var lista = (Cargo)TrabajadorBL.Instancia.Search(name.ElementAt(1).Trim()).SingleOrDefault();
                    var lista = (Cargo)TrabajadorBL.Instancia.Search(nombre.Trim()).SingleOrDefault();

                    jsonResponse.Data = lista.IDCargo;
                    jsonResponse.Success = true;
                }
                catch (Exception ex)
                {
                    jsonResponse.Success = false;
                    return Json("ERROR - Vuelva a cargar la Página", JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                jsonResponse.Message = "Por favor ingrese todos los campos requeridos";
            }
            return Json(jsonResponse, JsonRequestBehavior.AllowGet);
        }
コード例 #7
0
        public ActionResult Edit(int boardId, Competitor updatedCompetitor)
        {
            var board = _repository.GetBoardById(boardId);
            var competitor = _repository.GetCompetitorByName(boardId, updatedCompetitor.Name);
            var response = new JsonResponse<bool>();

            if (competitor == null)
            {
                response.Message = "Competitor not found";
                response.Error = true;
            }
            else if (!competitor.CanEdit(board, User.Identity.Name))
            {
                response.Message = "Invalid authority";
                response.Error = true;
            }
            else
            {
                // Just update status for now (owner only can change status)
                if(board.IsOwner(User.Identity.Name))
                    competitor.Status = updatedCompetitor.Status;

                _repository.CommitChanges();
                response.Result = true;
            }

            return (Json(response));
        }
コード例 #8
0
ファイル: AdvertisementTest.cs プロジェクト: FROSTBlTE/FAD
        public void AddAdvertisement()
        {
            response = client.ViewAllClients();
            Assert.IsNotNull(response.ClientCollection);
            Assert.IsTrue(response.ClientCollection.ToList().Count > 0);
            var theClient = response.ClientCollection.FirstOrDefault();

            response = client.ViewAllCatagories();
            Assert.IsNotNull(response.CatagoryCollection);
            Assert.IsTrue(response.CatagoryCollection.ToList().Count > 0);
            var catagory = response.CatagoryCollection.FirstOrDefault();

            var advertisement = new Advertisement
            {
                Title = "Big Sale on Cosmetics!",
                Description = "There is a big sale on Cosmetics just around the corner!",
                ExpiryDate = DateTime.Now.AddDays(30),
                CategoryId = catagory.Id,
                ClientId = theClient.Id,
                CreatedDate = DateTime.Now
            };
            response = client.AddAdvertisement(new JsonRequest {AdvertisementCollection = new List<Advertisement>{advertisement}});

            Assert.IsTrue(response.IsSuccessFull);
        }
コード例 #9
0
        public ActionResult Create(PostViewModel post)
        {
            var response = new JsonResponse<PostViewModel>();
            var newPost = new Post();

            try
            {
                newPost.Board = _repository.GetBoardById(post.BoardId);
                newPost.Owner = _repository.GetCompetitorByUserName(post.BoardId, User.Identity.Name);
                newPost.Body = post.Body;

                _repository.Add(newPost);
                _repository.CommitChanges();

                newPost.Owner.LastViewedPostId = newPost.PostId;
                _repository.CommitChanges();

                response.Result = new PostViewModel(newPost);
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.Error = true;
            }

            return (Json(response));
        }
コード例 #10
0
ファイル: HomeController.cs プロジェクト: JolevqSAC/Interv2
        public string Upload(HttpPostedFileBase file, FormCollection forms)
        {
            var jsonResponse = new JsonResponse { Success = false };
            try
            {
                var content = new byte[file.ContentLength];
                file.InputStream.Read(content, 0, file.ContentLength);
                var indexOfLastDot = file.FileName.LastIndexOf('.');
                var extension = file.FileName.Substring(indexOfLastDot + 1, file.FileName.Length - indexOfLastDot - 1);
                var name = file.FileName.Substring(0, indexOfLastDot);

                var fileUpload = new ImageFile
                {
                    Id = string.Format("_{0}", DateTime.Now.ToString("M_dd_yyyy_H_M_s")),
                    Name = name,
                    DirectoryPath = ConfigurationManager.AppSettings["TempFilePath"],
                    ApplicationPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath,
                    Extension = extension,
                    Data = content
                };

                jsonResponse.Data = fileUpload.RelativePath;
                jsonResponse.Success = true;
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace));
                jsonResponse.Message = "Ocurrio un error, por favor intente de nuevo o más tarde.";
            }

            return JsonConvert.SerializeObject(jsonResponse);
        }
コード例 #11
0
 public static JsonResponse GetUploadStatus(string qid)
 {
     var j = new JsonResponse();
     // try and turn the id into a guid
     Guid id;
     if (!Guid.TryParse(qid, out id)) {
         j.Message = "Id not a valid Guid.";
         j.Error = 1;
         return j;
     }
     if(!Core.UploadStatuses.ContainsKey(id)) {
         j.Message = "Upload does not exist or status has expired.";
         j.Error = 2;
         return j;
     }
     var u = Core.UploadStatuses[id];
     j.Add("BytesRead", u.BytesRead);
     j.Add("BytesTotal", u.BytesTotal);
     j.Add("Complete", u.Complete);
     j.Add("CurrentFile", u.CurrentFile);
     j.Add("Id", u.Id);
     j.Add("LastUpdated", u.LastUpdated);
     j.Add("Message", u.Message);
     j.Add("StartedOn", u.StartedOn);
     return j;
 }
コード例 #12
0
ファイル: FileManager.cs プロジェクト: CorbinDallas/Oda
 public static JsonResponse Upload(string targetPath, IList<UploadedFile> files)
 {
     var j = new JsonResponse();
     if(files.Count>1) {
         j.Error = 1;
         j.Message = "FileManager.Upload only supports one file at a time.  Use FileManager.UploadFiles instead.";
         return j;
     }
     if (files.Count == 0) {
         j.Error = 2;
         j.Message = "Source file is missing from upload request.";
         return j;
     }
     try {
         targetPath = targetPath.Replace("~\\", Core.BaseDirectory) + files[0].OriginalFileName;
         if(File.Exists(targetPath)) {
             File.Delete(targetPath);
         }
         File.Move(files[0].Path, targetPath);
     }catch(Exception e) {
         j.Error = e.Message.GetHashCode();
         j.Message = e.Message;
         return j;
     }
     j.Error = 0;
     j.Message = "File uploaded successfully.";
     return j;
 }
コード例 #13
0
        public void Should_fail_to_return_xml_body_on_non_xml_response()
        {
            var response = new JsonResponse<Model>(new Model() { Dummy = "Data" });
            var context = new NancyContext() { Response = response };

            Assert.Throws<InvalidOperationException>(() => context.XmlBody<Model>());
        }
コード例 #14
0
        public virtual JsonResult Crear(CategoriaProducto entidad)
        {
            var jsonResponse = new JsonResponse { Success = false };

            if (ModelState.IsValid)
            {
                try
                {
                    entidad.UsuarioCreacion = UsuarioActual.IdUsuario.ToString();
                    entidad.UsuarioModificacion = UsuarioActual.IdUsuario.ToString();

                    if (entidad.CAT_NombreIngles == null)
                        entidad.CAT_NombreIngles = "";
                    if (entidad.CAT_Descripcion == null)
                        entidad.CAT_Descripcion = "";
                    entidad.CAT_IndicadorArea = "A"; // cambiar 22/01/2013

                    CategoriaProductoBL.Instancia.Add(entidad);

                    jsonResponse.Success = true;
                    jsonResponse.Message = "Se Proceso con éxito";
                }
                catch (Exception ex)
                {
                    logger.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace));
                    jsonResponse.Message = "Ocurrio un error, por favor intente de nuevo o más tarde.";
                }
            }
            else
            {
                jsonResponse.Message = "Por favor ingrese todos los campos requeridos";
            }
            return Json(jsonResponse, JsonRequestBehavior.AllowGet);
        }
コード例 #15
0
        public void ViewAllPersons()
        {
            response = client.ViewAllPersons();

            Assert.IsTrue(response.IsSuccessFull);
            Assert.IsNotNull(response.PersonCollection);
            Assert.IsTrue(response.PersonCollection.ToList().Count > 0);
        }
コード例 #16
0
ファイル: CatagoryTest.cs プロジェクト: FROSTBlTE/FAD
        public void ViewAllClients()
        {
            response = client.ViewAllCatagories();

            Assert.IsTrue(response.IsSuccessFull);
            Assert.IsNotNull(response.CatagoryCollection);
            Assert.IsTrue(response.CatagoryCollection.ToList().Count > 0);
        }
コード例 #17
0
ファイル: AdvertisementTest.cs プロジェクト: FROSTBlTE/FAD
        public void ViewAllAdvertisements()
        {
            response = client.ViewAllAdvertisements();

            Assert.IsTrue(response.IsSuccessFull);
            Assert.IsNotNull(response.AdvertisementCollection);
            Assert.IsTrue(response.AdvertisementCollection.ToList().Count > 0);
        }
コード例 #18
0
ファイル: AjaxBase.cs プロジェクト: a-fung/MangaWeb3
        /// <summary>
        /// Return a Json response to the client app
        /// </summary>
        /// <param name="response">The response object to be stringify and return to client app</param>
        public void ReturnJson(JsonResponse response)
        {
            string output = JsonConvert.SerializeObject(response);

            Response.StatusCode = 200;
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/json";
            Response.Write(output);
        }
コード例 #19
0
ファイル: WebResponse.cs プロジェクト: the-wazz/clifton
 public void Process(ISemanticProcessor proc, IMembrane membrane, JsonResponse resp)
 {
     resp.Context.Response.StatusCode = resp.StatusCode;
     resp.Context.Response.ContentType = "text/json";
     resp.Context.Response.ContentEncoding = Encoding.UTF8;
     resp.Context.Response.ContentLength64 = resp.Json.Length;
     resp.Context.Response.OutputStream.Write(resp.Json.to_Utf8(), 0, resp.Json.Length);
     resp.Context.Response.Close();
 }
コード例 #20
0
        public void Should_fail_to_return_xml_body_on_non_xml_response()
        {
            var response = new JsonResponse<Model>(new Model() { Dummy = "Data" }, new DefaultJsonSerializer());
            var context = new NancyContext() { Response = response };

            var result = Record.Exception(() => context.XmlBody<Model>());

            result.ShouldNotBeNull();
        }
コード例 #21
0
ファイル: AjaxController.cs プロジェクト: FuujinTheHacker/LoM
        public string loginpage()
        {
            var jp = new JsonResponse();

            jp.result = true;
            jp.addData(this, "loginpage");

            return jp.ToString();
        }
コード例 #22
0
        public void Should_create_new_wrapper_from_json_response_if_not_already_present()
        {
            var response = new JsonResponse<Model>(new Model() { Dummy = "Data" });
            var context = new NancyContext() { Response = response };

            var result = context.JsonBody<Model>();

            result.Dummy.ShouldEqual("Data");
        }
コード例 #23
0
ファイル: CatagoryTest.cs プロジェクト: FROSTBlTE/FAD
        public void AddCatagory()
        {
            var catagory = new Catagory
            {
                CatagoryName= "Vehicles",
                CreatedDate = DateTime.Now
            };
            response = client.AddCatagory(catagory);

            Assert.IsTrue(response.IsSuccessFull);
        }
コード例 #24
0
        public void Should_create_new_wrapper_from_json_response_if_not_already_present()
        {
            // Given
            var response = new JsonResponse<Model>(new Model() { Dummy = "Data" }, new DefaultJsonSerializer());
            var context = new NancyContext() { Response = response };

            // When
            var result = context.JsonBody<Model>();

            // Then
            result.Dummy.ShouldEqual("Data");
        }
コード例 #25
0
ファイル: AdvertisementTest.cs プロジェクト: FROSTBlTE/FAD
        public void ViewAllAdvertisementsByClient()
        {
            var response = client.ViewAllClients();
            Assert.IsNotNull(response.ClientCollection);
            Assert.IsTrue(response.ClientCollection.Count > 0);

            response = client.ViewAllAdvertisementsByClient(new JsonRequest { ClientCollection = new List<Client>{ response.ClientCollection.FirstOrDefault() } });

            Assert.IsTrue(response.IsSuccessFull);
            Assert.IsNotNull(response.AdvertisementCollection);
            Assert.IsTrue(response.AdvertisementCollection.ToList().Count > 0);
        }
コード例 #26
0
ファイル: AjaxController.cs プロジェクト: FuujinTheHacker/LoM
        public string logout()
        {
            var jp = new JsonResponse();

            if (isLogdin)
                FormsAuthentication.SignOut();
            else
                jp.ex = "not Authenticated";

            jp.result = isLogdin;

            return jp.ToString();
        }
コード例 #27
0
ファイル: PostHandler.cs プロジェクト: davidalpert/fubulinks
        public JsonResponse Execute(CreateLinkInputModel inputModel)
        {
            var response = new JsonResponse { Success = true };
            var link = new Link
                           {
                               DateAdded = DateTime.Now,
                               OriginalUrl = inputModel.OriginalUrl,
                               ShortenedUrl = _urlShortener.Shorten(inputModel.OriginalUrl)
                           };
            _repository.Insert(link);
            _repository.Save();

            return response;
        }
コード例 #28
0
ファイル: UI.cs プロジェクト: CorbinDallas/Oda
 /// <summary>
 /// Gets an embedded file.
 /// </summary>
 /// <param name="fileName">Name of the file.</param>
 /// <returns></returns>
 public static JsonResponse GetFile(string fileName)
 {
     var j = new JsonResponse();
     var lName = fileName.ToLower();
     if(UIPlugin.IsImageFile(lName)) {
         j.AttachmentStream = UIPlugin.UIRef.GetResource(fileName);
     } else {
         j.AttachmentContent = UIPlugin.UIRef.GetResourceString(fileName);
     }
     j.AttachmentFileName = fileName;
     j.ContentDisposition = JsonContentDisposition.Normal;
     j.ContentType = UIPlugin.GetMimeType(lName);
     return j;
 }
コード例 #29
0
        public void BeforeAll()
        {
            // Arrange
             _emailAddressSubmitted = "*****@*****.**";
            _genericResponse = new GenericResponse(true,"some message");

            _program = MockRepository.GenerateStub<AlphaProgram>();
            _program.Stub(p => p.SaveInterestedCustomer(Arg<string>.Is.Anything)).Return(_genericResponse);

            var controller = new CustomerController(_program);

            // Act
            _result = controller.SubmitCustomerEmail(new SubmitCustomerEmailModel {CustomerEmail = _emailAddressSubmitted});
            _responseData = _result.Data as JsonResponse;
        }
コード例 #30
0
ファイル: AjaxController.cs プロジェクト: FuujinTheHacker/LoM
        public string productpage(string name)
        {
            var jp = new JsonResponse();

            if (isLogdin)
            {
                jp.addData(this, "ProductPage", new Models.ProductModel(name));
            }
            else
                jp.ex = "not Authenticated";

            jp.result = isLogdin;

            return jp.ToString();
        }
コード例 #31
0
        public async Task <JsonResult> RemoveStudentToCourse(int courseID, string studentID)
        {
            SetRoles();
            JsonResponse <CourseGroup> response = new JsonResponse <CourseGroup>();
            Course  lookupCourse = this.courseRepository.FindByID(courseID);
            AppUser student      = await usrMgr.FindByIdAsync(studentID);

            if (student == null)
            {
                response.Error.Add(new Error()
                {
                    Name = "RemoveStudentToCourse", Description = "Student doesn't exist"
                });
                return(Json(response));
            }
            if (lookupCourse == null)
            {
                response.Error.Add(new Error()
                {
                    Name = "addStudentToCourse", Description = "Course Not Found"
                });
                return(Json(response));
            }
            // lets find the enrollment
            var enrollment = this.courseGroupRepository.GetAll().FindAll((x) => {
                if (x.FK_Course.ID == courseID && x.FK_AppUser.Id == studentID)
                {
                    return(true);
                }
                return(false);
            });

            if (enrollment.Count == 0)
            {
                response.Error.Add(new Error()
                {
                    Name = "RemoveStudentToCourse", Description = "Student is not in the class"
                });
                return(Json(response));
            }
            if (this.isAdmin)
            {
                enrollment.ForEach((x) => {
                    this.courseGroupRepository.Delete(x);
                });
                return(Json(response));
            }
            else if (this.isInstructor)
            {
                // Check if instructor is teaching the course
                if
                (lookupCourse.FK_INSTRUCTOR == await usrMgr.GetUserAsync(HttpContext.User))
                {
                    enrollment.ForEach((x) => {
                        this.courseGroupRepository.Delete(x);
                    });
                    return(Json(response));
                }
            }
            response.Error.Add(new Error()
            {
                Name = "RemoveStudentToCourse", Description = "failed to remove student to course"
            });
            return(Json(response));
        }
コード例 #32
0
 public SocketRepository(Socket clientSocket, JsonRequest jsonRequest)
 {
     _clientSocket = clientSocket;
     _jsonRequest  = jsonRequest;
     _jsonResponse = new JsonResponse();
 }
コード例 #33
0
        public JsonResponse Edit(string id, string bg, string[] vals)
        {
            if (!Security.IsAuthorizedTo(Rights.EditRoles))
            {
                return(GetNotAuthorized());
            }
            else if (Utils.StringIsNullOrWhitespace(id))
            {
                return(new JsonResponse()
                {
                    Message = Resources.labels.idArgumentNull
                });
            }
            else if (vals == null)
            {
                return(new JsonResponse()
                {
                    Message = Resources.labels.valsArgumentNull
                });
            }
            else if (vals.Length == 0 || Utils.StringIsNullOrWhitespace(vals[0]))
            {
                return(new JsonResponse()
                {
                    Message = Resources.labels.roleNameIsRequired
                });
            }

            var response = new JsonResponse();

            try
            {
                Right.OnRenamingRole(id, vals[0]);

                string[] usersInRole = Roles.GetUsersInRole(id);
                if (usersInRole.Length > 0)
                {
                    Roles.RemoveUsersFromRoles(usersInRole, new string[] { id });
                }

                Roles.DeleteRole(id);
                Roles.CreateRole(vals[0]);

                if (usersInRole.Length > 0)
                {
                    Roles.AddUsersToRoles(usersInRole, new string[] { vals[0] });
                }

                Right.RefreshAllRights();

                response.Success = true;
                response.Message = string.Format(Resources.labels.roleUpdatedFromTo, id, vals[0]);
            }
            catch (Exception ex)
            {
                Utils.Log(string.Format("Roles.UpdateRole: {0}", ex.Message));
                response.Message = string.Format(Resources.labels.couldNotUpdateRole, vals[0]);
            }

            return(response);
        }
コード例 #34
0
ファイル: HttpSyncHandler.cs プロジェクト: yuxuac/LoginDemo
 /// <summary>
 /// BadRequest : 400
 /// </summary>
 /// <param name="response"></param>
 /// <param name="msg"></param>
 protected virtual void BadRequest(HttpResponse response, JsonResponse resp)
 {
     response.StatusCode = (int)HttpStatusCode.BadRequest;
     response.Write(Utility.Serialize(resp));
 }
コード例 #35
0
        public async Task <JsonResult> GetCourses()
        {
            SetRoles();
            JsonResponse <CourseDataOut> response = new JsonResponse <CourseDataOut>();

            if (this.isAdmin)
            {
                // Show all courses
                List <CourseDataOut> courseDataOuts = new List <CourseDataOut>();
                this.courseRepository.GetAll().ToList <Course>().ForEach(course =>
                {
                    CourseDataOut dataOut = new CourseDataOut
                    {
                        ID                 = course.ID,
                        Name               = course.Name,
                        IsActive           = course.IsActive,
                        FK_INSTRUCTOR_NAME = course.FK_INSTRUCTOR.FirstName + " " + course.FK_INSTRUCTOR.LastName
                    };
                    courseDataOuts.Add(dataOut);
                });
                response.Data = courseDataOuts;
            }
            else if (this.isInstructor)
            {
                var currentUser = await usrMgr.GetUserAsync(HttpContext.User);

                // Lookup the course the instructor is teaching
                this.courseRepository.GetAll().ToList <Course>()
                .ForEach(course =>
                {
                    if (course.FK_INSTRUCTOR.Id == currentUser.Id)
                    {
                        CourseDataOut dataOut = new CourseDataOut
                        {
                            ID       = course.ID,
                            Name     = course.Name,
                            IsActive = course.IsActive,
                            //  FK_INSTRUCTOR_NAME = course.FK_INSTRUCTOR.FirstName + " " + course.FK_INSTRUCTOR.LastName
                        };
                        response.Data.Add(dataOut);
                    }
                });
            }
            else if (this.isStudent)
            {
                List <CourseDataOut> courseDataOuts = new List <CourseDataOut>();
                AppUser currentUser = await usrMgr.GetUserAsync(HttpContext.User);

                // Look at Course Groups and add courses that the student is in
                this.courseGroupRepository.GetAll().ToList <CourseGroup>().ForEach(
                    courseGroup =>
                {
                    if (courseGroup.FK_AppUser == currentUser)
                    {
                        //AppUser instructor = courseGroup.FK_Course.FK_INSTRUCTOR;
                        courseDataOuts.Add(new CourseDataOut
                        {
                            ID       = courseGroup.FK_Course.ID,
                            Name     = courseGroup.FK_Course.Name,
                            IsActive = courseGroup.FK_Course.IsActive,
                            //  FK_INSTRUCTOR_NAME = instructor.FirstName + " " + instructor.LastName
                        });
                    }
                });
                response.Data = courseDataOuts;
            }
            else
            {
                response.Error.Add(new Error()
                {
                    Name = "Courses", Description = "Your in a role that cannot view courses"
                });
            }
            return(Json(response));
        }
コード例 #36
0
        public async Task <IActionResult> AddSetting(SettingDto model)
        {
            using (var txscope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    if (!ModelState.IsValid)
                    {
                        txscope.Dispose();
                        return(RedirectToAction("Index"));
                    }
                    if (model.Id == 0)
                    {
                        model.UserId   = User.GetUserId();
                        model.IsActive = true;
                        var dataModel = Mapper.Map <Settings>(model);
                        var result    = await _settingService.InsertAsync(dataModel, Accessor, User.GetUserId());

                        if (result != null)
                        {
                            //StaffLog
                            if (User.IsInRole(UserRoles.Staff))
                            {
                                await _staffLog.InsertAsync(new Log { CreatedDate = DateTime.UtcNow, StaffId = User.GetUserId(), Description = ResponseConstants.SettingTextCreated }, Accessor, User.GetUserId());
                            }
                            txscope.Complete();
                            return(JsonResponse.GenerateJsonResult(1, ResponseConstants.SettingTextCreated));
                        }
                        else
                        {
                            txscope.Dispose();
                            ErrorLog.AddErrorLog(null, "Post-AddSettings");
                            return(JsonResponse.GenerateJsonResult(0, "Settings not added."));
                        }
                    }
                    else
                    {
                        var data = _settingService.GetSingle(x => x.Id == model.Id && x.IsDelete == false && x.IsActive == true);
                        data.Id     = model.Id;
                        data.Html   = model.Html;
                        data.Title  = model.Title;
                        data.UserId = User.GetUserId();
                        var updateResult = await _settingService.UpdateAsync(data, Accessor, User.GetUserId());

                        if (updateResult != null)
                        {
                            //StaffLog
                            if (User.IsInRole(UserRoles.Staff))
                            {
                                await _staffLog.InsertAsync(new Log { CreatedDate = DateTime.UtcNow, StaffId = User.GetUserId(), Description = ResponseConstants.SettingTextCreated }, Accessor, User.GetUserId());
                            }
                            txscope.Complete();
                            return(JsonResponse.GenerateJsonResult(1, ResponseConstants.SettingTextUpdated));
                        }
                        else
                        {
                            txscope.Dispose();
                            return(JsonResponse.GenerateJsonResult(1, ResponseConstants.SomethingWrong));
                        }
                    }
                }

                catch (Exception ex)
                {
                    txscope.Dispose();
                    ErrorLog.AddErrorLog(ex, "Post-AddSettings");
                    return(JsonResponse.GenerateJsonResult(0));
                }
            }
            #endregion
        }
コード例 #37
0
        public async Task <IActionResult> AddEditInvitationCode(InvitationCodeDto model)
        {
            using (var txscope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    if (!ModelState.IsValid)
                    {
                        txscope.Dispose();
                        RedirectToAction("_AddEditInvitationCode", model.Id);
                    }

                    if (model.Id == 0)
                    {
                        var invitationCodeObj = Mapper.Map <InvitationCode>(model);
                        invitationCodeObj.IsActive              = true;
                        invitationCodeObj.NumberOfFreeDays      = model.NoOfFreeDays;
                        invitationCodeObj.NumberOfFreeQuestions = model.NoOfFreeQuestions;
                        invitationCodeObj.ExpirationDays        = model.ExpirationDays;

                        var result = await _invitationCodesService.InsertAsync(invitationCodeObj, Accessor, User.GetUserId());

                        if (result != null)
                        {
                            //StaffLog
                            if (User.IsInRole(UserRoles.Staff))
                            {
                                await _staffLog.InsertAsync(new Log { CreatedDate = DateTime.UtcNow, StaffId = User.GetUserId(), Description = ResponseConstants.CreateInvitaionCode }, Accessor, User.GetUserId());
                            }
                            txscope.Complete();
                            return(JsonResponse.GenerateJsonResult(1, ResponseConstants.CreateInvitaionCode));
                        }
                    }
                    else if (model != null)
                    {
                        var result = await _invitationCodesService.GetSingleAsync(x => x.Id == model.Id && x.IsActive == true && x.IsDelete == false);

                        result.NumberOfFreeDays      = model.NoOfFreeDays;
                        result.NumberOfFreeQuestions = model.NoOfFreeQuestions;
                        result.ExpirationDays        = model.ExpirationDays;
                        result.IsActive = true;
                        await _invitationCodesService.UpdateAsync(result, Accessor, User.GetUserId());


                        //StaffLog
                        if (User.IsInRole(UserRoles.Staff))
                        {
                            await _staffLog.InsertAsync(new Log { CreatedDate = DateTime.UtcNow, StaffId = User.GetUserId(), Description = ResponseConstants.UpdateInvitationCode }, Accessor, User.GetUserId());
                        }
                        txscope.Complete();
                        return(JsonResponse.GenerateJsonResult(1, ResponseConstants.UpdateInvitationCode));
                    }
                    else
                    {
                        txscope.Dispose();
                        return(JsonResponse.GenerateJsonResult(0, ResponseConstants.SomethingWrong));
                    }

                    txscope.Dispose();
                    return(JsonResponse.GenerateJsonResult(0, ResponseConstants.SomethingWrong));
                }
                catch (Exception ex)
                {
                    txscope.Dispose();
                    ErrorLog.AddErrorLog(ex, "CreateInvitationCodeSetUp");
                    return(Json(ResponseConstants.SomethingWrong));
                }
            }
        }
コード例 #38
0
        public JsonResult Add(TablaRegistroDTO tablaRegistroDTO)
        {
            var jsonResponse = new JsonResponse {
                Success = true
            };

            try
            {
                int resultado     = 0;
                var tablaregistro = MapperHelper.Map <TablaRegistroDTO, TablaRegistro>(tablaRegistroDTO);

                resultado = TablaRegistroBL.Instancia.Add(tablaregistro);

                if (resultado > 0)
                {
                    jsonResponse.Title   = Title.TitleRegistro;
                    jsonResponse.Message = Mensajes.RegistroSatisfactorio;
                }
                else if (resultado == -1)
                {
                    jsonResponse.Title   = Title.TitleAlerta;
                    jsonResponse.Warning = true;
                    jsonResponse.Message = Mensajes.YaExisteRegistro;
                }
                else if (resultado < 0)
                {
                    jsonResponse.Title   = Title.TitleAlerta;
                    jsonResponse.Warning = true;
                    jsonResponse.Message = Mensajes.RegistroFallido;
                }

                LogBL.Instancia.Add(new Log
                {
                    Accion        = Mensajes.Add,
                    Controlador   = Mensajes.UsuarioController,
                    Identificador = resultado,
                    Mensaje       = jsonResponse.Message,
                    Usuario       = tablaRegistroDTO.UsuarioRegistro,
                    Objeto        = JsonConvert.SerializeObject(tablaRegistroDTO)
                });
            }
            catch (Exception ex)
            {
                LogError(ex);
                jsonResponse.Success = false;
                jsonResponse.Title   = Title.TitleAlerta;
                jsonResponse.Message = Mensajes.IntenteloMasTarde;

                LogBL.Instancia.Add(new Log
                {
                    Accion        = Mensajes.Add,
                    Controlador   = Mensajes.UsuarioController,
                    Identificador = 0,
                    Mensaje       = ex.Message,
                    Usuario       = tablaRegistroDTO.UsuarioRegistro,
                    Objeto        = JsonConvert.SerializeObject(tablaRegistroDTO)
                });
            }

            return(Json(jsonResponse));
        }
コード例 #39
0
ファイル: BIDVBank.cs プロジェクト: WKahWai/SeleniumTest
        protected override void Login()
        {
            socket.Clients.Client(socket.ConnectionId).Receive(JsonResponse.success(null, $"[{param.AccountNo}] - 系统开始登陆网银"));
            var result = StepLooping(new StepLoopOption((sleep) =>
            {
                driver.Url = "https://www.bidv.vn:81/iportalweb/iRetail@1";
                driver.Navigate();
                sleep();
                return(driver.PageSource.Contains("Đăng nhập<span> BIDV Online</span>") || driver.PageSource.Contains("Login<span> BIDV Online</span>"));
            })
            {
                MaxLoop       = 3,
                SleepInterval = 8
            });

            if (result.HasError || !result.IsComplete)
            {
                throw new Exception($"[{param.AccountNo}] - 获取首页失败");
            }
            SwitchToEnglish();
            result = StepLooping(new StepLoopOption((sleep) =>
            {
                Thread.Sleep(3000);
                var userId = driver.FindElement(By.Id("userNo"));
                userId.Clear();
                userId.SendKeys(param.AccountID);
                var pass = driver.FindElement(By.Id("userPin"));
                pass.Clear();
                pass.SendKeys(param.Password);

                string code = GetCode(driver.FindElement(By.Id("captcha")).GetAttribute("src"), driver.GetCookies());
                if (string.IsNullOrEmpty(code))
                {
                    return(false);
                }
                var cap = driver.FindElement(By.Id("cap1"));
                cap.Clear();
                cap.SendKeys(code);
                driver.ToChromeDriver().ExecuteScript("SubmitForm();");
                sleep();
                Regex Logoutregex = new Regex("(<a ?.*><span>(?<logout>Logout)</span>?.*</a>)");
                if (Logoutregex.Match(driver.PageSource).Groups["logout"].Value.ToLower() == "logout")
                {
                    return(true);
                }
                else
                {
                    string error = (string)driver.ToChromeDriver().ExecuteScript("return $('#errid1').text();");
                    if (!string.IsNullOrEmpty(error))
                    {
                        throw new TransferProcessException(error, 403);
                    }
                }
                return(false);
            })
            {
                MaxLoop       = 5,
                SleepInterval = 12
            });
            if (result.HasError || !result.IsComplete)
            {
                throw new Exception($"[{param.AccountNo}] - 登录失败。 Ex - {result.Message}");
            }
            //RetriveDiness();
        }
コード例 #40
0
ファイル: BIDVBank.cs プロジェクト: WKahWai/SeleniumTest
        protected override void OTP()
        {
            IsWaitingOTP = true;
            if (param.IsSameBank)
            {
                string btnId = "";
                while (string.IsNullOrEmpty(btnId))
                {
                    btnId = new Regex("(<button type=\"button\" id=\"(?<id>[a-z0-9\\-]+)\" class=\" x-btn-text\">Submit</button>)").Match(driver.PageSource).Groups["id"].Value;
                    Thread.Sleep(200);
                }

                if (param.OTPType == 2)//smart otp
                {
                    //renew the smart otp to avoid expired too fast
                    driver.ToChromeDriver().ExecuteScript("$('button')[22].click()");
                    var refNo = driver.ToChromeDriver().ExecuteScript("return $(\"input[name='TRANS_ID']\").val()");
                    Thread.Sleep(600);
                    socket.Clients.Client(socket.ConnectionId).Receive(JsonResponse.success(refNo, "Otp reference success", 209));
                }

                OTPResult = OTPListener((otp) =>
                {
                    var submitBtn = driver.FindElement(By.Id(btnId));
                    var otpInput  = driver.FindElement(By.Name("KEY_OTP"));
                    otpInput.Clear();
                    otpInput.SendKeys(Keys.NumberPad0);
                    otpInput.SendKeys(Keys.Backspace);
                    otpInput.SendKeys(otp);
                    Thread.Sleep(1000);
                    submitBtn.Click();
                    //driver.ToChromeDriver().ExecuteScript("$('button')[24].click()");
                    Thread.Sleep(800);
                    IsOTPSubmit           = true;
                    string invalidMessage = "OTP entered is incorrect. Please try again";
                    if (driver.PageSource.Contains("Please enter the OTP"))
                    {
                        return(new Tuple <string, bool>("Please enter the OTP, OTP cannot be null", !driver.PageSource.Contains("Please enter the OTP")));
                    }
                    logger.Debug(driver.PageSource);
                    return(new Tuple <string, bool>(invalidMessage, !driver.PageSource.Contains(invalidMessage)));
                }, otpExpiredDuration: 0.5, SupportReenter: bankInfo.ReenterOTP);
                if (OTPResult.ForceStop)
                {
                    RenewOTP();
                }
                //if (!IsOTPSubmit)
                //{
                if (OTPResult.HasError)
                {
                    throw new Exception($"[{param.AccountNo}] - Fail during OTP request. EX :  {OTPResult.Message}");
                }
                else if (!OTPResult.IsComplete)
                {
                    throw new TransferProcessException("等待短信验证码超时", 406);
                }
                //todo if need extra logic to verify is stuck in the same page
                //}
            }
            else
            {
                throw new NotImplementedException();
            }
        }
コード例 #41
0
        public ActionResult NotificationMessage(NotificationMessage notificationMessage)
        {
            if (!notificationMessage.NotificationType.HasValue)
            {
                notificationMessage.NotificationType
                    = _notificationMessageService
                      .Find(notificationMessage.NotificationMessageId).NotificationType;
            }

            switch ((Enums.MessageType)notificationMessage.NotificationType)
            {
            case Enums.MessageType.StandardMessage:
                UpdateStandardMessageDetails(notificationMessage);
                notificationMessage.StandardMessageId = notificationMessage.StandardMessage.StandardMessageId;
                break;

            case Enums.MessageType.SurveyMessage:
                UpdateSurveyMessageDetails(notificationMessage);
                break;

            case Enums.MessageType.ReviewMessage:
                UpdateReviewMessageDetails(notificationMessage);
                break;

            case Enums.MessageType.RatingMessage:
                notificationMessage.SurveyMessage   = null;
                notificationMessage.StandardMessage = null;
                UpdateRatingMessageDetails(notificationMessage);
                break;

            case Enums.MessageType.Offer:
                notificationMessage.SurveyMessage   = null;
                notificationMessage.StandardMessage = null;
                UpdateOfferMessageDetails(notificationMessage);
                break;
            }
            notificationMessage.SurveyMessage   = null;
            notificationMessage.StandardMessage = null;
            notificationMessage.ReviewMessage   = null;
            notificationMessage.RatingMessage   = null;

            if (notificationMessage.NotificationMessageId == 0)
            {
                _notificationMessageService.Insert(notificationMessage);
                _unitOfWorkAsync.SaveChanges();
            }
            else
            {
                var m = _notificationMessageService.Find(notificationMessage.NotificationMessageId);
                m.NotificationTitle       = notificationMessage.NotificationTitle;
                m.NotificationType        = notificationMessage.NotificationType;
                m.NotificationDescription = notificationMessage.NotificationDescription;
                m.MessageThumbImage       = notificationMessage.MessageThumbImage;
                m.ModifiedDate            = DateTime.UtcNow;
                _notificationMessageService.Update(m);
                _unitOfWorkAsync.SaveChanges();
            }
            JsonResponse response = new JsonResponse();

            return(RedirectToAction("Edit", "Notification", new { id = notificationMessage.NotificationId }));
        }
コード例 #42
0
        public async Task <JsonResult> GetCourse(int courseID = -1)
        {
            SetRoles();
            JsonResponse <Course>        response        = new JsonResponse <Course>();
            JsonResponse <CourseDataOut> responseStudent = new JsonResponse <CourseDataOut>();

            if (this.isAdmin)
            {
                //If they are admin we don't need to check if they are in the course
                response.Data.Add(this.courseRepository.FindByID(courseID));
            }
            else if (isInstructor)
            {
                //Lookup the course
                Course courseLookup = this.courseRepository.FindByID(courseID);
                /// Lets see if that course exists
                if (courseLookup == null)
                {
                    response.Error.Add(new Error()
                    {
                        Description = "The course does not exist", Name = "Course"
                    });
                    return(Json(response));
                }
                //Lets see if the instructor is teacing the course
                if (courseLookup.FK_INSTRUCTOR == await usrMgr.GetUserAsync(HttpContext.User))
                {
                    response.Data.Add(courseLookup);
                }
            }
            else if (this.isStudent)
            {
                //Lets see if the student is in the course]
                AppUser curentUser = await usrMgr.GetUserAsync(HttpContext.User);

                Course course = this.courseGroupRepository.GetAll().ToList <CourseGroup>().Find(
                    // Look for the user
                    x =>
                {
                    if ((x.FK_AppUser == curentUser) &&
                        (x.FK_Course == this.courseRepository.FindByID(courseID)))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                    ).FK_Course;

                AppUser       instructor = course.FK_INSTRUCTOR;
                CourseDataOut dataOut    = new CourseDataOut
                {
                    ID                 = course.ID,
                    Name               = course.Name,
                    IsActive           = course.IsActive,
                    FK_INSTRUCTOR_NAME = instructor.FirstName + " " + instructor.LastName
                };

                if (responseStudent.Data.Count > 0)
                {
                    responseStudent.Data.Add(dataOut);
                    return(Json(responseStudent));
                }
            }
            // If we didn't find the course show error
            if (response.Data.Count == 0)
            {
                response.Error.Add(new Error()
                {
                    Name = "GetCourse", Description = "You have not been added to any courses"
                });
            }
            return(Json(response));
        }
コード例 #43
0
        public JsonResponse Add(CVN_CATEGORIA_PAGO_PRECIODTO pagoprecioDTO)
        {
            var jsonResponse = new JsonResponse {
                Success = true
            };

            try
            {
                int resultado  = 0;
                var pagoprecio = MapperHelper.Map <CVN_CATEGORIA_PAGO_PRECIODTO, CVN_CATEGORIA_PAGO_PRECIO>(pagoprecioDTO);

                if (!CVN_CATEGORIA_PAGO_PRECIOBL.Instancia.Exists(pagoprecio))
                {
                    resultado = CVN_CATEGORIA_PAGO_PRECIOBL.Instancia.Add(pagoprecio);

                    if (resultado > 0)
                    {
                        jsonResponse.Message = Mensajes.RegistroSatisfactorio;
                        jsonResponse.Data    = resultado;
                    }
                    else
                    {
                        jsonResponse.Warning = true;
                        jsonResponse.Message = Mensajes.RegistroFallido;
                    }
                }
                else
                {
                    jsonResponse.Warning = true;
                    jsonResponse.Message = Mensajes.YaExisteRegistro;
                }

                LogBL.Instancia.Add(new Log
                {
                    Accion        = Mensajes.Add,
                    Controlador   = Mensajes.UsuarioController,
                    Identificador = resultado,
                    Mensaje       = jsonResponse.Message,
                    Usuario       = pagoprecioDTO.UsuarioCreacion,
                    Objeto        = JsonConvert.SerializeObject(pagoprecioDTO)
                });
            }
            catch (Exception ex)
            {
                LogError(ex);
                jsonResponse.Success = false;
                jsonResponse.Message = Mensajes.IntenteloMasTarde;

                LogBL.Instancia.Add(new Log
                {
                    Accion        = Mensajes.Add,
                    Controlador   = Mensajes.UsuarioController,
                    Identificador = 0,
                    Mensaje       = ex.Message,
                    Usuario       = pagoprecioDTO.UsuarioCreacion,
                    Objeto        = JsonConvert.SerializeObject(pagoprecioDTO)
                });
            }

            return(jsonResponse);
        }
コード例 #44
0
ファイル: UserActions.cs プロジェクト: benshyuv/Workshop
 public UserActions(IMarketFacade newMarketFacade)
 {
     this.newMarketFacade = newMarketFacade;
     Json = new JsonResponse();
 }
        /// <summary>
        /// Check condition for upload Excel sheet with combination of rta and filetype
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonResponse ExcelUpload(BulkUpload model)
        {
            JsonResponse response = new JsonResponse();

            if (model.File == null)
            {
                response.Status  = "F";
                response.Message = "Failed";
                return(response);
            }
            try
            {
                System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
                var extension = Path.GetExtension(model.File.FileName);
                if (extension.Equals(".xls") || extension.Equals(".xlsx"))
                {
                    bool     FileHeaderMatching = false;
                    string[] FileHeader         = null;
                    string[] RtaFileTypeCombo1  = BAL.Utilites.Constants.Message.RtaFileTypeCombination.rtaFileTypecombo1.Split(",");
                    string[] RtaFileTypeCombo2  = BAL.Utilites.Constants.Message.RtaFileTypeCombination.rtaFileTypecombo2.Split(",");
                    string[] RtaFileTypeCombo3  = BAL.Utilites.Constants.Message.RtaFileTypeCombination.rtaFileTypecombo3.Split(",");
                    string[] RtaFileTypeCombo4  = BAL.Utilites.Constants.Message.RtaFileTypeCombination.rtaFileTypecombo4.Split(",");
                    string[] RtaFileTypeCombo5  = BAL.Utilites.Constants.Message.RtaFileTypeCombination.rtaFileTypecombo5.Split(",");
                    string[] RtaFileTypeCombo6  = BAL.Utilites.Constants.Message.RtaFileTypeCombination.rtaFileTypecombo6.Split(",");
                    //string[] RtaFileTypeCombo7 = BAL.Utilites.Constants.Message.RtaFileTypeCombination.rtaFileTypecombo7.Split(",");
                    string    ExpectedHeader = string.Empty;
                    string    TableName      = string.Empty;
                    DataTable table          = ExcelDataTable(model.File);
                    //new folio
                    if (model.FileTypeId == Convert.ToInt32(RtaFileTypeCombo1[0]) && model.RTAsId == Convert.ToInt32(RtaFileTypeCombo1[1]) && model.File.FileName == RtaFileTypeCombo1[2])
                    {
                        ExpectedHeader = BAL.Utilites.Constants.Message.UploadFileHeader.CAMSFolioFile;
                        FileHeader     = ExpectedHeader.Split(",");
                        TableName      = "dbo.tbl_CamsFolio_Staging";
                    }
                    //new format camstran
                    else if (model.FileTypeId == Convert.ToInt32(RtaFileTypeCombo2[0]) && model.RTAsId == Convert.ToInt32(RtaFileTypeCombo2[1]) && model.File.FileName == RtaFileTypeCombo2[2])
                    {
                        ExpectedHeader = BAL.Utilites.Constants.Message.UploadFileHeader.CAMSTransactionFile;
                        FileHeader     = ExpectedHeader.Split(",");
                        TableName      = "dbo.tbl_CamsTransaction_Staging";
                    }
                    //Franklin tran
                    else if (model.FileTypeId == Convert.ToInt32(RtaFileTypeCombo5[0]) && model.RTAsId == Convert.ToInt32(RtaFileTypeCombo5[1]) && model.File.FileName == RtaFileTypeCombo5[2])
                    {
                        ExpectedHeader = BAL.Utilites.Constants.Message.UploadFileHeader.FranklinTranFileHeader;
                        FileHeader     = ExpectedHeader.Split(",");
                        TableName      = "dbo.tbl_Franklin_Tran_Staging";
                    }
                    //Franklin AUM
                    else if (model.FileTypeId == Convert.ToInt32(RtaFileTypeCombo4[0]) && model.RTAsId == Convert.ToInt32(RtaFileTypeCombo4[1]) && model.File.FileName == RtaFileTypeCombo4[2])
                    {
                        ExpectedHeader = BAL.Utilites.Constants.Message.UploadFileHeader.FranklinAUMFileHeader;
                        FileHeader     = ExpectedHeader.Split(",");
                        TableName      = "dbo.tbl_Franklin_AUM_Staging";
                    }
                    //Karvy AUM
                    else if (model.FileTypeId == Convert.ToInt32(RtaFileTypeCombo6[0]) && model.RTAsId == Convert.ToInt32(RtaFileTypeCombo6[1]) && model.File.FileName == RtaFileTypeCombo6[2])
                    {
                        ExpectedHeader = BAL.Utilites.Constants.Message.UploadFileHeader.KarvyAUMFileHeader;
                        FileHeader     = ExpectedHeader.Split(",");
                        TableName      = "dbo.tbl_karvy_aum_staging";
                    }
                    //Karvy Tran
                    else if (model.FileTypeId == Convert.ToInt32(RtaFileTypeCombo3[0]) && model.RTAsId == Convert.ToInt32(RtaFileTypeCombo3[1]) && model.File.FileName == RtaFileTypeCombo3[2])
                    {
                        ExpectedHeader = BAL.Utilites.Constants.Message.UploadFileHeader.KarvyTranFileHeader;
                        FileHeader     = ExpectedHeader.Split(",");
                        TableName      = "dbo.tbl_karvy_tran_staging";
                    }
                    else
                    {
                        response.Status  = "F";
                        response.Message = "Rta's FileType Combination is mismatched.";
                    }
                    if (FileHeader != null)
                    {
                        for (int i = 0; i < table.Columns.Count; i++)
                        {
                            if (table.Columns[i].ToString().ToLower() == FileHeader[i].ToLower())
                            {
                                FileHeaderMatching = true;
                            }
                            else
                            {
                                FileHeaderMatching = false;
                                response.Status    = "F";
                                response.Message   = FileHeader[i] + " column is missing in the selected file";
                                break;
                            }
                        }
                    }
                    if (FileHeaderMatching)
                    {
                        string status = UploadExcelFile(table, TableName, FileHeader);
                        if (status != null)
                        {
                            model.BatchNumber = status;
                            int i = InsertBulkUploadDetails(model);
                            if (i != 0)
                            {
                                response.Status  = "S";
                                response.Message = "Upload Successfully..";
                            }
                            else
                            {
                                response.Status  = "F";
                                response.Message = "File is not inserted..";
                            }
                        }
                        else
                        {
                            response.Status  = "F";
                            response.Message = "Something went wrong..";
                        }
                    }
                }
                else
                {
                    response.Status  = "F";
                    response.Message = "File is not valid";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(response);
        }
コード例 #46
0
ファイル: HomePageController.cs プロジェクト: Abhinav9550/MVC
 public ActionResult LogIn(JsonResponse jsonResponse)
 {
     return(View(jsonResponse));
 }
コード例 #47
0
ファイル: HttpSyncHandler.cs プロジェクト: yuxuac/LoginDemo
 /// <summary>
 /// InternalServerError : 500
 /// </summary>
 /// <param name="response"></param>
 /// <param name="msg"></param>
 protected virtual void InternalServerError(HttpResponse response, JsonResponse resp)
 {
     response.StatusCode = (int)HttpStatusCode.InternalServerError;
     response.Write(Utility.Serialize(resp));
 }
コード例 #48
0
        protected override async Task <bool> PostJsonAsync(IOwinEnvironment context, IClient client, ContentType bodyContentType, CancellationToken cancellationToken)
        {
            var model = await PostBodyParser.ToModel <VerifyEmailPostModel>(context, bodyContentType, _logger, cancellationToken);

            var jsonSuccessHandler = new Func <CancellationToken, Task <bool> >(ct => JsonResponse.Ok(context));

            return(await ResendVerification(
                       email : model.Email,
                       client : client,
                       environment : context,
                       errorHandler : null, // Errors are caught in AbstractRouteMiddleware
                       successHandler : jsonSuccessHandler,
                       cancellationToken : cancellationToken));
        }
コード例 #49
0
ファイル: HttpSyncHandler.cs プロジェクト: yuxuac/LoginDemo
 /// <summary>
 /// OK : 200
 /// </summary>
 /// <param name="response"></param>
 /// <param name="msg"></param>
 protected virtual void OK(HttpResponse response, JsonResponse resp)
 {
     response.StatusCode = (int)HttpStatusCode.OK;
     response.Write(Utility.Serialize(resp));
 }
コード例 #50
0
        public JsonResult Modificar(Compra compra)
        {
            var jsonResponse = new JsonResponse();

            if (ModelState.IsValid)
            {
                try
                {
                    var compraOriginal = CompraBL.Instancia.Single(compra.IdTransaccion);
                    var operacion      = OperacionBL.Instancia.Single(IdOperacion);

                    compraOriginal.IdPersona           = compra.IdPersona;
                    compraOriginal.IdAlmacen           = compra.IdAlmacen;
                    compraOriginal.FechaEntrega        = compra.FechaEntrega;
                    compraOriginal.Glosa               = compra.Glosa;
                    compraOriginal.MontoTipoCambio     = compra.MontoTipoCambio;
                    compraOriginal.IdEmpleado          = UsuarioActual.IdEmpleado;
                    compraOriginal.UsuarioCreacion     = UsuarioActual.IdEmpleado;
                    compraOriginal.UsuarioModificacion = UsuarioActual.IdEmpleado;
                    compraOriginal.MovimientoProducto  = new List <MovimientoProducto>();
                    compraOriginal.TransaccionImpuesto = new List <TransaccionImpuesto>();

                    if (DetalleCompra.Count == 0)
                    {
                        jsonResponse.Success = false;
                        jsonResponse.Message = "No se puede registrar la compra sin ingresar los productos.";
                    }
                    else
                    {
                        var secuencia = 0;
                        foreach (var movimientoProducto in DetalleCompra)
                        {
                            movimientoProducto.Secuencia           = ++secuencia;
                            movimientoProducto.FechaRegistro       = compra.FechaDocumento;
                            movimientoProducto.IdAlmacen           = compra.IdAlmacen;
                            movimientoProducto.SignoStock          = operacion.SignoStock;
                            movimientoProducto.Estado              = (int)TipoEstadoTransaccion.Registrado;
                            movimientoProducto.FechaCreacion       = FechaCreacion;
                            movimientoProducto.FechaModificacion   = FechaModificacion;
                            movimientoProducto.UsuarioCreacion     = UsuarioActual.IdEmpleado;
                            movimientoProducto.UsuarioModificacion = UsuarioActual.IdEmpleado;

                            var secuenciaDetalle = 0;
                            foreach (var productoStock in movimientoProducto.MovimientoProductoStock)
                            {
                                productoStock.Secuencia = ++secuenciaDetalle;
                                productoStock.IdAlmacen = compra.IdAlmacen.Value;
                            }

                            if (movimientoProducto.MovimientoProductoStock.Count == 0)
                            {
                                movimientoProducto.MovimientoProductoStock.Add(
                                    new MovimientoProductoStock
                                {
                                    Secuencia = 1,
                                    IdAlmacen = compra.IdAlmacen.Value,
                                    Cantidad  = movimientoProducto.Cantidad,
                                    LoteSerie = string.Empty
                                });
                            }

                            compraOriginal.MovimientoProducto.Add(movimientoProducto);
                        }

                        foreach (var impuesto in compra.TransaccionImpuesto)
                        {
                            impuesto.FechaCreacion       = FechaCreacion;
                            impuesto.FechaModificacion   = FechaModificacion;
                            impuesto.UsuarioCreacion     = UsuarioActual.IdEmpleado;
                            impuesto.UsuarioModificacion = UsuarioActual.IdEmpleado;

                            compraOriginal.TransaccionImpuesto.Add(impuesto);
                        }

                        var impuestoTotal = compra.TransaccionImpuesto.FirstOrDefault(p => p.IdImpuesto == (int)TipoImpuesto.Total);
                        if (impuestoTotal != null)
                        {
                            compraOriginal.MontoNeto = impuestoTotal.Valor;
                        }

                        CompraBL.Instancia.Actualizar(compraOriginal);

                        jsonResponse.Success = true;
                        jsonResponse.Message = "La compra fue actualizada correctamente.";
                    }
                }
                catch (Exception ex)
                {
                    jsonResponse.Message = ex.Message;
                }
            }
            else
            {
                jsonResponse.Message = "Por favor ingrese todos los campos requeridos";
            }
            return(Json(jsonResponse, JsonRequestBehavior.AllowGet));
        }
コード例 #51
0
        public JsonResult GuardarOrdenProduccion(OrdenProduccionModel model)
        {
            var response = new JsonResponse();

            try
            {
                var ordenProduccion = new OrdenProduccion
                {
                    TomarStock               = model.TomarStock,
                    CantidadProducto         = model.CantidadProducto,
                    CantidadProductoDigitado = model.CantidadProductoDigitado,
                    Estado     = Constantes.EstadoOrdenPoduccion.PendienteAprobar,
                    OrdenVenta = new OrdenVenta
                    {
                        Id       = model.IdOrdenVenta,
                        Producto = new Producto
                        {
                            Id          = model.IdProducto,
                            Stock       = model.StockProducto,
                            StockMinimo = model.StockMinimoProducto
                        },
                        Cantidad = model.CantidadOrdenVenta
                    },
                    Materiales = new List <OrdenProduccionMaterial>(),
                    Secuencia  = new List <OrdenProduccionSecuencia>()
                };

                foreach (var material in model.Materiales)
                {
                    ordenProduccion.Materiales.Add(new OrdenProduccionMaterial
                    {
                        Comprar   = material.Comprar,
                        Requerido = material.Requerido,
                        Material  = new Material
                        {
                            Id          = material.IdMaterial,
                            Stock       = material.Stock,
                            StockMinimo = material.StockMinimo
                        }
                    });
                }

                foreach (var secuencia in model.Secuencia)
                {
                    var fechaInicio = Utils.ConvertDate(secuencia.FechaInicioStr, "dd/MM/yyyy HH:mm");
                    var fechaFin    = Utils.ConvertDate(secuencia.FechaFinStr, "dd/MM/yyyy HH:mm");

                    ordenProduccion.Secuencia.Add(new OrdenProduccionSecuencia
                    {
                        Secuencia = secuencia.Secuencia,
                        Maquina   = new Maquina {
                            Id = secuencia.IdMaquina
                        },
                        FechaInicio = fechaInicio.Value,
                        FechaFin    = fechaFin.Value
                    });
                }

                var idOrdenProduccion = 0;
                using (var service = new ProduccionServiceClient())
                {
                    idOrdenProduccion = service.RegistrarOrdenProduccion(ordenProduccion);
                }

                response.Data    = idOrdenProduccion;
                response.Success = true;
                response.Message = "Ok";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;

                LogError(ex);
            }
            return(Json(response));
        }
コード例 #52
0
        public ActionResult CrearPoliza(PolizaModel model)
        {
            var jsonResponse = new JsonResponse {
                Success = false
            };

            try
            {
                var cliente = new Cliente
                {
                    Nu_DNI             = model.DniCliente,
                    No_Cliente         = model.NombreCliente,
                    No_ApePaterno      = model.ApellidoPaternoCliente,
                    No_ApeMaterno      = model.ApellidoMaternoCliente,
                    Fe_Nacimiento      = Convert.ToDateTime(model.FechaNacimientoCliente),
                    Tx_LugarNacimiento = model.LugarNacimientoCliente,
                    Tx_Direccion       = model.DireccionCliente,
                    Fi_EstadoCivil     = model.EstadoCivilCliente,
                    Fi_Sexo            = model.SexoCliente
                };

                var beneficiario = new List <Beneficiario>
                {
                    new Beneficiario
                    {
                        Num_DNI     = model.DniBeneficiario,
                        Txt_Nombre  = model.NombreBeneficiario,
                        Txt_Ape_Pat = model.ApellidoPaternoBeneficiario,
                        Txt_Ape_Mat = model.ApellidoMaternoBeneficiario,
                        Po_Cap_Aseg = model.PorcentajeCapitalAsegurado,
                        Fec_Nac     = Convert.ToDateTime(model.FechaNacimientoBeneficiario)
                    }
                };

                var poliza = new Poliza
                {
                    Nu_Poliza         = model.NumSolicitud,
                    Fe_Creacion       = DateTime.Now,
                    Fe_InicioVigencia = Convert.ToDateTime(model.InicioVigencia),
                    Cap_Asegurado     = model.CapitalAsegurado,
                    Cod_Plan          = model.CodTipoPlan,
                    Cliente           = cliente,
                    Beneficiario      = beneficiario,
                    Ocupacion         = model.Ocupacion,
                    Actividad         = model.Actividad,
                    LugarTrabajo      = model.LugarTrabajo,
                    IngresoMensual    = model.IngresoMensual,
                    Horario           = model.Horario,
                    ExpuestoAPeligro  = model.ExpuestoAPeligro,
                    MedioTransporte   = model.MedioTransporte,
                    FrecuenciaViaje   = model.FrecuenciaViaje,
                    DeporteAficion    = model.DeporteAficion,
                    RiesgoAccidente   = model.RiesgoAccidente,
                    CoberturaRiego    = model.CoberturaRiego,
                    Estatura          = model.Estatura,
                    Peso                 = model.Peso,
                    ConsumeTabaco        = model.ConsumeTabaco,
                    ConsumeAlcohol       = model.ConsumeAlcohol,
                    InsuficienciaRenal   = model.InsuficienciaRenal,
                    Diabetes             = model.Diabetes,
                    Cancer               = model.Cancer,
                    Epilepsia            = model.Epilepsia,
                    AfeccionCardiaca     = model.AfeccionCardiaca,
                    HipertensionArterial = model.HipertensionArterial,
                    TranstornoMental     = model.TranstornoMental
                };

                _polizaBL.Add(poliza);
                jsonResponse.Success = true;
                jsonResponse.Data    = Url.Action("Index", "Poliza");
            }
            catch (Exception)
            {
            }

            return(Json(jsonResponse, JsonRequestBehavior.AllowGet));
        }
コード例 #53
0
        public JsonResult ModificarDetalle(MovimientoProducto movimientoProducto, string lotesJson, int tipoCompra)
        {
            var jsonResponse = new JsonResponse();

            if (ModelState.IsValid)
            {
                try
                {
                    var movimientoProductoOriginal = DetalleCompra.SingleOrDefault(p => p.IdMovimientoProducto == movimientoProducto.IdMovimientoProducto);

                    if (movimientoProductoOriginal != null)
                    {
                        var existePorductoRepetido = false;
                        foreach (var detalle in DetalleCompra)
                        {
                            if (movimientoProducto.IdProducto == detalle.IdProducto &&
                                movimientoProducto.IdPresentacion == detalle.IdPresentacion &&
                                movimientoProducto.IdMovimientoProducto != detalle.IdMovimientoProducto)
                            {
                                existePorductoRepetido = true;
                            }
                        }

                        if (existePorductoRepetido)
                        {
                            jsonResponse.Success = false;
                            jsonResponse.Message = "No puede ingresar un mismo producto en mas de un Item.";
                        }
                        else
                        {
                            var lotes        = new JavaScriptSerializer().Deserialize <IList <MovimientoProductoStock> >(lotesJson);
                            var presentacion = PresentacionBL.Instancia.Single(movimientoProducto.IdPresentacion);
                            var producto     = ProductoBL.Instancia.Single(movimientoProducto.IdProducto);
                            var operacion    = OperacionBL.Instancia.Single(IdOperacion);

                            movimientoProductoOriginal.IdProducto          = movimientoProducto.IdProducto;
                            movimientoProductoOriginal.IdPresentacion      = movimientoProducto.IdPresentacion;
                            movimientoProductoOriginal.CodigoProducto      = producto.Codigo;
                            movimientoProductoOriginal.NombreProducto      = producto.Nombre;
                            movimientoProductoOriginal.TipoProducto        = producto.TipoProducto;
                            movimientoProductoOriginal.TipoClasificacion   = producto.TipoClasificacion;
                            movimientoProductoOriginal.NombrePresentacion  = presentacion.Nombre;
                            movimientoProductoOriginal.PrecioBase          = movimientoProducto.PrecioBase;
                            movimientoProductoOriginal.Cantidad            = movimientoProducto.Cantidad;
                            movimientoProductoOriginal.MontoDescuento      = movimientoProducto.MontoDescuento;
                            movimientoProductoOriginal.PorcentajeDescuento = movimientoProducto.PorcentajeDescuento;
                            movimientoProductoOriginal.PrecioNeto          = movimientoProducto.PrecioNeto;
                            movimientoProductoOriginal.CantidadDocumento   = movimientoProducto.CantidadDocumento;

                            if (tipoCompra == 1)
                            {
                                if (!producto.EsExonerado)
                                {
                                    movimientoProductoOriginal.MontoImpuesto      = movimientoProducto.PrecioNeto * (Igv.Monto / 100);
                                    movimientoProductoOriginal.PorcentajeImpuesto = Igv.Monto / 100;
                                }
                            }

                            movimientoProductoOriginal.SubTotal   = movimientoProducto.PrecioNeto + movimientoProducto.MontoImpuesto;
                            movimientoProductoOriginal.SignoStock = operacion.SignoStock;
                            movimientoProductoOriginal.Peso       = presentacion.Peso;
                            movimientoProductoOriginal.MovimientoProductoStock = new List <MovimientoProductoStock>();

                            foreach (var movimientoProductoStock in lotes)
                            {
                                movimientoProductoStock.FechaVencimiento = Convert.ToDateTime(movimientoProductoStock.FechaVencimientoFormato);
                                movimientoProductoOriginal.MovimientoProductoStock.Add(movimientoProductoStock);
                            }

                            jsonResponse.Success = true;
                            jsonResponse.Message = "El detalle del producto fue ingresado correctamente.";
                        }
                    }
                    else
                    {
                        jsonResponse.Success = false;
                        jsonResponse.Message = "No existe el producto dentro de la lista de los ya ingresados.";
                    }
                }
                catch (Exception ex)
                {
                    jsonResponse.Message = ex.Message;
                }
            }
            else
            {
                jsonResponse.Message = "Por favor ingrese todos los campos requeridos";
            }
            return(Json(jsonResponse, JsonRequestBehavior.AllowGet));
        }
コード例 #54
0
        public async Task <JsonResult> AddStudentToCourse(int courseID, string studentEmail)
        {
            SetRoles();
            JsonResponse <CourseGroup> response = new JsonResponse <CourseGroup>();
            Course  lookupCourse = this.courseRepository.FindByID(courseID);
            AppUser student      = await usrMgr.FindByEmailAsync(studentEmail);

            if (student == null)
            {
                response.Error.Add(new Error()
                {
                    Name = "addStudentToCourse", Description = "Student doesn't exist"
                });
                return(Json(response));
            }
            if (lookupCourse == null)
            {
                response.Error.Add(new Error()
                {
                    Name = "addStudentToCourse", Description = "Course Not Found"
                });
                return(Json(response));
            }
            // Lets see if this student is already in the course
            bool alreadyEnrolled = this.courseGroupRepository.GetAll().Exists((x) => {
                if (x.FK_Course.ID == courseID && x.FK_AppUser.Id == student.Id)
                {
                    return(true);
                }
                return(false);
            });

            if (alreadyEnrolled)
            {
                response.Error.Add(new Error()
                {
                    Name = "addStudentToCourse", Description = "Student is already in class"
                });
                return(Json(response));
            }
            var newCourseGroup = new CourseGroup()
            {
                FK_AppUser = student, FK_Course = lookupCourse, ReviewGroup = "1"
            };

            if (this.isAdmin)
            {
                this.courseGroupRepository.Add(newCourseGroup);
                response.Data.Add(newCourseGroup);
                return(Json(response));
            }
            else if (this.isInstructor)
            {
                // Check if instructor is teaching the course
                if
                (lookupCourse.FK_INSTRUCTOR == await usrMgr.GetUserAsync(HttpContext.User))
                {
                    this.courseGroupRepository.Add(newCourseGroup);
                    response.Data.Add(newCourseGroup);
                    return(Json(response));
                }
            }
            response.Error.Add(new Error()
            {
                Name = "studentAdd", Description = "failed to add student to course"
            });
            return(Json(response));
        }
コード例 #55
0
        public ActionResult EditarPoliza(PolizaModel model)
        {
            var jsonResponse = new JsonResponse {
                Success = false
            };

            try
            {
                var poliza = _polizaBL.Get(model.CodPoliza);

                poliza.Fe_InicioVigencia = Convert.ToDateTime(model.InicioVigencia);
                poliza.Cap_Asegurado     = model.CapitalAsegurado;
                poliza.Cod_Plan          = model.CodTipoPlan;

                poliza.Cliente.Nu_DNI             = model.DniCliente;
                poliza.Cliente.No_Cliente         = model.NombreCliente;
                poliza.Cliente.No_ApePaterno      = model.ApellidoPaternoCliente;
                poliza.Cliente.No_ApeMaterno      = model.ApellidoMaternoCliente;
                poliza.Cliente.Fe_Nacimiento      = Convert.ToDateTime(model.FechaNacimientoCliente);
                poliza.Cliente.Tx_LugarNacimiento = model.LugarNacimientoCliente;
                poliza.Cliente.Tx_Direccion       = model.DireccionCliente;
                poliza.Cliente.Fi_EstadoCivil     = model.EstadoCivilCliente;
                poliza.Cliente.Fi_Sexo            = model.SexoCliente;

                var beneficiario = poliza.Beneficiario.ElementAt(0);

                beneficiario.Num_DNI     = model.DniBeneficiario;
                beneficiario.Txt_Nombre  = model.NombreBeneficiario;
                beneficiario.Txt_Ape_Pat = model.ApellidoPaternoBeneficiario;
                beneficiario.Txt_Ape_Mat = model.ApellidoMaternoBeneficiario;
                beneficiario.Po_Cap_Aseg = model.PorcentajeCapitalAsegurado;
                beneficiario.Fec_Nac     = Convert.ToDateTime(model.FechaNacimientoBeneficiario);


                poliza.Ocupacion            = model.Ocupacion;
                poliza.Actividad            = model.Actividad;
                poliza.LugarTrabajo         = model.LugarTrabajo;
                poliza.IngresoMensual       = model.IngresoMensual;
                poliza.Horario              = model.Horario;
                poliza.ExpuestoAPeligro     = model.ExpuestoAPeligro;
                poliza.MedioTransporte      = model.MedioTransporte;
                poliza.FrecuenciaViaje      = model.FrecuenciaViaje;
                poliza.DeporteAficion       = model.DeporteAficion;
                poliza.RiesgoAccidente      = model.RiesgoAccidente;
                poliza.CoberturaRiego       = model.CoberturaRiego;
                poliza.Estatura             = model.Estatura;
                poliza.Peso                 = model.Peso;
                poliza.ConsumeTabaco        = model.ConsumeTabaco;
                poliza.ConsumeAlcohol       = model.ConsumeAlcohol;
                poliza.InsuficienciaRenal   = model.InsuficienciaRenal;
                poliza.Diabetes             = model.Diabetes;
                poliza.Cancer               = model.Cancer;
                poliza.Epilepsia            = model.Epilepsia;
                poliza.AfeccionCardiaca     = model.AfeccionCardiaca;
                poliza.HipertensionArterial = model.HipertensionArterial;
                poliza.TranstornoMental     = model.TranstornoMental;

                _polizaBL.Update(poliza);
                jsonResponse.Success = true;
                jsonResponse.Data    = Url.Action("Index", "Poliza");
            }
            catch (Exception)
            {
            }

            return(Json(jsonResponse, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// Add Update Data
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Jsonresponse</returns>
        public JsonResponse AddUpdate(ClientGroup model)
        {
            JsonResponse resp = new JsonResponse();

            try
            {
                if (model.Id == 0)
                {
                    if (!IsExsits(model.GroupName))
                    {
                        model.IsActive  = true;
                        model.CreatedOn = DateTime.Now;
                        model.CreatedBy = GetUserID();
                        _context.Set <ClientGroup>().Add(model);
                        int i = _context.SaveChanges();

                        if (i != 0)
                        {
                            resp.Status  = Constants.ResponseStatus.Success;
                            resp.Message = Constants.Service.Data_insert_success;
                        }
                        else
                        {
                            resp.Message = Constants.Service.Data_insert_failed;
                        }
                    }
                    else
                    {
                        resp.Message = Constants.ControllerMessage.Data_Exsists;
                    }
                }
                else
                {
                    resp.Message = Constants.Service.Data_Update_failed;
                    var models = GetData(model.Id);
                    if (models != null)
                    {
                        models.GroupName    = model.GroupName;
                        models.AddressLine1 = model.AddressLine1;
                        models.AddressLine2 = model.AddressLine2;
                        models.CountryID    = model.CountryID;
                        models.StateID      = model.StateID;
                        models.CityID       = model.CityID;
                        models.IsActive     = true;
                        models.ModifiedOn   = DateTime.Now;
                        models.ModifiedBy   = GetUserID();
                        _context.Set <ClientGroup>().Update(models);
                        int i = _context.SaveChanges();
                        if (i != 0)
                        {
                            resp.Status  = Constants.ResponseStatus.Success;
                            resp.Message = Constants.Service.Data_Update_success;
                        }
                    }
                }
            }
            catch (Exception)
            {
                resp.Message = Constants.Service.Common_message;
            }

            return(resp);
        }
コード例 #57
0
        /// <summary>
        /// The post response data.
        /// </summary>
        /// <param name="routeParams">
        /// The route parameters.
        /// </param>
        /// <returns>
        /// The <see cref="Response"/>.
        /// </returns>
        protected override Response PostResponseData(dynamic routeParams)
        {
            NpgsqlConnection  connection  = null;
            NpgsqlTransaction transaction = null;

            var sw = new Stopwatch();

            sw.Start();
            var    requestToken = this.GenerateRandomToken();
            string logMessage;

            try
            {
                logMessage = $"{requestToken} started";
                Logger.Info(this.ConstructLog(logMessage));

                HttpRequestHelper.ValidateSupportedQueryParameter(this.Request, this.RequestUtils, SupportedPostQueryParameter);

                var contentTypeRegex = new Regex("^multipart/.*;\\s*boundary=(.*)$", RegexOptions.IgnoreCase);
                var isMultiPart      = contentTypeRegex.IsMatch(this.Request.Headers.ContentType);

                logMessage = $"Request {requestToken} is mutlipart: {isMultiPart}";
                Logger.Debug(this.ConstructLog(logMessage));

                Stream bodyStream;
                Dictionary <string, Stream> fileDictionary = null;
                if (isMultiPart)
                {
                    bodyStream = this.ExtractJsonBodyStreamFromMultiPartMessage();

                    // - New File:
                    //      create -> File, FileRevision
                    //      update -> FileStore

                    // - New FileRevision:
                    //      create -> FileRevision
                    //      update -> File

                    // - Update File:
                    //      update -> File

                    // - ANY Filerevision metadata object in operation without contentHash -> ERROR.
                    // - NO matching file hash found in request body and NO matching file hash found on server -> ERROR
                    // - Matching file hash found in request body ??? is allready checked to find binary in request...
                    // - ANY file binary in request without corresponding metadata -> ERROR
                    fileDictionary = new Dictionary <string, Stream>();
                    foreach (var uploadedFile in this.Request.Files.ToList().Where(f => f.ContentType == this.MimeTypeOctetStream))
                    {
                        var hash = this.FileBinaryService.CalculateHashFromStream(uploadedFile.Value);

                        logMessage = $"File with hash {hash} present in request: {requestToken}";
                        Logger.Debug(this.ConstructLog(logMessage));

                        fileDictionary.Add(hash, uploadedFile.Value);
                    }
                }
                else
                {
                    // use the single request (JSON) stream
                    bodyStream = this.Request.Body;
                }

                this.JsonSerializer.Initialize(this.RequestUtils.MetaInfoProvider, this.RequestUtils.GetRequestDataModelVersion);
                var operationData = this.JsonSerializer.Deserialize <CdpPostOperation>(bodyStream);

                // get prepared data source transaction
                var credentials = this.RequestUtils.Context.AuthenticatedCredentials;
                transaction = this.TransactionManager.SetupTransaction(ref connection, credentials);

                // the route pattern enforces that there is atleast one route segment
                string[] routeSegments = string.Format("{0}/{1}", TopContainer, routeParams.uri)
                                         .Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);

                var resourceProcessor = new ResourceProcessor(
                    this.ServiceProvider,
                    transaction,
                    this.RequestUtils);

                var modelSetup = this.DetermineEngineeringModelSetup(resourceProcessor, routeSegments);
                var partition  = this.RequestUtils.GetEngineeringModelPartitionString(modelSetup.EngineeringModelIid);

                if (credentials != null)
                {
                    credentials.EngineeringModelSetup = modelSetup;
                    this.PersonResolver.ResolveParticipantCredentials(transaction, credentials);
                    credentials.IsParticipant = true;

                    this.PermissionService.Credentials = credentials;
                }

                // defer all reference data check until after transaction commit
                using (var command = new NpgsqlCommand("SET CONSTRAINTS ALL DEFERRED;", transaction.Connection, transaction))
                {
                    command.ExecuteAndLogNonQuery(this.TransactionManager.CommandLogger);
                }

                // retrieve the revision for this transaction (or get next revision if it does not exist)
                var transactionRevision = this.RevisionService.GetRevisionForTransaction(transaction, partition);

                this.OperationProcessor.Process(operationData, transaction, partition, fileDictionary);

                // save revision-history
                var actor         = credentials.Person.Iid;
                var changedThings = (IEnumerable <Thing>) this.RevisionService.SaveRevisions(transaction, partition, actor, transactionRevision);

                transaction.Commit();

                if (this.RequestUtils.QueryParameters.RevisionNumber == -1)
                {
                    Logger.Info("{0} completed in {1} [ms]", requestToken, sw.ElapsedMilliseconds);
                    return(this.GetJsonResponse(changedThings.ToList(), this.RequestUtils.GetRequestDataModelVersion));
                }

                Logger.Info(this.ConstructLog());
                var fromRevision = this.RequestUtils.QueryParameters.RevisionNumber;

                // use new transaction to include latest database state
                transaction = this.TransactionManager.SetupTransaction(ref connection, credentials);
                var revisionResponse = ((IEnumerable <Thing>) this.RevisionService.Get(transaction, partition, fromRevision)).ToArray();
                transaction.Commit();

                Logger.Info("{0} completed in {1} [ms]", requestToken, sw.ElapsedMilliseconds);

                return(this.GetJsonResponse(revisionResponse, this.RequestUtils.GetRequestDataModelVersion));
            }
            catch (InvalidOperationException ex)
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }

                Logger.Error(ex, this.ConstructFailureLog($"{requestToken} failed after {sw.ElapsedMilliseconds} [ms]"));

                // error handling
                var errorResponse = new JsonResponse($"exception:{ex.Message}", new DefaultJsonSerializer());
                return(errorResponse.WithStatusCode(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }

                Logger.Error(ex, this.ConstructFailureLog($"{requestToken} failed after {sw.ElapsedMilliseconds} [ms]"));

                // error handling
                var errorResponse = new JsonResponse($"exception:{ex.Message}", new DefaultJsonSerializer());
                return(errorResponse.WithStatusCode(HttpStatusCode.InternalServerError));
            }
            finally
            {
                transaction?.Dispose();
                connection?.Dispose();
            }
        }
コード例 #58
0
        public virtual async Task <ActionResult> EditRole(Guid roleId, string roleName, string tempRoleName)
        {
            JsonResponse response = new JsonResponse();

            if (string.IsNullOrEmpty(roleName))
            {
                response.Success  = false;
                response.Message  = "You must enter a role name.";
                response.CssClass = "red";

                return(Json(response));
            }

            try
            {
                if (roleName.ToLower().Equals(tempRoleName.ToLower()))
                {
                    Role dbItem = await roleRepo.FindByRoleIdAsync(roleId);

                    dbItem.RoleName = roleName;

                    await roleRepo.EditAsync(dbItem);

                    if (Request.IsAjaxRequest())
                    {
                        response.Success  = true;
                        response.Message  = "Role edited successfully!";
                        response.CssClass = "green";

                        return(Json(response));
                    }
                }

                if (!roleService.RoleExists(roleName))
                {
                    Role dbItem = await roleRepo.FindByRoleIdAsync(roleId);

                    dbItem.RoleName = roleName;

                    await roleRepo.EditAsync(dbItem);

                    if (Request.IsAjaxRequest())
                    {
                        response.Success  = true;
                        response.Message  = "Role edited successfully!";
                        response.CssClass = "green";

                        return(Json(response));
                    }
                }
                else
                {
                    if (Request.IsAjaxRequest())
                    {
                        response.Success  = false;
                        response.Message  = "Role already exists!";
                        response.CssClass = "red";

                        return(Json(response));
                    }
                }

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                if (Request.IsAjaxRequest())
                {
                    response.Success  = false;
                    response.Message  = ex.Message;
                    response.CssClass = "red";

                    return(Json(response));
                }

                ModelState.AddModelError("", ex.Message);
            }

            return(RedirectToAction("Index"));
        }
コード例 #59
0
        public virtual ActionResult RevokeModulesForRole(string RoleId, string Modules)
        {
            //JsonResponse response = new JsonResponse();
            //response.Messages = new List<ResponseItem>();

            //string[] moduleIds = Modules.Split(',');
            //StringBuilder sb = new StringBuilder();

            //ResponseItem item = null;

            //foreach (string s in moduleIds)
            //{
            //    if (!string.IsNullOrWhiteSpace(s))
            //    {
            //        try
            //        {
            //            //remove action in repo
            //            repoModulesInRole.DeleteByModule(new Guid(s));

            //            ////remove action in ModulesInRole
            //            //modulesInRoleRepo.RemoveAction(new Guid(moduleId), new Guid(s));

            //            ////remove all empty actions in ModulesInRole
            //            //modulesInRoleRepo.DeleteByModule(new Guid(moduleId));

            //            item = new ResponseItem();
            //            item.Success = true;
            //            response.Message = moduleRepo.FindByPk(new Guid(s)).ModuleName + " was removed successfully!";
            //            response.CssClass = "green";
            //            response.Messages.Add(item);
            //        }
            //        catch (Exception ex)
            //        {
            //            item = new ResponseItem();
            //            item.Success = false;
            //            response.Success = false;
            //            response.Message = ex.Message;
            //            response.CssClass = "red";
            //            response.Messages.Add(item);
            //        }
            //    }
            //}

            //return Json(response);
            JsonResponse response = new JsonResponse();

            response.Messages = new List <ResponseItem>();

            string[]      moduleIds = Modules.Split(',');
            StringBuilder sb        = new StringBuilder();

            ResponseItem item = null;

            try
            {
                roleRepo.AddModuleAndAction(moduleIds, RoleId);

                item              = new ResponseItem();
                item.Success      = true;
                response.Message  = "modules was added successfully!";
                response.CssClass = "green";
                response.Messages.Add(item);
            }
            catch (Exception ex)
            {
                item         = new ResponseItem();
                item.Success = false;
                if (moduleIds == null)
                {
                    item              = new ResponseItem();
                    item.Success      = true;
                    response.Message  = "modules was added successfully!";
                    response.CssClass = "green";
                    response.Messages.Add(item);
                }
                else
                {
                    response.Success  = false;
                    response.Message  = ex.Message;
                    response.CssClass = "red";
                    response.Messages.Add(item);
                }
            }
            return(Json(response));
        }
コード例 #60
0
        public JsonResult CustomerSave(BusinessPartnerModel model, int mode = 0)
        {
            var jsonReturn = new JsonResponse();

            using (var db = new FTTxEntities())
            {
                try
                {
                    string responseMessage = String.Empty;
                    var    sap             = new FTTx();

                    model.Cellular = new StringBuilder(System.Text.RegularExpressions.Regex.Replace(model.Cellular, "[^0-9]", "")).ToString();

                    if (mode == 0)
                    {
                        string prefix       = "C";
                        int    newCode      = 1;
                        var    lastCardCode = db.OCRD.Where(r => r.CardCode.Substring(0, 3) == prefix + model.ProvinceId).OrderByDescending(r => r.CardCode.Substring(3)).Select(r => r.CardCode.Substring(3)).FirstOrDefault();
                        if (lastCardCode != null)
                        {
                            newCode = int.Parse(lastCardCode) + 1;
                        }

                        model.CustomerCode = string.Format("{0}{1}{2}", prefix, model.ProvinceId, newCode.ToString().PadLeft(6, '0'));

                        sap.Connecting(out responseMessage);
                        if (sap.company.Connected)
                        {
                            SAPbobsCOM.BusinessPartners bp = (SAPbobsCOM.BusinessPartners)sap.company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oBusinessPartners);
                            bp.GroupCode    = 103;
                            bp.CardType     = SAPbobsCOM.BoCardTypes.cCustomer;
                            bp.CardCode     = model.CustomerCode;
                            bp.CardName     = model.CustomerName;
                            bp.FederalTaxID = model.CardNo;
                            bp.Frozen       = model.FrozenFor == "Y" ? SAPbobsCOM.BoYesNoEnum.tYES : SAPbobsCOM.BoYesNoEnum.tNO;
                            bp.Address      = model.Address;
                            bp.Block        = model.District;
                            bp.County       = model.Amphur;
                            bp.City         = model.ProvinceName;
                            bp.ZipCode      = model.Zipcode;
                            bp.Cellular     = model.Cellular;
                            bp.EmailAddress = model.Email;

                            bp.MailAddress           = model.Address;
                            bp.Addresses.AddressType = SAPbobsCOM.BoAddressType.bo_ShipTo;
                            bp.Addresses.AddressName = "Ship to";
                            bp.Addresses.Block       = model.District;
                            bp.Addresses.County      = model.Amphur;
                            bp.Addresses.City        = model.ProvinceName;
                            bp.Addresses.ZipCode     = model.Zipcode;
                            if (!string.IsNullOrEmpty(model.Cellular))
                            {
                                bp.UserFields.Fields.Item("U_InsTel").Value = model.Cellular;
                            }

                            if (!string.IsNullOrEmpty(model.Address))
                            {
                                bp.UserFields.Fields.Item("U_StmAddr").Value = bp.Address;
                            }
                            if (!string.IsNullOrEmpty(model.District))
                            {
                                bp.UserFields.Fields.Item("U_StmBlck").Value = model.District;
                            }
                            if (!string.IsNullOrEmpty(model.Amphur))
                            {
                                bp.UserFields.Fields.Item("U_StmCnty").Value = model.Amphur;
                            }
                            if (!string.IsNullOrEmpty(model.ProvinceName))
                            {
                                bp.UserFields.Fields.Item("U_StmCity").Value = model.ProvinceName;
                            }
                            if (!string.IsNullOrEmpty(model.Zipcode))
                            {
                                bp.UserFields.Fields.Item("U_StmZipC").Value = model.Zipcode;
                            }
                            if (!string.IsNullOrEmpty(model.Cellular))
                            {
                                bp.UserFields.Fields.Item("U_Bphone").Value = model.Cellular;
                            }

                            if (0 != bp.Add())
                            {
                                jsonReturn = new JsonResponse {
                                    status = false, message = sap.company.GetLastErrorDescription()
                                };
                            }
                            else
                            {
                                jsonReturn = new JsonResponse {
                                    status = true, message = "บันทึกข้อมูลเรียบร้อยแล้ว"
                                };
                            }

                            sap.company.Disconnect();
                        }
                        else
                        {
                            jsonReturn = new JsonResponse()
                            {
                                status = false, message = responseMessage
                            };
                        }
                    }
                    else
                    {
                        sap.Connecting(out responseMessage);
                        if (sap.company.Connected)
                        {
                            SAPbobsCOM.BusinessPartners bp = (SAPbobsCOM.BusinessPartners)sap.company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oBusinessPartners);
                            bp.GetByKey(model.CustomerCode);

                            bp.CardName     = model.CustomerName;
                            bp.FederalTaxID = model.CardNo;
                            bp.Frozen       = model.FrozenFor == "Y" ? SAPbobsCOM.BoYesNoEnum.tYES : SAPbobsCOM.BoYesNoEnum.tNO;
                            bp.Address      = model.Address;
                            bp.Block        = model.District;
                            bp.County       = model.Amphur;
                            bp.City         = model.ProvinceName;
                            bp.ZipCode      = model.Zipcode;
                            bp.Cellular     = model.Cellular;
                            bp.EmailAddress = model.Email;

                            bp.MailAddress       = model.Address;
                            bp.Addresses.Block   = model.District;
                            bp.Addresses.County  = model.Amphur;
                            bp.Addresses.City    = model.ProvinceName;
                            bp.Addresses.ZipCode = model.Zipcode;
                            if (!string.IsNullOrEmpty(model.Cellular))
                            {
                                bp.UserFields.Fields.Item("U_InsTel").Value = model.Cellular;
                            }

                            if (!string.IsNullOrEmpty(model.Address))
                            {
                                bp.UserFields.Fields.Item("U_StmAddr").Value = bp.Address;
                            }
                            if (!string.IsNullOrEmpty(model.District))
                            {
                                bp.UserFields.Fields.Item("U_StmBlck").Value = model.District;
                            }
                            if (!string.IsNullOrEmpty(model.Amphur))
                            {
                                bp.UserFields.Fields.Item("U_StmCnty").Value = model.Amphur;
                            }
                            if (!string.IsNullOrEmpty(model.ProvinceName))
                            {
                                bp.UserFields.Fields.Item("U_StmCity").Value = model.ProvinceName;
                            }
                            if (!string.IsNullOrEmpty(model.Zipcode))
                            {
                                bp.UserFields.Fields.Item("U_StmZipC").Value = model.Zipcode;
                            }
                            if (!string.IsNullOrEmpty(model.Cellular))
                            {
                                bp.UserFields.Fields.Item("U_Bphone").Value = model.Cellular;
                            }

                            if (0 != bp.Update())
                            {
                                jsonReturn = new JsonResponse {
                                    status = false, message = sap.company.GetLastErrorDescription()
                                };
                            }
                            else
                            {
                                jsonReturn = new JsonResponse {
                                    status = true, message = "บันทึกข้อมูลเรียบร้อยแล้ว"
                                };
                            }

                            sap.company.Disconnect();
                        }
                        else
                        {
                            jsonReturn = new JsonResponse()
                            {
                                status = false, message = responseMessage
                            };
                        }
                    }
                }
                catch (Exception ex)
                {
                    jsonReturn = new JsonResponse {
                        status = false, message = ex.Message
                    };
                    Log.Error(this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + " Error -> " + ex.Message);
                }
            }
            return(Json(jsonReturn));
        }