Ejemplo n.º 1
0
        public HttpResponseMessage RegisterEmployer([FromBody] EmployerEntity value)
        {
            // System.Diagnostics.Debugger.Break();
            var dump = ObjectDumper.Dump(value);


            //
            Console.WriteLine(dump);
            var result = new Result();

            if (string.IsNullOrEmpty(value.Email) || string.IsNullOrEmpty(value.Password) || string.IsNullOrEmpty(value.EmployerName))
            {
                result = new Result(false);
                return(Request.CreateResponse(HttpStatusCode.BadRequest, result));
            }

            result = _employersManager.Register(value);

            if (!result.Success)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, result));
            }

            var employer       = new EmployerModel();
            var employerEntity = (EmployerEntity)result.Entity;

            employer.Email        = employerEntity.Email;
            employer.Token        = employerEntity.Token;
            employer.EmployerName = employerEntity.EmployerName;
            //employer.ApnaUser = false;
            employer.EmployerId = employerEntity.EmployerId;
            result.Entity       = employer;
            return(Request.CreateResponse(HttpStatusCode.OK, result));
        }
Ejemplo n.º 2
0
        public FetchSpecs(SqLiteNHibernateFixture fixture) : base(fixture) {
            using (var tx = Session.BeginTransaction()) {
                var person = new PersonEntity();

                CarEntity car;
                car = new CarEntity{Owner = person};
                person.Cars.Add(car);
                car = new CarEntity{Owner = person};
                person.Cars.Add(car);

                PetEntity pet;
                pet = new PetEntity {Owner = person};
                person.Pets.Add(pet);
                pet = new PetEntity {Owner = person};
                person.Pets.Add(pet);

                var employer = new EmployerEntity();
                Session.Save(employer);

                employer.Employees.Add(person);
                person.Employer = employer;
             
                Session.Save(person);
                tx.Commit();
            }

            Session.Clear();
            SessionFactory.Statistics.Clear();
        }
Ejemplo n.º 3
0
        public HttpResponseMessage EditDetails([FromBody] EmployerEntity value)
        {
            var result = new Result();

            if (string.IsNullOrEmpty(value.Email) || string.IsNullOrEmpty(value.EmployerName))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new Result(false)));
            }
            if (!value.Email.Contains("@") || value.Email.Length < 3)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new Result(false)));
            }
            object objemp = null;

            Request.Properties.TryGetValue("employer", out objemp);
            var employer = objemp as EmployerEntity;

            value.EmployerId = employer.EmployerId;

            value.ModifyDate = DateTime.Now;
            result           = _employersManager.UpdateDetails(value);

            var emp    = (EmployerEntity)_employersManager.GetEmployerById(employer.EmployerId).Entity;
            var em_mod = new EmployerModel();

            PropertyCopier <EmployerEntity, EmployerModel> .Copy(emp, em_mod);

            result.Entity = em_mod;
            return(Request.CreateResponse(HttpStatusCode.OK, result));
        }
Ejemplo n.º 4
0
        public Result Delete(EmployerEntity entity)
        {
            var credentials = new CredentialsManager();
            var result      = credentials.ValidateUserToken(entity.Token);

            if (!result.Success)
            {
                return(result);
            }
            var employer = (EmployerEntity)result.Entity;

            if (employer.EmployerId != entity.EmployerId)
            {
                result.Message = "Forbidden operation";
                result.Success = false;
                return(result);
            }

            var con   = new DapperConnectionManager();
            var query = new QueryEntity();

            entity.Email = entity.Email.Trim().ToLower();
            query.Query  = @"Update Employers Set Active = 0
                            where EmployerID = @EmployerID";
            query.Entity = new { EmployerID = entity.EmployerId };

            result         = con.ExecuteQuery <EmployerEntity>(query);
            result.Message = result.Success ? "The user has been deleted" : "An error has occurred";
            return(result);
        }
Ejemplo n.º 5
0
        public Result UpdateMembership(EmployerEntity entity)
        {
            var result = new Result();

            try
            {
                var con   = new DapperConnectionManager();
                var query = new QueryEntity();


                entity.ModifyDate = DateTime.Now;

                query.Query    = @"
                        BEGIN TRAN
                        Update Employers Set 
                                                    [MembershipType] = ISNULL( @MembershipType , MembershipType ) ,
                                                    [MembershipStartDate] = ISNULL( @MembershipStartDate , MembershipStartDate ) ,
                                                    [MembershipEndDate] = ISNULL( @MembershipEndDate , MembershipEndDate ) 
                            where EmployerId = @EmployerId;
                            SELECT * FROM EMPLOYERS WHERE EmployerId = @EmployerId;
                            COMMIT TRAN
    ";
                query.Entity   = entity;
                result         = con.ExecuteQuery <EmployerEntity>(query);
                result.Message = result.Success ? "The user details has been updated" : "An error has occurred";
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                result         = result ?? new Result(false);
                result.Message = "An error occurred";
                throw;
            }
            return(result);
        }
Ejemplo n.º 6
0
        public string GenerateRecoverPasswordToken(EmployerEntity employer)
        {
            var utc0      = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var issueTime = DateTime.Now;

            var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
            var exp = (int)issueTime.AddDays(1).Subtract(utc0).TotalSeconds;

            IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
            IJsonSerializer   serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);

            var payload = new Dictionary <string, object>
            {
                { "EmployerId", employer.EmployerId },
                { "exp", exp },
                { "iat", iat },
                { "roles", "employer, generic" }
            };

            var token = encoder.Encode(payload, SecretRecoverKey);

            return(token);
        }
        public FetchManySpecs(SqLiteNHibernateFixture fixture) : base(fixture)
        {
            using (var tx = Session.BeginTransaction()) {
                EmployerEntity       employer;
                PersonEntity         person;
                RepresentativeEntity representative;
                CarEntity            car;

                employer = new EmployerEntity();
                Session.Save(employer);

                representative = new RepresentativeEntity();
                Session.Save(representative);
                person = new PersonEntity {
                    Employer = employer, Representative = representative
                };
                representative.Constituents.Add(person);
                employer.Employees.Add(person);

                car = new CarEntity {
                    Owner = person
                };
                person.Cars.Add(car);
                car = new CarEntity {
                    Owner = person
                };
                person.Cars.Add(car);

                Session.Save(person);


                representative = new RepresentativeEntity();
                Session.Save(representative);
                person = new PersonEntity {
                    Employer = employer, Representative = representative
                };
                representative.Constituents.Add(person);
                employer.Employees.Add(person);

                car = new CarEntity {
                    Owner = person
                };
                person.Cars.Add(car);
                car = new CarEntity {
                    Owner = person
                };
                person.Cars.Add(car);

                Session.Save(person);

                tx.Commit();
            }

            Session.Clear();
            SessionFactory.Statistics.Clear();
        }
Ejemplo n.º 8
0
        public Result Login(EmployerEntity entity)
        {
            var result = new Result();

            try
            {
                var con         = new DapperConnectionManager();
                var query       = new QueryEntity();
                var credentials = new CredentialsManager();
                entity.Email = entity.Email.Trim().ToLower();
                query.Query  = @"SELECT * FROM Employers
                            where Email = @Email and Active = 1 and ApnaUser = 0";
                query.Entity = entity;
                result       = con.ExecuteQuery <EmployerEntity>(query);

                if (!result.Success)
                {
                    result.Message = "Login error";
                    return(result);
                }

                var r = (IEnumerable <EmployerEntity>)result.Entity;

                var employer = r.FirstOrDefault();

                if (employer == null)
                {
                    result.Message = "Invalid password or username";
                    result.Success = false;
                    result.Entity  = null;
                    return(result);
                }
                var password = credentials.EncodePassword(entity.Password, employer.Hash);
                if (password == employer.Password)
                {
                    employer.Hash     = null;
                    employer.Password = null;
                    employer.Token    = credentials.GenerateEmployerToken(employer);
                    result.Entity     = employer;
                    return(result);
                }
                result.Entity  = null;
                result.Message = "Employer not found";
                result.Success = false;
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                result.Entity  = null;
                result         = result ?? new Result(false);
                result.Message = "An error occurred";
            }

            return(result);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Cria um novo funcionario.
        /// </summary>
        /// <param name="companyId">identificador unico da empresa.</param>
        /// <param name="employer">dados de um funcionario.</param>
        /// <returns></returns>
        public async Task AddEmployer(EmployerEntity employer)
        {
            var employers = await _stateManager.GetOrAddAsync <IReliableDictionary <Guid, EmployerEntity> >("companies");

            using (var transac = _stateManager.CreateTransaction())
            {
                await employers.AddOrUpdateAsync(transac, employer.EmployerId, employer, (id, value) => employer);

                await transac.CommitAsync();
            }
        }
Ejemplo n.º 10
0
        public async Task <HttpResponseMessage> Post([FromBody] LoginObject value)
        {
            var result     = new Result();
            var tokenLogin = false;
            var apnaLogin  = false;


            var employer = new EmployerEntity();

            PropertyCopier <LoginObject, EmployerEntity> .Copy(value, employer);

            var token = Request.Headers.Authorization;

            if (token != null)
            {
                tokenLogin = true;
                result     = _employersManager.Login(token.Parameter);
            }

            if ((string.IsNullOrEmpty(employer.Email) || string.IsNullOrEmpty(employer.Password)) && !tokenLogin)
            {
                result = new Result(false);
                return(Request.CreateResponse(HttpStatusCode.BadRequest, result));
            }

            if (!tokenLogin && !apnaLogin)
            {
                result    = _employersManager.Login(employer);
                apnaLogin = !result.Success;
            }


            var employer_model = new EmployerModel();
            var employerEntity = (EmployerEntity)result.Entity;

            if (!result.Success)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, result));
            }
            employer_model.Token = employerEntity.Token;
            PropertyCopier <EmployerEntity, EmployerModel> .Copy(employerEntity, employer_model);

            if (token != null)
            {
                employer_model.Token = token.Parameter;
            }


            result.Entity = employer_model;
            return(Request.CreateResponse(HttpStatusCode.OK, result));
        }
Ejemplo n.º 11
0
        public Result GenerateRecoveringCode(EmployerEntity entity)
        {
            var result      = new Result();
            var con         = new DapperConnectionManager();
            var query       = new QueryEntity();
            var credentials = new CredentialsManager();

            entity.Email = entity.Email.Trim().ToLower();
            query.Query  = @"SELECT * FROM Employers
                            where Email = @Email and Active = 1 and ApnaUser = 0";
            query.Entity = entity;
            result       = con.ExecuteQuery <EmployerEntity>(query);

            if (!result.Success)
            {
                result.Entity  = null;
                result.Message = "An error occurred";
                return(result);
            }

            var r = (IEnumerable <EmployerEntity>)result.Entity;

            var employer = r.FirstOrDefault();

            if (employer == null)
            {
                result.Entity  = null;
                result.Message = "Invalid user";
                result.Success = false;
                return(result);
            }
            var Token = credentials.GenerateRecoverPasswordToken(employer);

            Token = HttpUtility.UrlEncode(Token);

            Task.Run(() => new EmailManager().SendEmail(entity.Email, DL.Models.EmailType.RecoverPassword, new
            {
                Token,
                CurrentUserName  = employer.EmployerName,
                CurrentUserEmail = employer.Email,
                WebsiteUrl       = ConfigurationManager.AppSettings["mnf.website"],
                ContentUrl       = ConfigurationManager.AppSettings["mnf.content"]
            }));

            result.Entity  = null;
            result.Message = "An email has been sent with instructions for recovering your password";
            result.Success = true;

            return(result);
        }
Ejemplo n.º 12
0
        public HttpResponseMessage Recover([FromBody] EmployerEntity value)
        {
            if (string.IsNullOrEmpty(value.Email))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new Result(false)));
            }
            if (!value.Email.Contains("@") || value.Email.Length < 3)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new Result(false)));
            }

            var result = _employersManager.GenerateRecoveringCode(value);

            return(Request.CreateResponse(HttpStatusCode.OK, result));
        }
Ejemplo n.º 13
0
        public Result GetAllListingsByEmployerV2(EmployerEntity employer)
        {
            var result = new Result();

            try
            {
                var credentials = new CredentialsManager();

                var con   = new DapperConnectionManager();
                var query = new QueryEntity
                {
                    Entity = employer,
                    Query  = @"SELECT *
                          FROM JobListings
                          WHERE EmployerId= @EmployerId
                    "
                };

                result = con.ExecuteQuery <JobListingEntity>(query);
                var listing_list = (List <JobListingEntity>)result.Entity;

                var formatted_listing_list = new List <dynamic>();
                var listing_cri_man        = new JobListingCriteriaManager();
                foreach (JobListingEntity listing in listing_list)
                {
                    var criteria           = (List <JobListingCriteriaEntity>)listing_cri_man.GetCriteriaByListingId(listing.JobListingId).Entity;
                    var formatted_Criteria = transformCriteria(criteria, Mode.DICTQuestionIdValue);
                    listing.JobListingCriteria_Dict_QuestionID_Value = formatted_Criteria;
                }

                result.Entity = listing_list;
                return(result);
            }
            catch (Exception ex)
            {
                if (result == null)
                {
                    result = new Result();
                }
                Logger.Log(ex);
                result.Entity  = null;
                result.Success = false;
                result.Message = "An error occurred" + ex.Message;
            }
            return(result);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Ponto principal de entrada para o service replica.
        /// Este metodo é executado quando a replica de um servico começa a ser invocado.
        /// </summary>
        /// <param name="cancellationToken">Cancelado quando um service fabric precisa desligar este serviço de replica.</param>
        /// <returns></returns>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            _repositoryEmployer = new ServiceFabricEmployerRepository(this.StateManager);
            _repositoryCompany  = new ServiceFabricCompanyRepository(this.StateManager);

            var company = _repositoryCompany.GetCompany("trends").GetAwaiter().GetResult().GetEnumerator();

            var employer1 = new EmployerEntity
            {
                EmployerId = Guid.NewGuid(),
                CompanyId  = company.Current.CompanyId,
                Birthday   = new DateTime(1988, 03, 30),
                Genre      = "Masculino",
                Name       = "Rodrigo",
                LastName   = "Galhardo"
            };

            var employer2 = new EmployerEntity
            {
                EmployerId = Guid.NewGuid(),
                CompanyId  = company.Current.CompanyId,
                Birthday   = new DateTime(1988, 02, 15),
                Genre      = "Masculino",
                Name       = "Rodolpho",
                LastName   = "Galhardo"
            };

            var employer3 = new EmployerEntity
            {
                EmployerId = Guid.NewGuid(),
                CompanyId  = company.Current.CompanyId,
                Birthday   = new DateTime(1988, 02, 15),
                Genre      = "Masculino",
                Name       = "Bruce Ro",
                LastName   = "Wayne"
            };

            await _repositoryEmployer.AddEmployer(employer1);

            await _repositoryEmployer.AddEmployer(employer1);

            await _repositoryEmployer.AddEmployer(employer1);

            IEnumerable <EmployerEntity> All = await _repositoryEmployer.GetAllEmployerByName("ro");
        }
Ejemplo n.º 15
0
        public HttpResponseMessage ResetPassword([FromBody] EmployerEntity value)
        {
            if (string.IsNullOrEmpty(value.Token))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new Result(false)));
            }
            if (string.IsNullOrEmpty(value.Password))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new Result(false)));
            }
            if (value.Password.Length < 6)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new Result(false)));
            }
            value.Token = HttpUtility.HtmlDecode(value.Token);
            var result = _employersManager.ResetPassword(value);

            return(Request.CreateResponse(HttpStatusCode.OK, result));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Atualiza os dados de um funcionario.
        /// </summary>
        /// <param name="companyId">Id da empresa.</param>
        /// <param name="employer">Entidade de funcionario para atualizar.</param>
        /// <returns></returns>
        public async Task UpdateEmployer(Guid employerId, EmployerEntity employer)
        {
            var employers = await _stateManager.GetOrAddAsync <IReliableDictionary <Guid, EmployerEntity> >("employers");

            var employee = await GetEmployerById(employerId);

            using (var transac = _stateManager.CreateTransaction())
            {
                ConditionalValue <EmployerEntity> employ = await employers.TryGetValueAsync(transac, employerId);

                var ret = employ.HasValue ? employ.Value : null;

                if (ret != null)
                {
                    await employers.TryUpdateAsync(transac, employerId, employer, employee);

                    await transac.CommitAsync();
                }
            }
        }
Ejemplo n.º 17
0
        // To hide the Listing
        public Result DeleteJobListing(JobListingEntity entity, EmployerEntity employer)
        {
            var result = new Result();

            try
            {
                var con         = new DapperConnectionManager();
                var query       = new QueryEntity();
                var credentials = new CredentialsManager();

                // confirm if the employer is the one that deleting
                if (employer.EmployerId != entity.EmployerId)
                {
                    result.Message = "Forbidden operation";
                    result.Success = false;
                    return(result);
                }

                // create a query for hiding the listing
                query.Entity = entity;
                query.Query  = @"UPDATE JobListings set Hidden = 1 WHERE JobListingId = @JobListingId";
                con.ExecuteQuery(query);
                result.Message = result.Success ? "The listing has been deleted" : "An error has occurred";
                return(result);
            }
            catch (Exception ex)
            {
                if (result == null)
                {
                    result = new Result();
                }
                Logger.Log(ex);
                result.Entity  = null;
                result.Success = false;
                result.Message = "An error occurred";
            }
            return(result);
        }
Ejemplo n.º 18
0
        public HttpResponseMessage ChangePassword([FromBody] EmployerEntity value)
        {
            if (string.IsNullOrEmpty(value.NewPassword) || string.IsNullOrEmpty(value.Password))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new Result(false)));
            }

            if (value.NewPassword.Length < 6 || value.Password.Length < 6)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new Result(false)));
            }

            object objuser = null;

            Request.Properties.TryGetValue("user", out objuser);
            var user = objuser as EmployerEntity;

            user.Password    = value.Password;
            user.NewPassword = value.NewPassword;
            var result = _employersManager.ChangePassword(user);

            return(Request.CreateResponse(HttpStatusCode.OK, result));
        }
Ejemplo n.º 19
0
        public Result CreateJobListing(JobListingEntity entity, EmployerEntity employer)
        {
            var result = new Result();

            try
            {
                var con         = new DapperConnectionManager();
                var query       = new QueryEntity();
                var credentials = new CredentialsManager();

                // Check if employer is valid

                result = ValidateEmployer(entity);

                if (result.Success == false)
                {
                    return(result);
                }


                // check if the listing has required fields
                if (entity.Title == null ||
                    entity.NurseType == null ||
                    entity.Suburb == null)
                {
                    entity.PublishStatus = false;
                }

                entity.CreateDate       = DateTime.Now;
                entity.ModificationDate = entity.CreateDate;

                // TODO : check for each element type and length



                query.Entity = entity;
                query.Query  = @"INSERT INTO [dbo].[JobListings]
                                           ([EmployerId]
                                           ,[Title]
                                           ,[NurseType]
                                           ,[SpecialRequirements]
                                           ,[PublishStatus]
                                           ,[MinSalary]
                                           ,[MaxSalary]
                                           ,[CreateDate]
                                           ,[ApplicationDeadline]
                                           ,[ModificationDate]
                                           ,[Area]
                                           ,[State]
                                           ,[Country]
                                           ,[Suburb]
                                           ,[PostalCode]
                                           ,[AddressLine1]
                                           ,[AddressLine2]
                                           ,[Completed]
                                           ,[JobType])
                                     VALUES
                                           (@EmployerId 
                                           ,@Title
                                           ,@NurseType
                                           ,@SpecialRequirements
                                           ,@PublishStatus
                                           ,@MinSalary
                                           ,@MaxSalary
                                           ,@CreateDate
                                           ,@ApplicationDeadline
                                           ,@ModificationDate
                                           ,@Area
                                           ,@State
                                           ,@Country
                                           ,@Suburb
                                           ,@PostalCode
                                           ,@AddressLine1
                                           ,@AddressLine2
                                           ,@Completed
                                           ,@JobType)";


                result = con.ExecuteQuery <JobListingEntity>(query);
                return(result);
            }
            catch (Exception ex)
            {
                if (result == null)
                {
                    result = new Result();
                }
                Logger.Log(ex);
                result.Entity  = null;
                result.Success = false;
                result.Message = "An error occurred";
            }
            return(result);
        }
Ejemplo n.º 20
0
        public Result PublishJobListing(JobListingEntity entity, EmployerEntity employer)
        {
            //Validate required fields
            var result = new Result();

            try
            {
                var con         = new DapperConnectionManager();
                var query       = new QueryEntity();
                var credentials = new CredentialsManager();


                // check if the listing has required fields
                if (entity.JobListingId != 0)
                {
                    entity.PublishStatus = true;
                }


                entity.ModificationDate = DateTime.Now;

                // TODO : check for each element type and length



                query.Entity = entity;

                /*                query.Query = @"UPDATE [dbo].[JobListings] set
                 *                                         [EmployerId] = @EmployerId
                 *                                         ,[Title] = @Title
                 *                                         ,[NurseType] = ,@NurseType
                 *                                         ,[SpecialRequirements] = @SpecialRequirements
                 *                                         ,[PublishStatus] = @PublishStatus
                 *                                         ,[MinSalary] = @MinSalary
                 *                                         ,[MaxSalary] = @MaxSalary
                 *                                         ,[ApplicationDeadline] = @ApplicationDeadline
                 *                                         ,[ModificationDate] = @ModificationDate
                 *                                         ,[Area] = @Area
                 *                                         ,[State] = @State
                 *                                         ,[Country] = @Country
                 *                                         ,[Suburb] = @Suburb
                 *                                         ,[PostalCode] = @PostalCode
                 *                                         ,[AddressLine1] = @AddressLine1
                 *                                         ,[AddressLine2] = @AddressLine2
                 *                                         ,[Completed] = @Completed
                 *                                         ,[JobType] =@JobType
                 *                                   WHERE JobListingId = @JobListingId";*/

                query.Query = @"UPDATE [dbo].[JobListings] set [PublishStatus] = @PublishStatus  WHERE JobListingId = @JobListingId";
                result      = con.InsertQuery(query);


                return(result);
            }
            catch (Exception ex)
            {
                if (result == null)
                {
                    result = new Result();
                }
                Logger.Log(ex);
                result.Entity  = null;
                result.Success = false;
                result.Message = "An error occurred";
            }
            return(result);
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Atualiza os dados de um funcionario.
 /// </summary>
 /// <param name="employerId">identificador unico de um funcionario.</param>
 /// <param name="employer">entidade de um funcionario.</param>
 /// <returns>
 /// Status 200::Atualizado com sucesso.
 /// </returns>
 public async Task UpdateEmployer(Guid employerId, EmployerEntity employer)
 {
     await _repositoryEmployer.UpdateEmployer(employerId, employer);
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Cria um registro de um funcionario para uma empresa.
 /// </summary>
 /// <param name="companyId"></param>
 /// <param name="employer"></param>
 /// <returns>
 /// status 200:: sucesso para um registro criado.
 /// </returns>
 public async Task AddEmployer(EmployerEntity employer)
 {
     await _repositoryEmployer.AddEmployer(employer);
 }
Ejemplo n.º 23
0
        public Result UpdateDetails(EmployerEntity entity)
        {
            var result = new Result();

            try
            {
                if (!entity.Email.Contains("@") || entity.Email.Length < 3)
                {
                    result         = new Result(false);
                    result.Message = "Email invalid";
                    return(result);
                }

                var con   = new DapperConnectionManager();
                var query = new QueryEntity();

                entity.Email = entity.Email.Trim().ToLower();


                query.Query  = @"SELECT count(*) as n FROM Employers
                            where Email = @Email and Active = 1 and EmployerId <> @EmployerId";
                query.Entity = entity;
                result       = con.ExecuteQuery(query);

                if (!result.Success)
                {
                    result.Entity  = null;
                    result.Message = "Login error";
                    return(result);
                }



                var countEmployers = (int)(((IEnumerable <dynamic>)result.Entity).First().n);
                if (countEmployers > 0)
                {
                    result.Entity  = null;
                    result.Success = false;
                    result.Message = "Email already in use";
                }

                entity.ModifyDate = DateTime.Now;

                query.Query    = @"
                        BEGIN TRAN
                        Update Employers Set 

                                                    [EmployerName] = ISNULL( @EmployerName , EmployerName ) ,
                                                    [AgentFirstName] = ISNULL( @AgentFirstName , AgentFirstName ) ,
                                                    [AgentLastName] = ISNULL( @AgentLastName , AgentLastName ) ,
                                                    [Email] = ISNULL( @Email , Email ) ,
                                                    [ModifyDate] = ISNULL( @ModifyDate , ModifyDate ) ,
                                                    [Area] = ISNULL( @Area , Area ) ,
                                                    [Country] = ISNULL( @Country , Country ) ,
                                                    [State] = ISNULL( @State , State ) ,
                                                    [Suburb] = ISNULL( @Suburb , Suburb ) ,
                                                    [PostalCode] = ISNULL( @PostalCode , PostalCode ) ,
                                                    [AddressLine1] = ISNULL( @AddressLine1 , AddressLine1 ) ,
                                                    [AddressLine2] = ISNULL( @AddressLine2 , AddressLine2 ) ,
                                                    [MembershipType] = ISNULL( @MembershipType , MembershipType ) ,
                                                    [MembershipStartDate] = ISNULL( @MembershipStartDate , MembershipStartDate ) ,
                                                    [MembershipEndDate] = ISNULL( @MembershipEndDate , MembershipEndDate ) 
                            where EmployerId = @EmployerId;
                            SELECT * FROM EMPLOYERS WHERE EmployerId = @EmployerId;
                            COMMIT TRAN
    ";
                query.Entity   = entity;
                result         = con.ExecuteQuery <EmployerEntity>(query);
                result.Message = result.Success ? "The user details has been updated" : "An error has occurred";
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                result         = result ?? new Result(false);
                result.Message = "An error occurred";
                throw;
            }

            return(result);
        }
Ejemplo n.º 24
0
        public Result ChangePassword(EmployerEntity entity)
        {
            var result = new Result();

            try
            {
                var credentials = new CredentialsManager();
                var con         = new DapperConnectionManager();
                var query       = new QueryEntity();

                //GET the user to check password
                query.Query  = @"SELECT * FROM Employers
                            where EmployerID = @EmployerID and Active = 1";
                query.Entity = entity;
                result       = con.ExecuteQuery <EmployerEntity>(query);

                if (!result.Success)
                {
                    result.Entity  = null;
                    result.Message = "Validation error";
                    return(result);
                }

                var r = (IEnumerable <EmployerEntity>)result.Entity;

                var user = r.FirstOrDefault();

                if (user == null)
                {
                    result.Entity  = null;
                    result.Message = "Validation error";
                    result.Success = false;
                    return(result);
                }


                var password = credentials.EncodePassword(entity.Password, user.Hash);
                if (password != user.Password)
                {
                    result.Entity  = null;
                    result.Message = "Invalid password";
                    result.Success = false;
                    return(result);
                }

                var newHash = credentials.GenerateSalt();

                entity.Hash     = newHash;
                entity.Password = credentials.EncodePassword(entity.NewPassword, newHash);

                query.Query  = @"Update Employers Set Password = @Password, Hash = @Hash
                            where EmployerID = @EmployerID";
                query.Entity = new { EmployerID = entity.EmployerId, Hash = entity.Hash, Password = entity.Password };

                result         = con.ExecuteQuery <EmployerEntity>(query);
                result.Message = result.Success ? "The user password has been updated" : "An error has occurred";
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                result         = result ?? new Result(false);
                result.Message = "An error occurred";
                throw;
            }

            return(result);
        }
Ejemplo n.º 25
0
        public Result Register(EmployerEntity entity)
        {
            var result = new Result();

            try
            {
                if (entity.Password.Length < 6)
                {
                    result         = new Result(false);
                    result.Message = "Password length invalid";
                    return(result);
                }

                var con   = new DapperConnectionManager();
                var query = new QueryEntity();

                var credentials = new CredentialsManager();

                var hash = credentials.GenerateSalt();

                entity.Password = credentials.EncodePassword(entity.Password, hash);
                entity.Hash     = hash;
                if (!entity.Email.Contains("@") || entity.Email.Length < 3)
                {
                    result         = new Result(false);
                    result.Message = "Email invalid";
                    return(result);
                }
                entity.Email = entity.Email.Trim().ToLower();

                var queryCheckEmail = new QueryEntity()
                {
                    Entity = new { Email = entity.Email },
                    Query  = @"SELECT Email from Employers where Email = @Email and Active = 1"
                };
                var resultCheckEmail = con.ExecuteQuery <EmployerEntity>(queryCheckEmail);
                var dump             = ObjectDumper.Dump(resultCheckEmail);
                if (!resultCheckEmail.Success)
                {
                    resultCheckEmail.Entity  = null;
                    resultCheckEmail.Success = false;
                    resultCheckEmail.Message = "An error occurred with email check";
                    return(resultCheckEmail);
                }
                var checkEmail = (IEnumerable <EmployerEntity>)resultCheckEmail.Entity;
                if (checkEmail.Any())
                {
                    resultCheckEmail.Entity  = null;
                    resultCheckEmail.Success = false;
                    resultCheckEmail.Message = "The email is currently in use";
                    return(resultCheckEmail);
                }

                entity.CreateDate = DateTime.Now;
                entity.ModifyDate = DateTime.Now;

                query.Entity = entity;
                query.Query  = @"INSERT INTO Employers (Email, EmployerName, Password, Hash, CreateDate, ModifyDate) VALUES(@Email, @EmployerName, @Password, @Hash, @CreateDate, @ModifyDate)";

                result = con.InsertQuery(query);
                if (result.Success)
                {
                    entity.EmployerId = (int)result.Entity;
                    entity.Password   = "";
                    entity.Hash       = "";
                    entity.Token      = credentials.GenerateEmployerToken(entity);
                    result.Entity     = entity;

                    Task.Run(() => new EmailManager().SendEmail(entity.Email, DL.Models.EmailType.Welcome, new
                    {
                        CurrentUserName  = entity.EmployerName,
                        CurrentUserEmail = entity.Email
                    }));
                }
                result.Message = result.Success ? "The employer has been created" : "An error occurred";
            }
            catch (Exception ex)
            {
                if (result == null)
                {
                    result = new Result();
                }
                Logger.Log(ex);
                result.Entity  = null;
                result.Success = false;
                result.Message = "An error occurred with exception";
            }
            return(result);
        }