public ActionResult SaveRecords()
 {
     try
     {
         UserLoginInformation loggedinUser = LoginController.ActiveUser;
         try
         {
             using (TransactionScope transactionScope = new TransactionScope())
             {
                 try
                 {
                     using (kryptoEntities1 db = new kryptoEntities1())
                     {
                         foreach (var @eachObj in FinalObjects)
                         {
                             @eachObj.FacilityId    = Facility;
                             @eachObj.Organisations = @eachObj.Facility.OrganisationId.ToString();
                             @eachObj.CreatedById   = loggedinUser.USERID.ToString();
                             @eachObj.ModifiedById  = loggedinUser.USERID.ToString();
                             @eachObj.CreatedDate   = DateTime.Now;
                             @eachObj.ModifiedDate  = DateTime.Now;
                             @eachObj.UserIsActive  = @eachObj.IsActive;
                             @eachObj.Status        = 1;
                             @eachObj.IsNormalUser  = true;
                             db.UserLoginInformations.Add(@eachObj);
                             db.SaveChanges();
                             if (@eachObj.IsActive)
                             {
                                 UserActivate useracive = new UserActivate();
                                 useracive.CreatedById = loggedinUser.USERID.ToString();
                                 useracive.Date        = DateTime.Now;
                                 useracive.USERID      = @eachObj.USERID;
                                 useracive.IsActive    = @eachObj.IsActive;
                                 db.UserActivates.Add(useracive);
                                 db.SaveChanges();
                             }
                         }
                     }
                     transactionScope.Complete();
                 }
                 catch (Exception wException)
                 {
                     return(Json("Record saving failed...", JsonRequestBehavior.AllowGet));
                 }
             }
         }
         catch (Exception wException)
         {
             return(Json("Record saving failed...", JsonRequestBehavior.AllowGet));
         }
         return(Json("Records Saved Sucessfully", JsonRequestBehavior.AllowGet));
     }
     catch (Exception)
     {
         return(Json("Record saving failed...", JsonRequestBehavior.AllowGet));
     }
 }
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPwdDTO pwd)
        {
            if (ModelState.IsValid)
            {
                var user = await _UserManager.FindByEmailAsync(pwd.Email);

                if (user == null || !(await _UserManager.IsEmailConfirmedAsync(user)))
                {
                }
                else
                {
                    string token = await _UserManager.GeneratePasswordResetTokenAsync(user);

                    string       keyval = Guid.NewGuid().ToString("N");
                    UserActivate usract = new UserActivate {
                        GuiId = keyval, Token = token, UserId = user.Id
                    };
                    _context.UserActivate.Add(usract);
                    await _context.SaveChangesAsync();
                    await SendRestMail(user, keyval);
                }
            }
            return(Ok(new { StatusCode = StatusCodes.Status200OK, Message = "We will email you the password reset link if the email entered is correct" }));
        }
        public string UpdateUser(UserLoginInformation ulinfo)
        {
            try
            {
                var loggedinUser = LoginController.ActiveUser;
                ulinfo.ModifiedById = loggedinUser.USERID.ToString();
                if (ulinfo.USERID == 0)
                {
                    ulinfo.CreatedById = loggedinUser.USERID.ToString();
                    ulinfo.CreatedDate = DateTime.Now;
                    ulinfo.Status      = 1; //insert record status
                    if (ulinfo.IsActive)
                    {
                        ulinfo.UserIsActive = true;
                    }
                    try
                    {
                        using (var transactionScope = new TransactionScope())
                        {
                            try
                            {
                                using (var db = new kryptoEntities1()) // Context object
                                {
                                    db.UserLoginInformations.Add(ulinfo);
                                    db.SaveChanges();

                                    if (ulinfo.USERID > 0)
                                    {
                                        if (ulinfo.IsActive)
                                        {
                                            ulinfo.ActivatedDate   = DateTime.Now;
                                            db.Entry(ulinfo).State = EntityState.Modified;
                                            db.SaveChanges();
                                            var useracive = new UserActivate
                                            {
                                                CreatedById = loggedinUser.USERID.ToString(),
                                                Date        = DateTime.Now,
                                                USERID      = ulinfo.USERID,
                                                IsActive    = ulinfo.IsActive,
                                                Status      = 1
                                            };
                                            db.UserActivates.Add(useracive);
                                            db.SaveChanges();
                                        }
                                    }

                                    var otherFacilityIds = ulinfo.OtherFacilityIds;
                                    if (ulinfo.USERID > 0 &&
                                        (otherFacilityIds != null && otherFacilityIds.Length > 0))
                                    {
                                        foreach (var eachid in otherFacilityIds)
                                        {
                                            var facilityid = int.Parse(eachid);
                                            db.UserFacilities.Add(new UserFacility
                                            {
                                                FacilityId   = facilityid,
                                                USERID       = ulinfo.USERID,
                                                Status       = 1,
                                                CreatedById  = loggedinUser.USERID.ToString(),
                                                CreatedDate  = DateTime.Now,
                                                ModifiedDate = DateTime.Now,
                                                ModifiedById = loggedinUser.USERID.ToString()
                                            });
                                        }
                                        db.SaveChanges();
                                    }
                                    if (ulinfo.USERID > 0)
                                    {
                                        var initiallogin =
                                            new UserRegitrationForInitialLogin
                                        {
                                            USERID            = ulinfo.USERID,
                                            Createdate        = DateTime.Now,
                                            IsInitialLogin    = true,
                                            IsTermsAccepted   = false,
                                            IsSecQuestEnabled = false,
                                            IsMpinCreated     = false,
                                            IsPasswordUpdated = false,
                                            Status            = 1,
                                            CreatedById       = loggedinUser.USERID.ToString(),
                                            ModifiedById      = loggedinUser.USERID.ToString()
                                        };
                                        initiallogin.ModifiedDate = initiallogin.Createdate;
                                        db.UserRegitrationForInitialLogins.Add(initiallogin);
                                        db.SaveChanges();
                                    }
                                }
                                transactionScope.Complete(); // transaction complete
                            }
                            catch (Exception ee)
                            {
                                return("FAIL");
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        return("FAIL");
                    }
                }
                else
                {
                    try
                    {
                        using (var transactionScope = new TransactionScope())
                        {
                            try
                            {
                                using (var db = new kryptoEntities1())
                                {
                                    ulinfo.ModifiedDate = DateTime.Now;
                                    var prevobj = _context.UserLoginInformations.Find(ulinfo.USERID);
                                    if (prevobj.IsActive != ulinfo.IsActive)
                                    {
                                        var activate = new UserActivate
                                        {
                                            IsActive    = !prevobj.IsActive,
                                            CreatedById = loggedinUser.USERID.ToString()
                                        };
                                        if (ulinfo.IsActive)
                                        {
                                            ulinfo.ActivatedDate = DateTime.Now;
                                            activate.Date        = ulinfo.ActivatedDate;
                                        }
                                        else
                                        {
                                            ulinfo.DeactivatedDate = DateTime.Now;
                                            activate.Date          = ulinfo.DeactivatedDate;
                                        }
                                        activate.USERID = prevobj.USERID;
                                        db.UserActivates.Add(activate);
                                    }
                                    ulinfo.UserIsActive = ulinfo.IsActive;
                                    ulinfo = Updateobject(ulinfo.USERID, ulinfo);
                                    db.Entry(ulinfo).State = EntityState.Modified;
                                    db.SaveChanges();

                                    var otherFacilityIdsAsints        = ulinfo.GetOtherFacilityIdsAsints();
                                    var facilityIdsInUserFacilityList = ulinfo.GetFacilityIdsInUserFacilityList();
                                    var toAdd    = ExcludedRight(facilityIdsInUserFacilityList, otherFacilityIdsAsints);
                                    var toDelete = ExcludedLeft(facilityIdsInUserFacilityList, otherFacilityIdsAsints);
                                    foreach (var @id in toAdd)
                                    {
                                        db.UserFacilities.Add(new UserFacility
                                        {
                                            FacilityId   = @id,
                                            USERID       = ulinfo.USERID,
                                            Status       = 1,
                                            CreatedById  = loggedinUser.USERID.ToString(),
                                            CreatedDate  = DateTime.Now,
                                            ModifiedDate = DateTime.Now,
                                            ModifiedById = loggedinUser.USERID.ToString()
                                        });
                                    }
                                    foreach (
                                        var existingUserFacility in
                                        toDelete.Select(
                                            id =>
                                            db.UserFacilities.SingleOrDefault(
                                                x =>
                                                x.FacilityId.Value.Equals(id) &&
                                                x.USERID.Equals(ulinfo.USERID))))
                                    {
                                        db.UserFacilities.Remove(existingUserFacility);
                                    }
                                    db.SaveChanges();
                                    if (ulinfo.IsActive == false)
                                    {
                                        RemoveUser(ulinfo.USERID);
                                    }
                                }
                                transactionScope.Complete();
                            }
                            catch (Exception ee)
                            {
                                return("FAIL");
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        return("FAIL");
                    }
                }
                if (ulinfo.USERID > 0 && ulinfo.IsActive)
                {
                    OtpSent(ulinfo, loggedinUser.USERID);
                }
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                      eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                          ve.PropertyName, ve.ErrorMessage);
                    }
                }
                return("FAIL");
            }
            return("SUCESS");
        }
        public ActionResult UpdateUserStatus(int currentRecord, bool currentStatus)
        {
            var info         = _context.UserLoginInformations.Single(x => x.USERID == currentRecord && x.Status == 1);
            var loggedinUser = LoginController.ActiveUser;

            if (info.IsActive != currentStatus)
            {
                info.IsActive     = currentStatus;
                info.UserIsActive = currentStatus;
                try
                {
                    using (var transactionScope = new TransactionScope())
                    {
                        try
                        {
                            using (kryptoEntities1 db = new kryptoEntities1()) // Context object
                            {
                                if (info.IsActive)
                                {
                                    info.ActivatedDate = DateTime.Now;
                                }
                                else
                                {
                                    info.DeactivatedDate = DateTime.Now;
                                }
                                db.Entry(info).State = EntityState.Modified;
                                db.SaveChanges();
                                var useracive = new UserActivate
                                {
                                    CreatedById = loggedinUser.USERID.ToString(),
                                    Date        = DateTime.Now,
                                    USERID      = info.USERID,
                                    IsActive    = info.IsActive
                                };
                                db.UserActivates.Add(useracive);
                                db.SaveChanges();
                            }
                            transactionScope.Complete();
                        }
                        catch (Exception Wx)
                        {
                            return(Json("Something went Wrong!", JsonRequestBehavior.AllowGet));
                        }
                    }
                    if (info.USERID > 0 && info.IsActive)
                    {
                        OtpSent(info, loggedinUser.USERID);
                    }
                    else if (info.IsActive == false)
                    {
                        RemoveUser(info.USERID);
                    }
                }
                catch (Exception Ex)
                {
                    return(Json("Something went Wrong!", JsonRequestBehavior.AllowGet));
                }
                return(Json("Sucessfully Updated the Status", JsonRequestBehavior.AllowGet));
            }
            return(Json("No Changes to Update", JsonRequestBehavior.AllowGet));
        }
        public async Task <IActionResult> Register([FromBody] RegisterDTO usr)
        {
            if (!_context.User.Any(u => u.Email == usr.Email))
            {
                var uguid = Guid.NewGuid();
                var user  = new User
                {
                    UserName     = usr.Email.ToLower(),
                    Email        = usr.Email,
                    FullName     = usr.Name,
                    PasswordHash = usr.Password,
                    UserGuid     = uguid,
                };

                if (usr.Type == 2)
                {
                    var    comp     = new Company();
                    string emaildom = _helperService.GetDomain(usr.Email);
                    if (!_context.User.Any(x => x.Email.Contains(emaildom)))
                    {
                        var addr = new Address();
                        addr.Phone   = usr.Phone;
                        comp.Name    = usr.Company;
                        comp.UID     = Guid.NewGuid();
                        comp.Address = addr;
                        user.Company = comp;
                        comp.Created = DateTime.Now;
                        comp.Updated = DateTime.Now;
                    }
                    else
                    {
                        return(BadRequest(new ErrorDto {
                            StatusCode = StatusCodes.Status400BadRequest, Message = "Company already exists, contact administrator"
                        }));
                    }
                }

                var createUser = await _UserManager.CreateAsync(user, usr.Password);

                if (createUser.Succeeded)
                {
                    if (usr.Type == 2)
                    {
                        await _UserManager.AddToRoleAsync(user, "ADMIN");
                    }
                    else
                    {
                        await _UserManager.AddToRoleAsync(user, "CANDIDATE");
                    }
                    //Gen Avatar
                    _helperService.GenAvatar(uguid.ToString(), user.FullName);

                    if (!string.IsNullOrEmpty(usr.Token) && usr.Type == 4)
                    {
                        if (usr.Token.Contains("-"))
                        {
                            //Find JD and select candidate by user email and company id
                            var jdinfo = await _context.JobOrder.Where(x => (x.InviteId == usr.Token)).FirstOrDefaultAsync();

                            //If new add candidate and select id
                            if (jdinfo != null)
                            {
                                var cand = await _context.Candidate.Where(c => (c.Email == usr.Email && c.CompanyId == jdinfo.CompanyId)).FirstOrDefaultAsync();

                                _context.Entry <JobOrder>(jdinfo).State = EntityState.Detached;

                                Candidate cnew = new Candidate();
                                if (cand == null)
                                {
                                    cnew.Name      = user.FullName;
                                    cnew.UserId    = user.Id;
                                    cnew.Email     = user.Email;
                                    cnew.CompanyId = jdinfo.CompanyId;
                                    cnew.Created   = DateTime.Now;
                                    await _context.Candidate.AddAsync(cnew);
                                }
                                else
                                {
                                    _context.Entry <Candidate>(cand).State = EntityState.Detached;
                                    cnew.Id = cand.Id;
                                    _context.Candidate.Attach(cnew);
                                    cnew.Name   = user.FullName;
                                    cnew.UserId = user.Id;
                                }
                                await _context.SaveChangesAsync();

                                var jdcand = await _context.JobCandidate.Where(x => (x.jobOrderId == jdinfo.Id && x.CandidateId == cnew.Id)).FirstOrDefaultAsync();

                                JobCandidate jc = new JobCandidate();
                                if (jdcand == null)
                                {
                                    jc.CandidateId = cnew.Id;
                                    jc.jobOrderId  = jdinfo.Id;
                                    jc.AddedOn     = DateTime.Now;
                                    jc.AddedById   = cnew.Id;
                                    await _context.JobCandidate.AddAsync(jc);
                                }
                                else
                                {
                                    _context.Entry <JobCandidate>(jdcand).State = EntityState.Detached;
                                    _context.JobCandidate.Attach(jc);
                                    jc.CandidateId = cnew.Id;
                                    jc.jobOrderId  = jdinfo.Id;
                                    jc.AddedOn     = DateTime.Now;
                                    jc.AddedById   = cnew.Id;
                                }
                                await _context.SaveChangesAsync();
                            }
                        }
                        else
                        {
                            InviteCandidate candid = await _context.InviteCandidate.Where(i => i.Token == usr.Token).SingleOrDefaultAsync();

                            if (candid == null)
                            {
                            }
                            else
                            {
                                Candidate cnew = new Candidate();
                                cnew.Id = candid.CandidateId;
                                _context.Candidate.Attach(cnew);
                                cnew.UserId = user.Id;
                                _context.InviteCandidate.Remove(candid);
                            }
                        }
                        string token = await _UserManager.GenerateEmailConfirmationTokenAsync(user);

                        var result = await _UserManager.ConfirmEmailAsync(user, token);

                        if (result.Succeeded)
                        {
                            await _context.SaveChangesAsync();
                        }
                    }
                    else
                    {
                        string token = await _UserManager.GenerateEmailConfirmationTokenAsync(user);

                        string       keyval = Guid.NewGuid().ToString("N");
                        UserActivate usract = new UserActivate {
                            GuiId = keyval, Token = token, UserId = user.Id
                        };
                        _context.UserActivate.Add(usract);
                        await _context.SaveChangesAsync();
                        await SendActivation(user, keyval);
                    }
                    return(Ok(new { StatusCode = StatusCodes.Status200OK, Message = "Account created successfully, Please check mail and activate account" }));
                }
                else
                {
                    return(BadRequest(new ErrorDto {
                        StatusCode = StatusCodes.Status400BadRequest, Message = "Password policy not met"
                    }));
                }
            }
            else
            {
                return(BadRequest(new ErrorDto {
                    StatusCode = StatusCodes.Status400BadRequest, Message = "Email id already exists"
                }));
            }
        }