Ejemplo n.º 1
0
 public JsonResult AddRole(RolePageViewModel role)
 {
     try
     {
         #region Add Role
         var existRole = _db.AspNetRoles.Any(x => x.Id == role.Id.ToString() || x.Name == role.Name);
         if (existRole)
         {
             //Role Already Exist
             return(null);
         }
         var newRole = new AspNetRole
         {
             Id           = role.Id.ToString(),
             Name         = role.Name,
             FriendlyName = role.FriendlyName,
             Description  = role.Description,
         };
         _db.AspNetRoles.Add(newRole);
         _db.SaveChanges();
         #endregion
         return(Json(newRole, JsonRequestBehavior.AllowGet));
     }
     catch (Exception ex)
     {
         LogHelper.LogException(User.Identity.Name, ex, "Error While adding new Role");
         return(null);
     }
 }
Ejemplo n.º 2
0
        public JsonResult AddPermission(PermissionViewModel permission)
        {
            try
            {
                #region Add Permission
                var permis = new Permission()
                {
                    CreatedBy     = User.Identity.Name,
                    CreatedOn     = DateTime.Now,
                    Status        = permission.Status,
                    PageUrl       = permission.PageUrl ?? String.Empty,
                    Description   = permission.Description,
                    PageName      = permission.PageName,
                    PermissionKey = permission.PermissionKey
                };
                _db.Permissions.Add(permis);
                _db.SaveChanges();


                _db.SaveChanges();


                #endregion


                return(Json(permission, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                LogHelper.LogException(User.Identity.Name, ex, "Error While adding new Permission");
                return(null);
            }
        }
Ejemplo n.º 3
0
        public JsonResult AddMenu(MenuViewModel menu)
        {
            try
            {
                int languageId = CultureHelper.GetCurrentLanguageId(Request.Cookies["_culture"]);

                #region Add Menu
                var men = new Menu()
                {
                    CreatedBy = User.Identity.Name,
                    CreatedOn = DateTime.Now,
                    ParentId  = menu.ParentId,
                    Status    = menu.Status,
                    Icon      = menu.Icon,
                    PageId    = menu.PageId,
                    SortOrder = menu.SortOrder,
                    PageUrl   = menu.PageUrl
                };
                _db.Menus.Add(men);
                _db.SaveChanges();

                var menTrans = new MenuTranslation()
                {
                    MenuId      = men.Id,
                    Description = menu.Description,
                    IsDefault   = languageId == CultureHelper.GetDefaultLanguageId(),
                    LanguageId  = languageId,
                    Title       = menu.Title
                };
                _db.MenuTranslations.Add(menTrans);
                if (!menTrans.IsDefault)
                {
                    var menTrans1 = new MenuTranslation()
                    {
                        MenuId      = men.Id,
                        Description = menu.Description,
                        IsDefault   = true,
                        LanguageId  = CultureHelper.GetDefaultLanguageId(),
                        Title       = menu.Title
                    };
                    _db.MenuTranslations.Add(menTrans1);
                }

                _db.SaveChanges();


                #endregion


                return(Json(menu, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                LogHelper.LogException(User.Identity.Name, ex, "Error While adding new menu");
                return(null);
            }
        }
Ejemplo n.º 4
0
        public JsonResult AddSMSTemplate(SMSTemplateViewModel smsTemplate)
        {
            try
            {
                int languageId = smsTemplate.LanguageId;

                #region Add SMS Template
                var men = new SMSTemplate()
                {
                    CreatedBy       = User.Identity.Name,
                    CreatedOn       = DateTime.Now,
                    DefaultLanguage = smsTemplate.DefaultTemplateLanguage > 0 ? smsTemplate.DefaultTemplateLanguage : CultureHelper.GetDefaultLanguageId(),
                    Status          = smsTemplate.Status,
                };
                _db.SMSTemplates.Add(men);
                _db.SaveChanges();

                var menTrans = new SMSTemplateTranslation()
                {
                    SMSTemplateId = men.Id,
                    Description   = smsTemplate.Description,
                    LanguageId    = languageId,
                    IsDefault     = languageId == CultureHelper.GetDefaultLanguageId(),
                    Name          = smsTemplate.Name
                };

                _db.SMSTemplateTranslations.Add(menTrans);
                if (!menTrans.IsDefault)
                {
                    var menTrans1 = new SMSTemplateTranslation()
                    {
                        SMSTemplateId = men.Id,
                        Description   = smsTemplate.Description,
                        LanguageId    = CultureHelper.GetDefaultLanguageId(),
                        IsDefault     = true,
                        Name          = smsTemplate.Name
                    };
                    _db.SMSTemplateTranslations.Add(menTrans1);
                }

                _db.SaveChanges();


                #endregion


                return(Json(smsTemplate, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                LogHelper.LogException(User.Identity.Name, ex, "Error While adding new SMS");
                return(null);
            }
        }
Ejemplo n.º 5
0
        public JsonResult AddDepartment(DepartmentViewModel department)
        {
            try
            {
                int languageId = CultureHelper.GetCurrentLanguageId(Request.Cookies["_culture"]);

                #region Add Department
                var men = new Department()
                {
                    CreatedBy = User.Identity.Name,
                    CreatedOn = DateTime.Now,
                    Status    = department.Status
                };
                _db.Departments.Add(men);
                _db.SaveChanges();

                var menTrans = new DepartmentTranslation()
                {
                    DepartmentId = men.Id,
                    Description  = department.Description,
                    IsDefault    = languageId == CultureHelper.GetDefaultLanguageId(),
                    LanguageId   = languageId,
                    Name         = department.Name
                };
                _db.DepartmentTranslations.Add(menTrans);
                if (!menTrans.IsDefault)
                {
                    var menTrans1 = new DepartmentTranslation()
                    {
                        DepartmentId = men.Id,
                        Description  = department.Description,
                        IsDefault    = true,
                        LanguageId   = CultureHelper.GetDefaultLanguageId(),
                        Name         = department.Name
                    };
                    _db.DepartmentTranslations.Add(menTrans1);
                }

                _db.SaveChanges();


                #endregion


                return(Json(department, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                LogHelper.LogException(User.Identity.Name, ex, "Error While adding new Department");
                return(null);
            }
        }
Ejemplo n.º 6
0
        public ActionResult AddSystemSetting(SettingViewModel Setting)
        {
            try
            {
                int languageId    = CultureHelper.GetCurrentLanguageId(Request.Cookies["_culture"]);
                var systemSetting = new SystemSetting
                {
                    CreatedOn = DateTime.Now,
                    CreatedBy = User.Identity.Name,
                    Status    = Setting.Status,
                    DeletedOn = Setting.DeletedOn,
                };
                _db.SystemSettings.Add(systemSetting);
                _db.SaveChanges();

                var systemSettingTran = new SystemSettingTranslation()
                {
                    Name       = Setting.Name,
                    LanguageId = languageId,
                    IsDefault  = languageId == CultureHelper.GetDefaultLanguageId(),
                    SettingId  = systemSetting.Id,
                    Value      = Setting.Value
                };
                _db.SystemSettingTranslations.Add(systemSettingTran);

                if (!systemSettingTran.IsDefault)
                {
                    var systemSettingTran1 = new SystemSettingTranslation()
                    {
                        Name       = Setting.Name,
                        LanguageId = CultureHelper.GetDefaultLanguageId(),
                        IsDefault  = true,
                        SettingId  = systemSetting.Id,
                        Value      = Setting.Value
                    };
                    _db.SystemSettingTranslations.Add(systemSettingTran1);
                }
                _db.SaveChanges();

                return(Json(Setting, JsonRequestBehavior.AllowGet));
            }

            catch (Exception ex)
            {
                LogHelper.LogException(User.Identity.Name, ex, "Error while add System Settings");
                return(null);
            }
        }
Ejemplo n.º 7
0
        public JsonResult AddDetailsLookup(DetailsLookupViewModel DetailsLookupViewModel)
        {
            try
            {
                int languageId    = CultureHelper.GetCurrentLanguageId(Request.Cookies["_culture"]);
                var DetailsLookup = new DetailsLookup
                {
                    CreatedOn = DateTime.Now,
                    CreatedBy = User.Identity.Name,
                    Status    = DetailsLookupViewModel.Status,
                    MasterId  = DetailsLookupViewModel.MasterId,
                };
                _db.DetailsLookups.Add(DetailsLookup);
                _db.SaveChanges();

                var detailsLookupTran = new DetailsLookupTranslation()
                {
                    Value           = DetailsLookupViewModel.Name,
                    LanguageId      = languageId,
                    IsDefault       = languageId == CultureHelper.GetDefaultLanguageId(),
                    DetailsLookupId = DetailsLookup.Id,
                };
                _db.DetailsLookupTranslations.Add(detailsLookupTran);

                if (!detailsLookupTran.IsDefault)
                {
                    var detailsLookupTran1 = new DetailsLookupTranslation()
                    {
                        Value           = DetailsLookupViewModel.Name,
                        LanguageId      = CultureHelper.GetDefaultLanguageId(),
                        IsDefault       = true,
                        DetailsLookupId = DetailsLookup.Id
                    };
                    _db.DetailsLookupTranslations.Add(detailsLookupTran1);
                }
                _db.SaveChanges();

                DetailsLookupViewModel.Id = DetailsLookup.Id;
                return(Json(DetailsLookupViewModel, JsonRequestBehavior.AllowGet));
            }

            catch (Exception ex)
            {
                LogHelper.LogException(User.Identity.Name, ex, "Error while add Details lookup");
                return(null);
            }
        }
Ejemplo n.º 8
0
        public void Create(CampaignViewModel c)
        {
            var companyId = SessionHelper.GetCompanyId();
            var campData  = new Campaign()
            {
                Name      = c.Name,
                StartDate = c.StartDate,
                EndDate   = c.EndDate,
                CompanyId = companyId
            };

            if (ModelState.IsValid)
            {
                _db.Campaigns.Add(campData);
                _db.SaveChanges();
                Response.Redirect(Request.Url.ToString(), false);
            }
            Response.Redirect(Request.Url.ToString(), false);
        }
Ejemplo n.º 9
0
 public ActionResult LeadInfo(LeadViewModel lead)
 {
     try
     {
         // TODO: Add update logic here
         var leadData = _db.Leads.Find(lead.Id);
         if (leadData != null)
         {
             leadData.Name = lead.Name;
             leadData.Phone_Number = lead.Phone_Number;
             leadData.Email = lead.Email;
             leadData.Address = lead.Address;
             leadData.Notes = lead.Notes;
             leadData.Status = (int)lead.Status;
             leadData.AssigneeId = lead.AssigneeId;
             leadData.CampaignId = lead.CampaignId;
             _db.SaveChanges();
             TempData["message"] = "The lead has been Updated";
         }
         return RedirectToAction("LeadInfo", new {id= lead.Id});
     }
     catch (Exception ex)
     {
         LogHelper.LogException(User.Identity.Name, ex, "Error While editing Lead (Post)");
         return null;
     }
 }
Ejemplo n.º 10
0
 public static void AddSystemLog(SystemLog log)
 {
     using (var db = new CrmSystemEntities())
     {
         try
         {
             db.SystemLogs.Add(log);
             db.SaveChanges();
         }
         catch (Exception ex)
         {
             //TODO: Send Email incase of the failure of adding appliaction log
         }
     }
 }
Ejemplo n.º 11
0
 public static void AddEmailLog(CommunicationLog log)
 {
     using (var db = new CrmSystemEntities())
     {
         try
         {
             db.CommunicationLogs.Add(log);
             db.SaveChanges();
         }
         catch (Exception ex)
         {
             //TODO: Send Email incase of the failure of adding Email log
         }
     }
 }
Ejemplo n.º 12
0
 // POST api/<controller>
 public HttpResponseMessage Post(CampaignViewModel campaign)
 {
     try
     {
         var data = new Campaign()
         {
             Name      = campaign.Name,
             StartDate = campaign.StartDate,
             EndDate   = campaign.EndDate
         };
         _db.Campaigns.Add(data);
         _db.SaveChanges();
         var msg = Request.CreateResponse(HttpStatusCode.Created, data);
         return(msg);
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
     }
 }
Ejemplo n.º 13
0
        // POST api/LeadController
        public HttpResponseMessage Post(LeadViewModel lead)
        {
            try
            {
                var record = _db.Leads.Where(r => r.Phone_Number == lead.Phone_Number).ToList();

                var rr = 121;
                if (record.Count() == 0)
                {
                    var data = new Lead()
                    {
                        Name         = lead.Name,
                        Email        = lead.Email,
                        Address      = lead.Address,
                        Status       = (int)LeadStatusEnum.New,
                        Phone_Number = lead.Phone_Number,
                        Notes        = lead.Notes,
                        CampaignId   = lead.CampaignId,
                        Created_Date = DateTime.Now
                    };
                    _db.Leads.Add(data);
                    _db.SaveChanges();
                    var msg = Request.CreateResponse(HttpStatusCode.Created, data);
                    return(msg);
                }
                else
                {
                    var msg2 = Request.CreateResponse(HttpStatusCode.Found);
                    return(msg2);
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Ejemplo n.º 14
0
 private static void AddEmailToCommunicationLog(int typeId, string LogText, IPrincipal User = null)
 {
     using (var db = new CrmSystemEntities())
     {
         var username = User != null ? User.Identity.Name : Constants.Users.Service;
         try
         {
             var data = new CommunicationLog()
             {
                 TypeId    = typeId,
                 LogText   = LogText,
                 CreatedBy = username,
                 CreatedOn = DateTime.Now,
                 Status    = (int)GeneralEnums.StatusEnum.Active,
             };
             db.CommunicationLogs.Add(data);
             db.SaveChanges();
         }
         catch (Exception ex)
         {
             //TODO QASEM LogHelper.LogException(username, ex, $"Error while saving communication log for sms template as email for msg {LogText}");
         }
     }
 }
Ejemplo n.º 15
0
        public ActionResult Details(CitizenProfileViewModel profile)
        {
            int languageId = CultureHelper.GetCurrentLanguageId(Request.Cookies["_culture"]);

            try
            {
                if (profile.LanguageId == 0)
                {
                    profile.LanguageId = CultureHelper.GetDefaultLanguageId();
                }

                var userProfile = _db.UserProfiles.Find(profile.Id);

                if (userProfile != null)
                {
                    userProfile.GenderLookupId     = profile.GenderLookupId;
                    userProfile.PreferedLanguageId = profile.PrefferdLanguage;
                    userProfile.Birthday           = profile.BirthDay;
                    userProfile.Fax                   = profile.Fax;
                    userProfile.IdNumber              = profile.IdNumber;
                    userProfile.PhoneNumber           = profile.PhoneNumber;
                    userProfile.RegionId              = profile.RegionId;
                    userProfile.CityId                = profile.CityId;
                    userProfile.ProvinceId            = profile.ProvinceId;
                    userProfile.MartialStatusLookupId = profile.MartialStatusLookupId;
                    userProfile.ProfilePhoto          = profile.ProfilePath;
                    userProfile.Mobile                = profile.Mobile;

                    _db.Entry(userProfile).State = EntityState.Modified;
                    _db.SaveChanges();

                    var userProfileTrans = _db.UserProfileTranslations.FirstOrDefault(r =>
                                                                                      r.UserProfileId == userProfile.Id && r.LanguageId == profile.LanguageId);
                    if (userProfileTrans != null)
                    {
                        userProfileTrans.FullName         = profile.FullName;
                        userProfileTrans.Address          = profile.Address;
                        _db.Entry(userProfileTrans).State = EntityState.Modified;
                    }
                    else
                    {
                        userProfileTrans = new UserProfileTranslation()
                        {
                            UserProfileId = userProfile.Id,
                            IsDefault     = false,
                            LanguageId    = profile.LanguageId,
                            FullName      = profile.FullName,
                            Address       = profile.Address,
                        };
                        _db.UserProfileTranslations.Add(userProfileTrans);
                    }
                }

                _db.SaveChanges();
                return(RedirectToAction("Details", new { id = profile.Id }));
            }
            catch (Exception ex)
            {
                LogHelper.LogException(User.Identity.Name, ex, "Error While Updating profile");
            }
            var prefferdLanguage = LookupHelper.GetLookupDetailsByMasterId((int)GeneralEnums.MasterLookupEnums.PrefferdLanguage,
                                                                           Request.Cookies["_culture"]);

            ViewBag.PrefferdLanguage = new SelectList(prefferdLanguage, "Id", "Name", profile.PrefferdLanguage);
            ViewBag.GenderLookupId   =
                new SelectList(
                    LookupHelper.GetLookupDetailsByMasterId((int)GeneralEnums.MasterLookupEnums.Gender,
                                                            Request.Cookies["_culture"]), "Id", "Name");
            ViewBag.MartialStatusLookupId = new SelectList(LookupHelper.GetLookupDetailsByMasterId((int)GeneralEnums.MasterLookupEnums.MartialStatus, Request.Cookies["_culture"]), "Id", "Name", profile.MartialStatusLookupId);
            ViewBag.ProvinceId            = new SelectList(LookupHelper.GetLookupDetailsByMasterId((int)GeneralEnums.MasterLookupEnums.Province, Request.Cookies["_culture"]), "Id", "Name", profile.ProvinceId);
            ViewBag.RegionId = new SelectList(LookupHelper.GetLookupDetailsByMasterId((int)GeneralEnums.MasterLookupEnums.Region, Request.Cookies["_culture"]), "Id", "Name", profile.RegionId);
            ViewBag.CityId   = new SelectList(LookupHelper.GetLookupDetailsByMasterId((int)GeneralEnums.MasterLookupEnums.City, Request.Cookies["_culture"]), "Id", "Name", profile.CityId);

            return(View(profile));
        }
Ejemplo n.º 16
0
        public static SettingViewModel GetOrCreate(string name, string defaultValue, int languageId = (int)GeneralEnums.LanguageEnum.Arabic)
        {
            using (var db = new CrmSystemEntities())
            {
                var setting = db.SystemSettings.FirstOrDefault(r =>
                                                               r.SystemSettingTranslations.Any(x => x.Name == name && x.LanguageId == languageId) &&
                                                               r.Status == (int)GeneralEnums.StatusEnum.Active) ?? db.SystemSettings.FirstOrDefault(r =>
                                                                                                                                                    r.SystemSettingTranslations.Any(x => x.Name == name && x.IsDefault) &&
                                                                                                                                                    r.Status == (int)GeneralEnums.StatusEnum.Active);

                if (setting == null)
                {
                    setting = new SystemSetting
                    {
                        Status    = (int)GeneralEnums.StatusEnum.Active,
                        CreatedBy = "System",
                        CreatedOn = DateTime.Now
                    };
                    db.SystemSettings.Add(setting);
                    db.SaveChanges();

                    var settingTrans = new SystemSettingTranslation()
                    {
                        LanguageId = languageId,
                        IsDefault  = languageId == CultureHelper.GetDefaultLanguageId(),
                        Name       = name,
                        Value      = defaultValue,
                        SettingId  = setting.Id
                    };
                    db.SystemSettingTranslations.Add(settingTrans);
                    if (!settingTrans.IsDefault)
                    {
                        var settingTrans1 = new SystemSettingTranslation()
                        {
                            LanguageId = CultureHelper.GetDefaultLanguageId(),
                            IsDefault  = true,
                            Name       = name,
                            Value      = defaultValue,
                            SettingId  = setting.Id
                        };
                        db.SystemSettingTranslations.Add(settingTrans1);
                    }
                    db.SaveChanges();

                    var sysSetting = new SettingViewModel()
                    {
                        Id    = setting.Id,
                        Name  = settingTrans.Name,
                        Value = settingTrans.Value
                    };

                    return(sysSetting);
                }
                else
                {
                    return(new SettingViewModel()
                    {
                        Id = setting.Id,
                        Name = setting.SystemSettingTranslations.FirstOrDefault()?.Name,
                        Value = setting.SystemSettingTranslations.FirstOrDefault()?.Value
                    });
                }
            }
        }
Ejemplo n.º 17
0
        public async Task <IHttpActionResult> UploadFile(int id)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return(Content(HttpStatusCode.UnsupportedMediaType, new BaseApiResponse()
                {
                    StatusCode = HttpStatusCode.UnsupportedMediaType,
                    Message = Constants.ApiMessages.UnSupported
                }));
            }

            try
            {
                var provider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(provider);

                var sysFiles = new List <FileResponse>();
                foreach (var file in provider.Contents)
                {
                    var dataStream = await file.ReadAsByteArrayAsync();

                    var sysFile = new SystemFile
                    {
                        CreatedBy  = User.Identity.Name,
                        CreatedOn  = DateTime.Now,
                        Status     = (int)GeneralEnums.StatusEnum.Active,
                        TypeId     = id,
                        FileUrl    = string.Empty,
                        ModifiedBy = User.Identity.Name,
                        ModifiedOn = DateTime.Now
                    };
                    _db.SystemFiles.Add(sysFile);
                    _db.SaveChanges();

                    var extention = Path.GetExtension(file.Headers.ContentDisposition.FileName.Trim('"').Trim('/'));

                    File.WriteAllBytes(
                        HttpContext.Current.Server.MapPath($"~/Document/{id}/{sysFile.Id}{extention}"), dataStream);
                    var setting =
                        SettingHelper.GetOrCreate(Constants.SystemSettings.WebsiteUrl, "http://localhost:61712/");
                    var url = $"{setting.Value}/Document/{id}/{sysFile.Id}{extention}";
                    sysFiles.Add(new FileResponse()
                    {
                        Id         = sysFile.Id,
                        CreatedOn  = sysFile.CreatedOn,
                        TypeId     = sysFile.TypeId,
                        FileUrl    = url,
                        StatusCode = HttpStatusCode.OK,
                        Message    = Constants.ApiMessages.Success
                    });
                    sysFile.FileUrl          = url;
                    _db.Entry(sysFile).State = EntityState.Modified;
                    _db.SaveChanges();

                    var sysFileTrans = new SystemFileTranslation()
                    {
                        Description  = string.Empty,
                        DisplayName  = string.Empty,
                        IsDefault    = true,
                        LanguageId   = CultureHelper.GetDefaultLanguageId(),
                        SystemFileId = sysFile.Id
                    };
                    _db.SystemFileTranslations.Add(sysFileTrans);
                    _db.SaveChanges();
                }
                return(Ok(sysFiles));
            }
            catch (Exception ex)
            {
                LogHelper.LogException(User.Identity.Name, ex, "Error While uploading file!");
                return(Content(HttpStatusCode.InternalServerError, new BaseApiResponse()
                {
                    StatusCode = HttpStatusCode.InternalServerError,
                    Message = Constants.ApiMessages.GeneralError
                }));
            }
        }
Ejemplo n.º 18
0
        public JsonResult AddProfile(ProfileViewModel profile)
        {
            var companyId = SessionHelper.GetCompanyId();
            var account   = _db.UserProfiles.FirstOrDefault(r => r.Username != profile.Email && r.Status == (int)GeneralEnums.StatusEnum.Deleted && profile.CompanyId == companyId);

            if (account != null && account.Status == (int)GeneralEnums.StatusEnum.Deactive)
            {
                string Msg = "تم تعطيل هذا الحساب من قبل المسؤول ";

                return(Json(new { Id = 0, Msg = Msg }, JsonRequestBehavior.AllowGet));
            }

            var user = new ApplicationUser {
                UserName = profile.Email, Email = profile.Email
            };
            var result     = UserManager.CreateAsync(user, profile.Password);
            int languageId = CultureHelper.GetCurrentLanguageId(Request.Cookies["_culture"]);

            if (result.Result.Succeeded)
            {
                string customerId = null;

                try
                {
                    var profil = new UserProfile()
                    {
                        Fax                   = profile.Fax,
                        Birthday              = profile.BirthDay,
                        CreatedOn             = DateTime.Now,
                        GenderLookupId        = profile.GenderLookupId,
                        ProvinceId            = profile.ProvinceId,
                        CityId                = profile.CityId,
                        RegionId              = profile.RegionId,
                        IdNumber              = profile.IdNumber ?? string.Empty,
                        PhoneNumber           = profile.PhoneNumber ?? string.Empty,
                        Mobile                = profile.Mobile ?? string.Empty,
                        MartialStatusLookupId = profile.MartialStatusLookupId,
                        ManagerId             = profile.ManagerId,
                        DepartmentId          = profile.Department,
                        PreferedLanguageId    = profile.PrefferdLanguage,
                        Status                = (int)GeneralEnums.StatusEnum.Active,
                        Username              = profile.Username,
                        Email                 = profile.Email,
                        CompanyId             = SessionHelper.GetCompanyId(),
                    };
                    _db.UserProfiles.Add(profil);
                    _db.SaveChanges();

                    var profTrans = new UserProfileTranslation()
                    {
                        Address       = profile.Address,
                        FullName      = profile.FullName,
                        IsDefault     = languageId == CultureHelper.GetDefaultLanguageId(),
                        LanguageId    = languageId,
                        UserProfileId = profil.Id
                    };
                    _db.UserProfileTranslations.Add(profTrans);
                    if (!profTrans.IsDefault)
                    {
                        var profTrans1 = new UserProfileTranslation()
                        {
                            Address       = profile.Address ?? string.Empty,
                            FullName      = profile.FullName,
                            IsDefault     = true,
                            LanguageId    = CultureHelper.GetDefaultLanguageId(),
                            UserProfileId = profil.Id
                        };
                        _db.UserProfileTranslations.Add(profTrans1);
                    }

                    _db.SaveChanges();

                    profile.Id = profil.Id;
                    string roleId = ((int)GeneralEnums.Role.User).ToString();
                    // var userProfile = _db.UserProfiles.Find(UserId);
                    var aspUser = _db.AspNetUsers.FirstOrDefault(r => r.UserName == profil.Username);
                    if (!_db.AspNetUserRoles.Any(r => r.UserId == aspUser.Id && r.RoleId == roleId))
                    {
                        _db.AspNetUserRoles.Add(new AspNetUserRole()
                        {
                            RoleId = roleId,
                            UserId = aspUser.Id
                        });
                        _db.SaveChanges();
                    }
                    return(Json(profile, JsonRequestBehavior.AllowGet));
                }
                catch (Exception ex)
                {
                    LogHelper.LogException(User.Identity.Name, ex, "Error While adding new profile");
                    UserManager.Delete(user);
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 19
0
        public IHttpActionResult Register(ProfileViewModel registerModel)
        {
            AuthenticationHelper.ApiAuthorizationCheck(Request);
            try
            {
                var lang       = Request?.Headers?.AcceptLanguage?.FirstOrDefault()?.Value ?? "ar";
                var languageId = lang == "ar"
                    ? (int)GeneralEnums.LanguageEnum.Arabic
                    : (int)GeneralEnums.LanguageEnum.English;

                var user = new ApplicationUser {
                    UserName = registerModel.Username, Email = registerModel.Email
                };
                var result = UserManager.CreateAsync(user, registerModel.Password);
                if (result.Result.Succeeded)
                {
                    var roleId = _db.AspNetRoles.FirstOrDefault(r => r.Name == Core.Constants.Roles.Citizen)?.Id;
                    if (roleId != null)
                    {
                        _db.AspNetUserRoles.Add(new AspNetUserRole()
                        {
                            RoleId = roleId,
                            UserId = user.Id
                        });
                        _db.SaveChanges();
                    }

                    var city          = LookupHelper.GetLookupDetailsByCode(registerModel.CityCode)?.Id;
                    var gender        = LookupHelper.GetLookupDetailsByCode(registerModel.GenderCode)?.Id;
                    var martialStatus = LookupHelper.GetLookupDetailsByCode(registerModel.MartialStatusCode)?.Id;
                    var province      = LookupHelper.GetLookupDetailsByCode(registerModel.ProvinceCode)?.Id;

                    var profil = new UserProfile
                    {
                        Fax                   = registerModel.Fax ?? string.Empty,
                        Birthday              = registerModel.BirthDay,
                        CreatedOn             = DateTime.Now,
                        GenderLookupId        = gender,
                        ProvinceId            = province,
                        CityId                = city,
                        RegionId              = registerModel.RegionId,
                        IdNumber              = registerModel.IdNumber ?? string.Empty,
                        PhoneNumber           = registerModel.PhoneNumber ?? string.Empty,
                        Mobile                = registerModel.Mobile ?? string.Empty,
                        MartialStatusLookupId = martialStatus,
                        ManagerId             = registerModel.ManagerId,
                        DepartmentId          = registerModel.Department,
                        PreferedLanguageId    = registerModel.PrefferdLanguage,
                        Status                = (int)GeneralEnums.StatusEnum.Active,
                        Username              = registerModel.Username,
                        Email                 = registerModel.Email
                    };
                    _db.UserProfiles.Add(profil);
                    _db.SaveChanges();

                    var profTrans = new UserProfileTranslation()
                    {
                        Address       = registerModel.Address ?? string.Empty,
                        FullName      = registerModel.FullName,
                        IsDefault     = languageId == CultureHelper.GetDefaultLanguageId(),
                        LanguageId    = languageId,
                        UserProfileId = profil.Id
                    };
                    _db.UserProfileTranslations.Add(profTrans);
                    if (!profTrans.IsDefault)
                    {
                        var profTrans1 = new UserProfileTranslation()
                        {
                            Address       = registerModel.Address ?? string.Empty,
                            FullName      = registerModel.FullName,
                            IsDefault     = true,
                            LanguageId    = CultureHelper.GetDefaultLanguageId(),
                            UserProfileId = profil.Id
                        };
                        _db.UserProfileTranslations.Add(profTrans1);
                    }

                    _db.SaveChanges();
                    registerModel.Id = profil.Id;
                    return(Ok(registerModel));
                }
                else
                {
                    return(Content(HttpStatusCode.Forbidden, new BaseApiResponse()
                    {
                        StatusCode = HttpStatusCode.Forbidden,
                        Message = result.Result.Errors.FirstOrDefault()
                    }));
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogException(Core.Constants.Users.System, ex, Core.Constants.Errors.Apis.ErrorRegister);
                return(Content(HttpStatusCode.InternalServerError, new BaseApiResponse()
                {
                    StatusCode = HttpStatusCode.InternalServerError,
                    Message = Core.Constants.Errors.Apis.ErrorRegister
                }));
            }
        }