예제 #1
0
        public void CreateBusiness()
        {
            IService service = new Service();
            Business b       = new Business();

            b.Id        = 1;
            b.Name      = "SKY";
            b.Employees = new List <Person>();
            Person p = new Person();

            p.Id   = 1;
            p.Name = "Sepehr";
            b.Employees.Add(p);
            service.Add(b);

            Business sky = service.GetById(1);

            Assert.IsNotNull(sky);
        }
예제 #2
0
        public ActionResult Create(RoleEntity entity, List <PermissionDescriptor> PermissionSet)
        {
            Service.Add(entity);
            var permissions = new List <Permission>();

            PermissionSet.Where(m => m.Checked ?? false).Each(m =>
            {
                permissions.Add(new Permission
                {
                    RoleId        = entity.ID,
                    PermissionKey = m.Key,
                    Module        = m.Module,
                    Title         = m.Title,
                    ActionType    = ActionType.Create
                });
            });
            _permissionService.AddRange(permissions.ToArray());
            return(RedirectToAction("Index"));
        }
예제 #3
0
        public virtual HttpResponseMessage Follow(int entityTypeId, int entityId, [FromUri(BinderType = typeof(TypeConverterModelBinder))] string purposeKey = null)
        {
            /*
             * 4/23/2021 - Daniel
             * The weird BinderType thing allows the user to do ?purposeKey=
             * to pass a blank purpose key, otherwise it throws a required value
             * error even though it's not required.
             */
            var person = GetPerson();

            if (person == null)
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            SetProxyCreation(true);

            var following = new Following
            {
                EntityTypeId  = entityTypeId,
                EntityId      = entityId,
                PersonAliasId = GetPerson().PrimaryAliasId.Value,
                PurposeKey    = purposeKey
            };

            Service.Add(following);

            if (!following.IsValid)
            {
                return(ControllerContext.Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest,
                           string.Join(",", following.ValidationResults.Select(r => r.ErrorMessage).ToArray())));
            }

            System.Web.HttpContext.Current.AddOrReplaceItem("CurrentPerson", GetPerson());

            Service.Context.SaveChanges();

            var response = ControllerContext.Request.CreateResponse(HttpStatusCode.Created, following.Id);

            return(response);
        }
예제 #4
0
        public JsonResult Save(string id, string title, string parentId)
        {
            MediaEntity entity = null;

            if (id.IsNotNullAndWhiteSpace() && title.IsNotNullAndWhiteSpace())
            {
                var media = Service.Get(id);
                media.Title = title;
                Service.Update(media);
                entity = Service.Get(id);
            }
            else if (title.IsNotNullAndWhiteSpace())
            {
                entity = new MediaEntity {
                    Title = title, MediaType = (int)MediaType.Folder, ParentID = parentId
                };
                Service.Add(entity);
            }
            return(Json(entity));
        }
예제 #5
0
        public ActionResult Index()
        {
            var TotalResult = client.Add(5, 8);

            ViewBag.Result1 = TotalResult;

            var TotalSubstract = client.Substract(5, 8);

            ViewBag.Result2 = TotalSubstract;

            var TotalMultiple = _clientInternal.Multiple(12, 12);

            ViewBag.Result3 = TotalMultiple;

            var TotalDivision = _clientInternal.Division(12, 0);

            ViewBag.Result4 = TotalDivision;

            return(View());
        }
        public ArticleVM Add(ArticleVM article)
        {
            Article service_result = service.Add(new Article
            {
                Author_ID    = article.Author_ID,
                Category_ID  = article.Category_ID,
                Created_Date = DateTime.Now,
                Is_Deleted   = false,
                Post_Content = article.Post_Content,
                Tags         = article.Tags,
                Title        = article.Title,
                ViewCount    = 0
            });

            service.Save();

            ArticleVM api_result = Mapper.Map <Article, ArticleVM>(service_result);

            return(api_result);
        }
예제 #7
0
        public IActionResult Put(LocaleResourceForm model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                foreach (var item in model.ResourceValues)
                {
                    var source = new LocaleResource()
                    {
                        LanguageId    = item.LanguageId,
                        ResourceName  = model.ResourceName,
                        ResourceValue = string.IsNullOrWhiteSpace(item.Value) ? "" : item.Value,
                        CreatedAt     = DateTime.Now,
                        CreatedBy     = CurrentUser?.Id
                    };

                    if (item.LocaleResourceId.HasValue)
                    {
                        var resource = Service.GetById(item.LocaleResourceId);
                        resource.Update(source);
                        resource.LastEditedBy   = CurrentUser?.Id;
                        resource.LastUpdateTime = DateTime.Now;
                        Service.Update(resource);
                    }
                    else
                    {
                        Service.Add(source);
                    }
                }

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
        public async Task <ActionResult <Category> > Post
        (
            [FromBody] Category model
        )
        {
            try
            {
                service.Add(model);

                if (await service.SaveChangesAsync())
                {
                    return(Created($"/api/category/{model.Id}", model));
                }

                return(BadRequest());
            }
            catch (Exception err)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, "Banco de dados falhou " + err.Message + " " + err.InnerException));
            }
        }
예제 #9
0
        public IHttpActionResult AddNewEvent()
        {
            try
            {
                var newEvent = new Event
                {
                    Name        = "Movie Logan",
                    Description = "Logan Description",
                    EventType   = Enums.EventType.Cinema,
                    StartDate   = DateTime.UtcNow,
                    ImageId     = null
                };
                Service.Add(newEvent);

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
예제 #10
0
파일: Program.cs 프로젝트: Mortion/Uses
        static void Main(string[] args)
        {
            Properties p = new Properties()
            {
                Name = "jarrik van camp",
                Email = "*****@*****.**"

            };
            Service service = new Service();

            service.Add(p);

            List<Properties> props = new List<Properties>();
            props = service.GetAll();

            foreach (var prop in props)
            {
                Console.WriteLine(prop.ToString());
            }
            Console.Read();
        }
예제 #11
0
        public ActionResult Add(CompanyDto companydto)
        {
            ResultJsonInfo resultJsonInfo = new ResultJsonInfo()
            {
                Data = "", ErrorMsg = "", Success = true
            };

            if (companydto != null)
            {
                companydto.CreateUser  = ServiceHelper.GetCurrentUser().UserName;
                companydto.CredateTime = DateTime.Now;
                if (!Service.Add(companydto))
                {
                    resultJsonInfo.Success  = false;
                    resultJsonInfo.ErrorMsg = "添加失敗";
                    return(Content("<script>alert('添加失敗');history.go(-1);</script>"));
                }
            }
            //return Content("<script>alert('添加成功');</script>");
            return(this.Ajax_JGClose());
        }
예제 #12
0
        public async Task <IActionResult> Upload(string parentId, string folder, long size)
        {
            if (Request.Form.Files.Count > 0)
            {
                if (folder.IsNotNullAndWhiteSpace())
                {
                    var parent = Service.Get(m => m.Title == folder && m.MediaType == (int)MediaType.Folder).FirstOrDefault();
                    if (parent == null)
                    {
                        parent = new MediaEntity
                        {
                            Title     = folder,
                            MediaType = (int)MediaType.Folder,
                            ParentID  = "#"
                        };
                        Service.Add(parent);
                    }
                    parentId = parent.ID;
                }
                parentId = parentId ?? "#";
                string fileName = Path.GetFileName(Request.Form.Files[0].FileName);
                var    entity   = new MediaEntity
                {
                    ParentID = parentId,
                    Title    = fileName,
                    Status   = Request.Form.Files[0].Length == size ? (int)RecordStatus.Active : (int)RecordStatus.InActive
                };
                string extension = Path.GetExtension(fileName).ToLower();
                string fileId    = new Easy.IDGenerator().CreateStringId();
                entity.Url = await _storage.SaveFileAsync(Request.Form.Files[0].OpenReadStream(), $"{fileId}{extension}");

                if (entity.Url.IsNotNullAndWhiteSpace())
                {
                    Service.Add(entity);
                    entity.Url = Url.Content(entity.Url);
                }
                return(Json(entity));
            }
            return(Json(false));
        }
예제 #13
0
        public ActionResult Create(AddEditBookModel model)
        {
            if (ModelState.IsValid)
            {
                var book = Mapper.Map <BookFullModel, Book>(model.Book);

                book.ImageFile = _fileService.SaveImage(model.Book.Image, null, model.IsImageChanged);

                Service.Add(book);

                return(RedirectToAction("Index", new
                {
                    id = model.Book.GenreId
                }));
            }
            else
            {
                FillDicts();

                return(View("CreateEdit", model));
            }
        }
예제 #14
0
            public void Run()
            {
                int var1 = 5;
                int var2 = 7;

                // instantiate the web service proxy
                Service theWebSvc = new Service();

                // call the add method
                Console.WriteLine("{0} + {1} = {2}", var1, var2,
                                  theWebSvc.Add(var1, var2));

                // build a table by repeatedly calling the pow method
                for (int i = 2; i < 10; i++)
                {
                    for (int j = 1; j < 10; j++)
                    {
                        Console.WriteLine("{0} to the power of {1} = {2}", i, j,
                                          theWebSvc.Pow(i, j));
                    }
                }
            }
예제 #15
0
        public async Task Test8()
        {
            MockServer server  = new MockServer("test8");
            var        service = new Service();

            service.Add(
                (ServiceContext context) => context.RemoteEndPoint.ToString(),
                "getAddress"
                );
            service.Bind(server);
            var client = new Client("mock://test8");
            var log    = new Log();

            client.Use(log.IOHandler).Use(log.InvokeHandler);
            Console.WriteLine(await client.InvokeAsync <string>("getAddress"));
            Console.WriteLine(await client.InvokeAsync <string>("getAddress"));
            await client.Abort();

            Console.WriteLine(await client.InvokeAsync <string>("getAddress"));
            Console.WriteLine(await client.InvokeAsync <string>("getAddress"));
            server.Close();
        }
예제 #16
0
        public async Task Test8()
        {
            UdpClient server  = new UdpClient(8422);
            var       service = new Service();

            service.Add(
                (ServiceContext context) => context.RemoteEndPoint.ToString(),
                "getAddress"
                );
            service.Bind(server);
            var client = new Client("udp4://127.0.0.1:8422");
            var log    = new Log();

            client.Use(log.IOHandler).Use(log.InvokeHandler);
            Console.WriteLine(await client.InvokeAsync <string>("getAddress").ConfigureAwait(false));
            Console.WriteLine(await client.InvokeAsync <string>("getAddress").ConfigureAwait(false));
            await client.Abort().ConfigureAwait(false);

            Console.WriteLine(await client.InvokeAsync <string>("getAddress").ConfigureAwait(false));
            Console.WriteLine(await client.InvokeAsync <string>("getAddress").ConfigureAwait(false));
            server.Close();
        }
예제 #17
0
        public void GetEstimations_ShouldReturnShapesDescriptionAndEstimationsAsStringCollection()
        {
            AbstractShape shape = new Circle()
            {
                Name = "CircleName", Surface = 12
            };
            string expectedEstimation = string.Format("{0} - {1} - {2}{3} - Estimation cout : {4}€",
                                                      shape.GetShapeType(), shape.Name, shape.Surface, shape.GetSurfaceUnit(), 2 * shape.Surface);

            var pricerMock = new Mock <IPricer>();

            pricerMock
            .Setup(x => x.Price(It.IsAny <int>()))
            .Returns <int>((b) => b * 2);
            Service service = new Service();

            service.Add(shape);

            IEnumerable <string> actualeShapesEstimations = service.GetEstimations(pricerMock.Object);

            Assert.IsNotNull(actualeShapesEstimations.SingleOrDefault(x => x == expectedEstimation));
        }
예제 #18
0
        private static void Add()
        {
            //get the existing list of players
            _playerList = _playerService.GetAll();

            //instantiate the new player object
            Player player = new Player();

            //for each property get info from the user
            player = ConsoleInput.GetUserInput <Player>();

            //get the current date and time for DateAdded
            player.DateAdded = DateTime.Now;

            //call the player service and add the player
            player = _playerService.Add(player);

            //give the user feed back--pause for one second on screen
            string message = $"Success: Added a new player ID: {player.Player_Id}";

            ConsoleMessage.ShowMessage(message);
        }
예제 #19
0
        protected override void OnStart()
        {
            base.OnStart();
            InitService();

            var button1 = FindViewById <Button> (Resource.Id.buttonCalc);

            button1.Click += (sender, e) => {
                if (IsBound)
                {
                    var text1  = FindViewById <EditText> (Resource.Id.value1);
                    var text2  = FindViewById <EditText> (Resource.Id.value2);
                    var result = FindViewById <TextView> (Resource.Id.result);

                    int v1;
                    int v2;
                    int v3;

                    if (Int32.TryParse(text2.Text, out v2) && Int32.TryParse(text1.Text, out v1))
                    {
                        v3 = Service.Add(v1, v2);
                    }
                    else
                    {
                        v3 = 0;
                        var builder = new AlertDialog.Builder(this);
                        builder.SetMessage("Spaces or special character are not allowed");
                        builder.SetNeutralButton("OK", (source, eventArgs) => {});
                        builder.Show();
                    }

                    result.Text = v3.ToString();
                }
                else
                {
                    Log.Warn(Tag, "The AdditionService is not bound");
                }
            };
        }
예제 #20
0
        public virtual HttpResponseMessage Follow(int entityTypeId, int entityId)
        {
            var person = GetPerson();

            if (person == null)
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            SetProxyCreation(true);

            var following = new Following
            {
                EntityTypeId  = entityTypeId,
                EntityId      = entityId,
                PersonAliasId = GetPerson().PrimaryAliasId.Value
            };

            Service.Add(following);

            if (!following.IsValid)
            {
                return(ControllerContext.Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest,
                           string.Join(",", following.ValidationResults.Select(r => r.ErrorMessage).ToArray())));
            }

            if (!System.Web.HttpContext.Current.Items.Contains("CurrentPerson"))
            {
                System.Web.HttpContext.Current.Items.Add("CurrentPerson", GetPerson());
            }

            Service.Context.SaveChanges();

            var response = ControllerContext.Request.CreateResponse(HttpStatusCode.Created, following.Id);

            return(response);
        }
예제 #21
0
 public IActionResult AddMovie(MovieDetailModel movieDetailModel, IFormFile file)
 {
     log.Info("Adding a movie started....");
     try
     {
         movieDetailModel.Poster = Path.GetExtension(file.FileName);
         Service.Add(movieDetailModel);
     }
     catch (Exception ex)
     {
         log.Error(ex);
     }
     if (file != null)
     {
         string ImageName = movieDetailModel.Id + Path.GetExtension(file.FileName);
         string SavePath  = Path.Combine(_configuration["ImagesFolder"], ImageName);
         using (var stream = new FileStream(SavePath, FileMode.Create))
         {
             file.CopyTo(stream);
         }
     }
     return(RedirectToAction("Index"));
 }
예제 #22
0
        public JsonResult Save(string id, string title, string parentId)
        {
            MediaEntity entity = null;

            if (id.IsNotNullAndWhiteSpace() && title.IsNotNullAndWhiteSpace())
            {
                DataFilter filter = new DataFilter(new List <string> {
                    "Title"
                });
                Service.Update(new MediaEntity {
                    Title = title
                }, filter.Where("ID", OperatorType.Equal, id));
                entity = Service.Get(id);
            }
            else if (title.IsNotNullAndWhiteSpace())
            {
                entity = new MediaEntity {
                    Title = title, MediaType = (int)MediaType.Folder, ParentID = parentId
                };
                Service.Add(entity);
            }
            return(Json(entity));
        }
예제 #23
0
        public ActionResult Add(UserDto userDto)
        {
            ResultJsonInfo resultJsonInfo = new ResultJsonInfo()
            {
                Data = "", ErrorMsg = "", Success = true
            };

            if (ModelState.IsValid)
            {
            }
            if (userDto != null)
            {
                userDto.CreateUser  = ServiceHelper.GetCurrentUser().LoginName;
                userDto.CredateTime = DateTime.Now.Date;
                if (!Service.Add(userDto))
                {
                    resultJsonInfo.Success  = false;
                    resultJsonInfo.ErrorMsg = "添加失败!";
                }
            }
            return(this.Ajax_JGClose());
            //  return Json(new { resultJsonInfo }, JsonRequestBehavior.AllowGet);
        }
예제 #24
0
        public ActionResult Add(Model.Dto.MenuTree menuDto)
        {
            ResultJsonInfo resultJsonInfo = new ResultJsonInfo()
            {
                Data = "", ErrorMsg = "", Success = true
            };

            if (ModelState.IsValid)
            {
                menuDto.CreateUser  = ServiceHelper.GetCurrentUser().LoginName;
                menuDto.CredateTime = DateTime.Now.Date;
                if (Service.Add(menuDto))
                {
                    return(this.Ajax_JGClose());
                }
                else
                {
                    resultJsonInfo.Success  = false;
                    resultJsonInfo.ErrorMsg = "添加失败!";
                }
            }
            return(View());
        }
예제 #25
0
        protected override void Save()
        {
            if (!Validate())
            {
                return;
            }
            IsObjectLoading = true;
            if (Object.ID == 0)
            {
                IObservable <T> addObs = Observable.FromAsync(() => Service.Add(Mapper.Map <TDetailViewModel, T>(Object)));

                addObs.Select((o) => Mapper.Map <TDetailViewModel>(o)).Subscribe((res) => {
                    Object = res;
                    OnAdd();
                    EditMode        = EditMode.ReadOnly;
                    IsObjectLoading = false;
                }, (e) => {
                    ShowMessageBox("Error occured while adding data.", "Error", System.Windows.MessageBoxButton.OK);
                    IsObjectLoading = false;
                });
            }
            else
            {
                IObservable <T> updateObs = Observable.FromAsync(() => Service.Update(Mapper.Map <TDetailViewModel, T>(Object)));
                updateObs.Subscribe((res) => {
                    editableObject.EndEdit();
                    editableObject = null;
                    Object         = Mapper.Map <TDetailViewModel>(res);
                    OnSave();
                    EditMode        = EditMode.ReadOnly;
                    IsObjectLoading = false;
                }, (e) => {
                    ShowMessageBox("Error occured while saving data.", "Error", System.Windows.MessageBoxButton.OK);
                    IsObjectLoading = false;
                });
            }
        }
예제 #26
0
        /// <summary>
        /// В случае отсутствия Псалма с таким номером в БД добавляет его
        /// </summary>
        /// <param name="currentPsalm"></param>
        private void InsertOrUpdatePsalm(Psalm currentPsalm)
        {
            var response = Service.Get(new GetPsalmRequest()
            {
                Number = currentPsalm.Number
            });

            currentPsalm.Definition = GetDefinition(currentPsalm);

            if (response.Psalm == null)
            {
                Service.Add(new AddPsalmRequest()
                {
                    Psalm = currentPsalm
                });
            }
            else
            {
                Service.Update(new UpdatePsalmRequest()
                {
                    Psalm = currentPsalm
                });
            }
        }
예제 #27
0
        public async Task <IActionResult> Post([FromBody] ITechnologyViewModel technology)
        {
            try
            {
                var data = await Service.Add(technology);

                return(Ok(new OneDATApiResponse("Inserted Successfully", data)));
            }
            catch (OneDATException ex)
            {
                if (ex.Code == OneDATExceptionCode.AlreadyExists)
                {
                    return(Conflict(new OneDATApiResponse("Data AlreadyExists", false)));
                }
                else
                {
                    return(BadRequest(new OneDATApiResponse(ex.Message, false)));
                }
            }
            catch (Exception ex)
            {
                return(ServerError("Error Adding Records in technology", false, ex));
            }
        }
예제 #28
0
        public ActionResult Add(ButtonDto buttonDto)
        {
            ResultJsonInfo resultJsonInfo = new ResultJsonInfo()
            {
                Data = "", ErrorMsg = "", Success = true
            };

            if (ModelState.IsValid)
            {
                buttonDto.CreateUser  = ServiceHelper.GetCurrentUser().LoginName;
                buttonDto.CredateTime = DateTime.Now.Date;
                if (!Service.Add(buttonDto))
                {
                    resultJsonInfo.Success  = false;
                    resultJsonInfo.ErrorMsg = "添加失败!";
                }
                return(this.Ajax_JGCloseAndMessage("保存成功"));
            }
            else
            {
                return(View());
            }
            //  return Json(new { resultJsonInfo }, JsonRequestBehavior.AllowGet);
        }
예제 #29
0
        public ActionResult Create(commentaire c, int id, int idemp)
        {
            IUnitOfWork            Uok       = new UnitOfWork(Factory);
            IService <commentaire> jbService = new Service <commentaire>(Uok);
            List <commentaire>     appo      = new List <commentaire>();

            appo = jbService.GetAll().ToList();
            for (int i = appo.Count - 1; i >= 0; i--)
            {
                if (appo[i].commentaireEvzl360_id == id && appo[i].employecommentaire_id == idemp)
                {
                    return(View("Exist"));
                }
            }
            c.commentaireEvzl360_id = id;
            c.employecommentaire_id = idemp;
            jbService.Add(c);
            jbService.Commit();
            String y = (string)System.Web.HttpContext.Current.Session["id"].ToString();
            int    x = int.Parse(y);

            ViewBag.idemploye = x;
            return(RedirectToAction("IndexByEmp", new { idemploye = x }));
        }
예제 #30
0
        public override IActionResult Edit(string id, RecoveryForm model)
        {
            if (ModelState.IsValid)
            {
                var User = _userHelper.GetUser(id);
                if (User != null)
                {
                    // Insert Vacancy
                    var NewVacancy = new VacancyList();
                    NewVacancy.AccountNameId         = model.AccountNameId;
                    NewVacancy.ApproverOneId         = model.ApproverOneId;
                    NewVacancy.ApproverTwoId         = model.SourcingId;
                    NewVacancy.CostCodeId            = model.CostCodeId;
                    NewVacancy.CreatedAt             = DateTime.Now;
                    NewVacancy.DepartmentId          = model.DepartmentId;
                    NewVacancy.DepartmentSubId       = model.DepartmentSubId;
                    NewVacancy.JobStageId            = model.JobStageId;
                    NewVacancy.JoinDate              = model.JoinDate;
                    NewVacancy.NetworkId             = model.NetworkId;
                    NewVacancy.NoarmalRate           = model.NoarmalRate;
                    NewVacancy.OtLevel               = model.OtLevel;
                    NewVacancy.RequestBy             = _userHelper.GetUserProfile(model.ApproverOneId);
                    NewVacancy.PackageTypeId         = model.PackageTypeId;
                    NewVacancy.ServicePackCategoryId = model.ServicePackCategoryId;
                    NewVacancy.ServicePackId         = model.ServicePackId;
                    //NewVacancy.Status = VacanStatusFive.Done;
                    NewVacancy.VacancyStatus = ApproverStatus.Completed;
                    NewVacancy.isHrms        = model.isHrms;
                    NewVacancy.isLaptop      = model.isLaptop == 1 ? true : false;
                    NewVacancy.isManager     = model.isManager;
                    NewVacancy.isUsim        = model.isUsim;
                    NewVacancy.StatusOne     = SrfApproveStatus.Approved;
                    NewVacancy.StatusTwo     = SrfApproveStatus.Approved;
                    NewVacancy.StatusThree   = SrfApproveStatus.Approved;
                    NewVacancy.StatusFourth  = SrfApproveStatus.Approved;
                    _vacancy.Add(NewVacancy);

                    if (NewVacancy.Id != null)
                    {
                        // Insert Candidate
                        var UserProfile  = _profileService.GetByUserId(id);
                        var GetCandidate = _candidate.GetAll().Where(x => x.AccountId == UserProfile.Id).FirstOrDefault();

                        if (GetCandidate == null)
                        {
                            var Candidate = new CandidateInfo();
                            Candidate.Account           = UserProfile;
                            Candidate.Address           = UserProfile.Address;
                            Candidate.AgencyId          = model.AgencyId;
                            Candidate.AgencyType        = AgencyType.Agency;
                            Candidate.ApproveOneDate    = DateTime.Now;
                            Candidate.ApproveOneStatus  = ApproverStatus.Selected;
                            Candidate.ApproveTwoeDate   = DateTime.Now;
                            Candidate.CreatedAt         = DateTime.Now;
                            Candidate.Email             = User.Email;
                            Candidate.Gender            = UserProfile.Gender.Value;
                            Candidate.HomePhoneNumber   = UserProfile.HomePhoneNumber;
                            Candidate.IdNumber          = UserProfile.IdNumber;
                            Candidate.IsCandidate       = false;
                            Candidate.IsContractor      = true;
                            Candidate.IsUser            = true;
                            Candidate.Martial           = Martial.M1;
                            Candidate.MobilePhoneNumber = UserProfile.MobilePhoneNumber;
                            Candidate.Name             = UserProfile.Name;
                            Candidate.Nationality      = "Indonesia";
                            Candidate.NickName         = UserProfile.Name;
                            Candidate.PlaceOfBirth     = UserProfile.Birthplace;
                            Candidate.DateOfBirth      = UserProfile.Birthdate.Value;
                            Candidate.RequestBy        = _userHelper.GetUserProfile(model.AgencyId);
                            Candidate.ApproveTwoStatus = ApproverStatus.Completed;
                            Candidate.Vacancy          = NewVacancy;
                            GetCandidate = _candidate.Add(Candidate);
                        }

                        if (GetCandidate != null)
                        {
                            var Department = _department.GetById(model.DepartmentId);
                            var Network    = _network.GetById(model.NetworkId);
                            // Insert SRF
                            SrfRequest NewSrf = new SrfRequest();
                            NewSrf.CreatedAt          = DateTime.Now;
                            NewSrf.Number             = "0000";
                            NewSrf.Type               = SrfType.New;
                            NewSrf.ApproveStatusOne   = SrfApproveStatus.Approved;
                            NewSrf.ApproveStatusTwo   = SrfApproveStatus.Approved;
                            NewSrf.ApproveStatusThree = SrfApproveStatus.Approved;
                            NewSrf.ApproveStatusFour  = SrfApproveStatus.Approved;
                            NewSrf.ApproveStatusFive  = SrfApproveStatus.Approved;
                            NewSrf.ApproveStatusSix   = SrfApproveStatus.Approved;
                            NewSrf.RequestBy          = _userHelper.GetUserProfile(model.ApproverOneId).Name;
                            NewSrf.SrfBegin           = model.SrfBegin;
                            NewSrf.SrfEnd             = model.SrfEnd;
                            NewSrf.ServiceLevel       = model.OtLevel;
                            NewSrf.isWorkstation      = model.isLaptop == 1 ? true  : false;
                            NewSrf.isCommunication    = model.isUsim;
                            NewSrf.IsHrms             = model.isHrms;
                            NewSrf.IsOps              = Department.OperateOrNon == 1 ? true : false;
                            NewSrf.IsManager          = false;
                            NewSrf.RateType           = Domain.Models.Enum.RateType.Normal;
                            NewSrf.IsExtended         = false;
                            NewSrf.IsLocked           = false;
                            NewSrf.Status             = Domain.Models.Enum.SrfStatus.Done;
                            NewSrf.SpectValue         = 0;
                            NewSrf.IsActive           = false;
                            NewSrf.ServicePackId      = model.ServicePackId;
                            NewSrf.NetworkId          = model.NetworkId;
                            NewSrf.CostCenterId       = model.CostCodeId;
                            NewSrf.LineManagerId      = model.ApproverOneId;
                            NewSrf.ActivityCode       = _activity.GetAll().OrderBy(x => Guid.NewGuid()).FirstOrDefault();
                            NewSrf.DepartmentId       = model.DepartmentId;
                            NewSrf.DepartmentSubId    = model.DepartmentSubId;
                            NewSrf.ProjectManagerId   = Network.ProjectManagerId;
                            NewSrf.ApproveOneId       = model.ApproverOneId;
                            NewSrf.ApproveTwoId       = model.ApproveTwoId;
                            NewSrf.ApproveThreeId     = model.ApproveThreeId;
                            NewSrf.ApproveFourId      = model.ApproveFourId;
                            NewSrf.ApproveSixId       = model.ApproveSixId;
                            NewSrf.Candidate          = GetCandidate;
                            NewSrf.AccountId          = model.AccountNameId;
                            NewSrf.IsLocked           = false;
                            NewSrf.IsActive           = true;
                            var AnnualLeave = MonthDistance(model.SrfBegin, model.SrfEnd);
                            NewSrf.AnnualLeave = AnnualLeave;
                            Service.Add(NewSrf);
                            if (NewSrf.Id != null)
                            {
                                TempData["Success"] = true;
                            }
                        }
                    }
                }
            }
            return(RedirectToAction("Index"));
        }
예제 #31
0
        public async Task <IActionResult> Import(IFormFile file)
        {
            int TOTAL_INSERT = 0;
            int TOTAL_UPDATE = 0;
            var uploads      = System.IO.Path.Combine(_environment.WebRootPath, "temp");

            file = Request.Form.Files[0];
            using (var fileStream = new FileStream(System.IO.Path.Combine(uploads, file.FileName),
                                                   FileMode.OpenOrCreate,
                                                   FileAccess.ReadWrite,
                                                   FileShare.ReadWrite))
            {
                await file.CopyToAsync(fileStream);

                try
                {
                    using (var Stream = new FileStream(System.IO.Path.Combine(uploads, file.FileName),
                                                       FileMode.OpenOrCreate,
                                                       FileAccess.ReadWrite,
                                                       FileShare.ReadWrite))
                    {
                        using (ExcelPackage package = new ExcelPackage(Stream))
                        {
                            ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                            int            rowCount  = worksheet.Dimension.Rows;
                            int            ColCount  = worksheet.Dimension.Columns;
                            for (int row = 2; row <= rowCount; row++)
                            {
                                if (worksheet.Cells[row, 1].Value != null &&
                                    worksheet.Cells[row, 2].Value != null &&
                                    worksheet.Cells[row, 3].Value != null &&
                                    worksheet.Cells[row, 4].Value != null &&
                                    worksheet.Cells[row, 5].Value != null &&
                                    worksheet.Cells[row, 6].Value != null)
                                {
                                    var NetworkNumber  = worksheet.Cells[row, 1].Value.ToString();
                                    var Project        = worksheet.Cells[row, 2].Value.ToString();
                                    var Department     = worksheet.Cells[row, 3].Value.ToString();
                                    var LineManager    = worksheet.Cells[row, 4].Value.ToString();
                                    var ProjectManager = worksheet.Cells[row, 5].Value.ToString();
                                    var AccountName    = worksheet.Cells[row, 6].Value.ToString();
                                    var Description    = (worksheet.Cells[row, 7].Value != null) ? worksheet.Cells[row, 7].Value.ToString() : "";

                                    NetworkNumber NetWorkFind = Service
                                                                .GetAll()
                                                                .FirstOrDefault(x => _excel.TruncateString(x.Code) == _excel.TruncateString(NetworkNumber));

                                    Projects ProjectFind = projects
                                                           .GetAll()
                                                           .FirstOrDefault(x => _excel.TruncateString(x.Name) == _excel.TruncateString(Project));

                                    Departement DepartmentFind = departement
                                                                 .GetAll()
                                                                 .FirstOrDefault(x => _excel.TruncateString(x.Name) == _excel.TruncateString(Department));

                                    UserProfile LineManagerUser = await FindUserByRole(LineManager, "Project Manager");

                                    UserProfile ProjectManagerUser = await FindUserByRole(ProjectManager, "Project Manager");

                                    AccountName AccountFind = accountName
                                                              .GetAll()
                                                              .FirstOrDefault(x => _excel.TruncateString(x.Name) == _excel.TruncateString(AccountName.ToString()));


                                    if (ProjectFind == null)
                                    {
                                        Projects pj = new Projects {
                                            Name = Project
                                        };
                                        ProjectFind = projects.Add(pj);
                                    }

                                    if (LineManagerUser != null && ProjectManagerUser != null && DepartmentFind != null && AccountName != null)
                                    {
                                        if (NetWorkFind == null)
                                        {
                                            NetworkNumber nt = new NetworkNumber
                                            {
                                                Code           = NetworkNumber,
                                                Project        = ProjectFind,
                                                Departement    = DepartmentFind,
                                                LineManager    = LineManagerUser,
                                                ProjectManager = ProjectManagerUser,
                                                AccountName    = AccountFind,
                                                Description    = Description
                                            };
                                            Service.Add(nt);
                                            TOTAL_INSERT++;
                                        }
                                        else
                                        {
                                            NetworkNumber nt = Service.GetById(NetWorkFind.Id);
                                            nt.Project        = ProjectFind;
                                            nt.Departement    = DepartmentFind;
                                            nt.LineManager    = LineManagerUser;
                                            nt.ProjectManager = ProjectManagerUser;
                                            nt.AccountName    = AccountFind;
                                            nt.Description    = Description;
                                            Service.Update(nt);
                                            TOTAL_UPDATE++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            TempData["Messages"] = "Total Inserted = " + TOTAL_INSERT + " , Total Updated = " + TOTAL_UPDATE;
            System.IO.File.Delete(System.IO.Path.Combine(uploads, file.FileName));
            return(RedirectToAction("Index"));
        }