private static void AddInitialServiceArea(this IDbAppContext context, ServiceArea initialServiceArea)
        {
            ServiceArea serviceArea = context.GetServiceAreaByMinistryServiceAreaId(initialServiceArea.MinistryServiceAreaID);

            if (serviceArea != null)
            {
                return;
            }

            serviceArea = new ServiceArea
            {
                MinistryServiceAreaID = initialServiceArea.MinistryServiceAreaID,
                Name      = initialServiceArea.Name,
                StartDate = initialServiceArea.StartDate
            };

            if (initialServiceArea.District != null)
            {
                District district = context.GetDistrictByMinistryDistrictId(initialServiceArea.District.MinistryDistrictID);
                serviceArea.District = district;
            }
            else
            {
                serviceArea.District = null;
            }

            context.ServiceAreas.Add(serviceArea);
            context.SaveChanges();
        }
        /// <summary>
        /// Update service area
        /// </summary>
        /// <param name="context"></param>
        /// <param name="serviceAreaInfo"></param>
        public static void UpdateSeedServiceAreaInfo(this DbAppContext context, ServiceArea serviceAreaInfo)
        {
            // Adjust the district.
            int ministryDistrictId = serviceAreaInfo.District.MinistryDistrictID;
            var exists             = context.Districts.Any(a => a.MinistryDistrictID == ministryDistrictId);

            if (exists)
            {
                District district = context.Districts.First(a => a.MinistryDistrictID == ministryDistrictId);
                serviceAreaInfo.District = district;
            }
            else
            {
                serviceAreaInfo.District = null;
            }

            ServiceArea serviceArea = context.GetServiceAreaByMinistryServiceAreaId(serviceAreaInfo.MinistryServiceAreaID);

            if (serviceArea == null)
            {
                context.ServiceAreas.Add(serviceAreaInfo);
            }
            else
            {
                serviceArea.Name      = serviceAreaInfo.Name;
                serviceArea.StartDate = serviceAreaInfo.StartDate;
                serviceArea.District  = serviceAreaInfo.District;
            }
        }
示例#3
0
        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;

                // Suitable nullity checks
                hash = hash * 59 + Id.GetHashCode();
                hash = hash * 59 + LocalAreaNumber.GetHashCode();

                if (Name != null)
                {
                    hash = hash * 59 + Name.GetHashCode();
                }

                if (ServiceArea != null)
                {
                    hash = hash * 59 + ServiceArea.GetHashCode();
                }

                hash = hash * 59 + StartDate.GetHashCode();

                if (EndDate != null)
                {
                    hash = hash * 59 + EndDate.GetHashCode();
                }

                return(hash);
            }
        }
示例#4
0
        private static void AddInitialServiceArea(this IDbAppContext context, ServiceArea initialServiceArea)
        {
            ServiceArea serviceArea = context.GetServiceAreaByMinistryServiceAreaId(initialServiceArea.MinistryServiceAreaID);

            if (serviceArea != null)
            {
                return;
            }

            serviceArea = new ServiceArea
            {
                MinistryServiceAreaID = initialServiceArea.MinistryServiceAreaID,
                Name                   = initialServiceArea.Name,
                StartDate              = initialServiceArea.StartDate,
                AppCreateUserid        = SystemId,
                AppCreateTimestamp     = DateTime.UtcNow,
                AppLastUpdateUserid    = SystemId,
                AppLastUpdateTimestamp = DateTime.UtcNow
            };

            if (initialServiceArea.District != null)
            {
                District district = context.GetDistrictByMinistryDistrictId(initialServiceArea.District.MinistryDistrictID);
                serviceArea.District = district;
            }
            else
            {
                serviceArea.District = null;
            }

            context.ServiceAreas.Add(serviceArea);
        }
        /// <summary>
        /// Returns a service area for a given Ministry Id
        /// </summary>
        /// <param name="context"></param>
        /// <param name="id">The Ministry Id</param>
        /// <returns>Region</returns>
        public static ServiceArea GetServiceAreaByMinistryServiceAreaId(this IDbAppContext context, int id)
        {
            ServiceArea serviceArea = context.ServiceAreas.Where(x => x.MinistryServiceAreaID == id)
                                      .Include(x => x.District.Region)
                                      .FirstOrDefault();

            return(serviceArea);
        }
示例#6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LocalArea" /> class.
 /// </summary>
 /// <param name="id">A system-generated unique identifier for a LocalArea (required).</param>
 /// <param name="localAreaNumber">A system-generated, visible to the user number for the Local Area (required).</param>
 /// <param name="name">The full name of the Local Area (required).</param>
 /// <param name="serviceArea">The Service Area in which the Local Area is found. (required).</param>
 /// <param name="startDate">The DATE the business information came into effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM (required).</param>
 /// <param name="endDate">The DATE the business information ceased to be in effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM.</param>
 public LocalArea(int id, int localAreaNumber, string name, ServiceArea serviceArea, DateTime startDate, DateTime?endDate = null)
 {
     Id = id;
     LocalAreaNumber = localAreaNumber;
     Name            = name;
     ServiceArea     = serviceArea;
     StartDate       = startDate;
     EndDate         = endDate;
 }
示例#7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LocalArea" /> class.
        /// </summary>
        /// <param name="Id">A system-generated unique identifier for a LocalArea (required).</param>
        /// <param name="LocalAreaNumber">A system-generated, visible to the user number for the Local Area (required).</param>
        /// <param name="Name">The full name of the Local Area (required).</param>
        /// <param name="ServiceArea">The Service Area in which the Local Area is found. (required).</param>
        /// <param name="StartDate">The DATE the business information came into effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM (required).</param>
        /// <param name="EndDate">The DATE the business information ceased to be in effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM.</param>
        public LocalArea(int Id, int LocalAreaNumber, string Name, ServiceArea ServiceArea, DateTime StartDate, DateTime?EndDate = null)
        {
            this.Id = Id;
            this.LocalAreaNumber = LocalAreaNumber;
            this.Name            = Name;
            this.ServiceArea     = ServiceArea;
            this.StartDate       = StartDate;



            this.EndDate = EndDate;
        }
示例#8
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="localArea"></param>
        /// <param name="systemId"></param>
        private static void CopyToInstance(DbAppContext dbContext, ImportModels.Area oldObject, ref LocalArea localArea, string systemId)
        {
            bool isNew = false;

            if (oldObject.Area_Id <= 0)
            {
                return;
            }

            if (localArea == null)
            {
                isNew     = true;
                localArea = new LocalArea {
                    Id = oldObject.Area_Id
                };
            }

            try
            {
                localArea.Name = oldObject.Area_Desc.Trim();
            }
            catch
            {
                // do nothing
            }

            try
            {
                ServiceArea serviceArea = dbContext.ServiceAreas.FirstOrDefault(x => x.MinistryServiceAreaID == oldObject.Service_Area_Id);
                localArea.ServiceArea = serviceArea;
            }
            catch
            {
                // do nothing
            }

            if (isNew)
            {
                localArea.CreateUserid    = systemId;
                localArea.CreateTimestamp = DateTime.UtcNow;
                dbContext.LocalAreas.Add(localArea);
            }
            else
            {
                localArea.LastUpdateUserid    = systemId;
                localArea.LastUpdateTimestamp = DateTime.UtcNow;
                dbContext.LocalAreas.Update(localArea);
            }
        }
        /// <summary>
        /// Copy xml item to instance (table entries)
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="instance"></param>
        /// <param name="systemId"></param>
        private static void CopyToInstance(DbAppContext dbContext, EquipType oldObject, ref DistrictEquipmentType instance, string systemId)
        {
            if (oldObject.Equip_Type_Id <= 0)
            {
                return;
            }

            // add the user specified in oldObject.Modified_By and oldObject.Created_By if not there in the database
            ImportUtility.AddUserFromString(dbContext, oldObject.Modified_By, systemId);
            User createdBy = ImportUtility.AddUserFromString(dbContext, oldObject.Created_By, systemId);

            if (instance == null)
            {
                instance = new DistrictEquipmentType {
                    Id = oldObject.Equip_Type_Id
                };

                try
                {
                    instance.DistrictEquipmentName = oldObject.Equip_Type_Cd.Length >= 10 ?
                                                     oldObject.Equip_Type_Cd.Substring(0, 10) :
                                                     oldObject.Equip_Type_Cd
                                                     + "-" + (oldObject.Equip_Type_Desc.Length >= 210 ?
                                                              oldObject.Equip_Type_Desc.Substring(0, 210) :
                                                              oldObject.Equip_Type_Desc);
                }
                catch
                {
                    // do nothing
                }

                ServiceArea serviceArea = dbContext.ServiceAreas.FirstOrDefault(x => x.MinistryServiceAreaID == oldObject.Service_Area_Id);

                if (serviceArea != null)
                {
                    int      districtId = serviceArea.DistrictId ?? 0;
                    District dis        = dbContext.Districts.FirstOrDefault(x => x.RegionId == districtId);
                    instance.DistrictId = districtId;
                    instance.District   = dis;
                }

                instance.CreateTimestamp = DateTime.UtcNow;
                instance.CreateUserid    = createdBy.SmUserId;
                dbContext.DistrictEquipmentTypes.Add(instance);
            }
        }
示例#10
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="localArea"></param>
        /// <param name="systemId"></param>
        private static void CopyToInstance(DbAppContext dbContext, Area oldObject, ref LocalArea localArea, string systemId)
        {
            try
            {
                if (oldObject.Area_Id <= 0)
                {
                    return;
                }

                localArea = new LocalArea
                {
                    Id = oldObject.Area_Id,
                    LocalAreaNumber = oldObject.Area_Id,
                    Name            = ImportUtility.GetCapitalCase(oldObject.Area_Desc.Trim())
                };

                // map to the correct service area
                ServiceArea serviceArea = dbContext.ServiceAreas.AsNoTracking()
                                          .FirstOrDefault(x => x.MinistryServiceAreaID == oldObject.Service_Area_Id);

                if (serviceArea == null)
                {
                    // not mapped correctly
                    return;
                }

                localArea.ServiceAreaId = serviceArea.Id;

                localArea.AppCreateUserid        = systemId;
                localArea.AppCreateTimestamp     = DateTime.UtcNow;
                localArea.AppLastUpdateUserid    = systemId;
                localArea.AppLastUpdateTimestamp = DateTime.UtcNow;

                dbContext.LocalAreas.Add(localArea);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
示例#11
0
        /// <summary>
        /// Returns true if LocalArea instances are equal
        /// </summary>
        /// <param name="other">Instance of LocalArea to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(LocalArea other)
        {
            if (other is null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Id == other.Id ||
                     Id.Equals(other.Id)
                     ) &&
                 (
                     LocalAreaNumber == other.LocalAreaNumber ||
                     LocalAreaNumber.Equals(other.LocalAreaNumber)
                 ) &&
                 (
                     Name == other.Name ||
                     Name != null &&
                     Name.Equals(other.Name)
                 ) &&
                 (
                     ServiceArea == other.ServiceArea ||
                     ServiceArea != null &&
                     ServiceArea.Equals(other.ServiceArea)
                 ) &&
                 (
                     StartDate == other.StartDate ||
                     StartDate.Equals(other.StartDate)
                 ) &&
                 (
                     EndDate == other.EndDate ||
                     EndDate != null &&
                     EndDate.Equals(other.EndDate)
                 ));
        }
示例#12
0
        /// <summary>
        /// Update service area
        /// </summary>
        /// <param name="context"></param>
        /// <param name="serviceAreaInfo"></param>
        public static void UpdateSeedServiceAreaInfo(this DbAppContext context, ServiceArea serviceAreaInfo)
        {
            // adding system Account if not there in the database
            ImportUtility.InsertSystemUser(context, SystemId);

            // Adjust the district.
            int ministryDistrictId = serviceAreaInfo.District.MinistryDistrictID;
            var exists             = context.Districts.Any(a => a.MinistryDistrictID == ministryDistrictId);

            if (exists)
            {
                District district = context.Districts.First(a => a.MinistryDistrictID == ministryDistrictId);
                serviceAreaInfo.District = district;
            }
            else
            {
                serviceAreaInfo.District = null;
            }

            ServiceArea serviceArea = context.GetServiceAreaByMinistryServiceAreaId(serviceAreaInfo.MinistryServiceAreaID);

            if (serviceArea == null)
            {
                serviceAreaInfo.AppCreateUserid        = SystemId;
                serviceAreaInfo.AppCreateTimestamp     = DateTime.UtcNow;
                serviceAreaInfo.AppLastUpdateUserid    = SystemId;
                serviceAreaInfo.AppLastUpdateTimestamp = DateTime.UtcNow;

                context.ServiceAreas.Add(serviceAreaInfo);
            }
            else
            {
                serviceArea.Name      = serviceAreaInfo.Name;
                serviceArea.StartDate = serviceAreaInfo.StartDate;
                serviceArea.District  = serviceAreaInfo.District;
            }
        }
示例#13
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="user"></param>
        /// <param name="systemId"></param>
        /// <param name="smUserId"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="maxUserIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, UserHets oldObject, ref User user,
                                           string systemId, string smUserId, string firstName, string lastName, ref int maxUserIndex)
        {
            try
            {
                // File contains multiple records per user (1 for each dsitrict they can access)
                // We are currently importing 1 only -> where Default_Service_Area = Y
                if (oldObject.Default_Service_Area != "Y")
                {
                    return;
                }

                if (user != null)
                {
                    return; // only add new users
                }

                user = new User
                {
                    Id       = ++maxUserIndex,
                    Active   = true,
                    SmUserId = smUserId,
                    SmAuthorizationDirectory = "IDIR"
                };

                if (!string.IsNullOrEmpty(firstName))
                {
                    user.GivenName = firstName;
                }

                if (!string.IsNullOrEmpty(lastName))
                {
                    user.Surname = lastName;
                }

                // *******************************************************************
                // create initials
                // *******************************************************************
                string temp = "";
                if (!string.IsNullOrEmpty(lastName) && lastName.Length > 0)
                {
                    temp = lastName.Substring(0, 1).ToUpper();
                }

                if (!string.IsNullOrEmpty(firstName) && firstName.Length > 0)
                {
                    temp = temp + firstName.Substring(0, 1).ToUpper();
                }

                if (!string.IsNullOrEmpty(temp))
                {
                    user.Initials = temp;
                }

                // *******************************************************************
                // map user to the correct service area
                // *******************************************************************
                int serviceAreaId;

                try
                {
                    serviceAreaId = int.Parse(oldObject.Service_Area_Id);
                }
                catch
                {
                    // not mapped correctly
                    throw new ArgumentException(string.Format("User Error - Invalid Service Area (userId: {0}", user.SmUserId));
                }

                ServiceArea serviceArea = dbContext.ServiceAreas.FirstOrDefault(x => x.MinistryServiceAreaID == serviceAreaId);

                if (serviceArea == null)
                {
                    // not mapped correctly
                    throw new ArgumentException(string.Format("User Error - Invalid Service Area (userId: {0}", user.SmUserId));
                }

                user.DistrictId = serviceArea.DistrictId;

                // *******************************************************************
                // set the user's role
                // ** all new users will be added with basic access only
                // *******************************************************************
                UserRole userRole = new UserRole();

                Role role = dbContext.Roles.FirstOrDefault(x => x.Name == "HETS Clerk");

                int roleId = -1;

                if (role != null)
                {
                    roleId = role.Id;
                }

                // ***********************************************
                // create user
                // ***********************************************
                user.AppCreateTimestamp     = DateTime.UtcNow;
                user.AppCreateUserid        = systemId;
                user.AppLastUpdateUserid    = systemId;
                user.AppLastUpdateTimestamp = DateTime.UtcNow;

                userRole.Role          = dbContext.Roles.First(x => x.Id == roleId);
                userRole.EffectiveDate = DateTime.UtcNow.AddDays(-1);

                userRole.AppCreateTimestamp     = DateTime.UtcNow;
                userRole.AppCreateUserid        = systemId;
                userRole.AppLastUpdateUserid    = systemId;
                userRole.AppLastUpdateTimestamp = DateTime.UtcNow;

                user.UserRoles = new List <UserRole> {
                    userRole
                };
                dbContext.Users.Add(user);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Employee Id: " + oldObject.Popt_Id);
                Debug.WriteLine("***Error*** - Master User Index: " + maxUserIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
示例#14
0
        /// <summary>
        /// Copy xml item to instance (table entries)
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="equipType"></param>
        /// <param name="systemId"></param>
        /// <param name="maxEquipTypeIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, EquipType oldObject,
                                           ref DistrictEquipmentType equipType, string systemId, ref int maxEquipTypeIndex)
        {
            try
            {
                if (oldObject.Equip_Type_Id <= 0)
                {
                    return;
                }

                if (equipType != null)
                {
                    return;
                }

                // get the equipment type
                string tempEquipTypeCode = ImportUtility.CleanString(oldObject.Equip_Type_Cd).ToUpper();

                // get the parent equipment type
                EquipmentType type = dbContext.EquipmentTypes.FirstOrDefault(x => x.Name == tempEquipTypeCode);

                if (type == null)
                {
                    throw new ArgumentException(
                              string.Format("Cannot find Equipment Type (Equipment Type Code: {0} | Equipment Type Id: {1})",
                                            tempEquipTypeCode, oldObject.Equip_Type_Id));
                }

                // get the description
                string tempDistrictDescription = ImportUtility.CleanString(oldObject.Equip_Type_Desc);
                tempDistrictDescription = ImportUtility.GetCapitalCase(tempDistrictDescription);

                // add new district equipment type
                int tempId = type.Id;

                equipType = new DistrictEquipmentType
                {
                    Id = ++maxEquipTypeIndex,
                    EquipmentTypeId       = tempId,
                    DistrictEquipmentName = tempDistrictDescription
                };

                // set the district
                ServiceArea serviceArea = dbContext.ServiceAreas.AsNoTracking()
                                          .Include(x => x.District)
                                          .FirstOrDefault(x => x.MinistryServiceAreaID == oldObject.Service_Area_Id);

                if (serviceArea == null)
                {
                    throw new ArgumentException(
                              string.Format("Cannot find Service Area (Service Area Id: {0} | Equipment Type Id: {1})",
                                            oldObject.Service_Area_Id, oldObject.Equip_Type_Id));
                }

                int districtId = serviceArea.District.Id;
                equipType.DistrictId = districtId;

                // save district equipment type record
                equipType.AppCreateUserid        = systemId;
                equipType.AppCreateTimestamp     = DateTime.UtcNow;
                equipType.AppLastUpdateUserid    = systemId;
                equipType.AppLastUpdateTimestamp = DateTime.UtcNow;

                dbContext.DistrictEquipmentTypes.Add(equipType);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - (Old) Equipment Code: " + oldObject.Equip_Type_Cd);
                Debug.WriteLine("***Error*** - Master District Equipment Index: " + maxEquipTypeIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
示例#15
0
        /// <summary>
        /// Copy xml item to instance (table entries)
        /// Output is ServiceArea name
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="instance"></param>
        /// <param name="systemId"></param>
        /// <param name="equipRentalRateNo"></param>
        /// <returns></returns>
        private static string CopyToInstance(DbAppContext dbContext, EquipType oldObject, ref DistrictEquipmentType instance, string systemId, float equipRentalRateNo)
        {
            string serviceAreaName = "";

            if (oldObject.Equip_Type_Id <= 0)
            {
                return(serviceAreaName);
            }

            // add the user specified in oldObject.Modified_By and oldObject.Created_By if not there in the database
            User createdBy = ImportUtility.AddUserFromString(dbContext, oldObject.Created_By, systemId);

            if (instance == null)
            {
                instance = new DistrictEquipmentType {
                    Id = oldObject.Equip_Type_Id
                };

                string typeCode = "";

                try
                {
                    typeCode = oldObject.Equip_Type_Cd.Length >= 20 ? oldObject.Equip_Type_Cd.Substring(0, 20) : oldObject.Equip_Type_Cd;
                }
                catch
                {
                    // do nothing
                }

                ServiceArea serviceArea = dbContext.ServiceAreas.FirstOrDefault(x => x.MinistryServiceAreaID == oldObject.Service_Area_Id);

                if (serviceArea != null)
                {
                    serviceAreaName = serviceArea.Name;
                    instance.DistrictEquipmentName = typeCode;

                    int      districtId = serviceArea.DistrictId ?? 0;
                    District dis        = dbContext.Districts.FirstOrDefault(x => x.RegionId == districtId);

                    if (dis != null)
                    {
                        instance.DistrictId = districtId;
                        instance.District   = dis;
                    }
                    else
                    {
                        // the District Id is not in the database
                        // (happens when the production data does not include district Other than "Lower Mainland" or all the districts)
                        return("ERROR");
                    }
                }

                instance.CreateTimestamp = DateTime.UtcNow;
                instance.CreateUserid    = createdBy.SmUserId;

                if (oldObject.Equip_Type_Cd != null)
                {
                    EquipmentType eType = dbContext.EquipmentTypes.FirstOrDefault(x => (Math.Abs((x.BlueBookSection ?? 0.1) - equipRentalRateNo)) <= ErrowAllowed);

                    if (eType == null)
                    {
                        eType = dbContext.EquipmentTypes.FirstOrDefault(x => (Math.Abs((x.BlueBookSection ?? 0.1) - DefaultBlueBoxSection)) <= ErrowAllowed);
                    }

                    if (eType != null)
                    {
                        instance.EquipmentTypeId = eType.Id;
                    }
                }
            }

            return(serviceAreaName);
        }
示例#16
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="user"></param>
        /// <param name="systemId"></param>
        private static void CopyToInstance(DbAppContext dbContext, UserHets oldObject, ref User user, string systemId)
        {
            string smUserId;
            int    serviceAreaId;

            int startPos = oldObject.User_Cd.IndexOf(@"\", StringComparison.Ordinal) + 1;

            try
            {
                serviceAreaId = oldObject.Service_Area_Id;
                smUserId      = oldObject.User_Cd.Substring(startPos).Trim();
            }
            catch
            {
                return;
            }

            // add the user specified in oldObject.Modified_By and oldObject.Created_By if not there in the database
            User modifiedBy = ImportUtility.AddUserFromString(dbContext, oldObject.Modified_By, systemId);
            User createdBy  = ImportUtility.AddUserFromString(dbContext, oldObject.Created_By, systemId);

            if (createdBy.SmUserId == smUserId)
            {
                user = createdBy;
                return;
            }

            if (modifiedBy.SmUserId == smUserId)
            {
                user = modifiedBy;
                return;
            }

            UserRole userRole = new UserRole();

            string authority;

            try
            {
                authority = oldObject.Authority.Trim();
            }
            catch
            {
                // regular User
                authority = "";
            }


            int roleId = ImportUtility.GetRoleIdFromAuthority(authority);

            User user1 = dbContext.Users.FirstOrDefault(x => x.SmUserId == smUserId);

            ServiceArea serArea = dbContext.ServiceAreas
                                  .Include(x => x.District)
                                  .FirstOrDefault(x => x.MinistryServiceAreaID == serviceAreaId);

            if (user1 == null)
            {
                if (user == null)
                {
                    user = new User();
                }

                try
                {
                    user.SmUserId = smUserId;

                    if (serArea != null)
                    {
                        user.District   = serArea.District;
                        user.DistrictId = serArea.DistrictId;
                    }
                }
                catch
                {
                    // do nothing
                }

                user.CreateTimestamp = DateTime.UtcNow;
                user.CreateUserid    = createdBy.SmUserId;

                //a dd user Role - Role Id is limited to 1, or 2
                if (roleId > 2)
                {
                    roleId = 1;
                }

                userRole.Role            = dbContext.Roles.First(x => x.Id == roleId);
                userRole.CreateTimestamp = DateTime.UtcNow;
                userRole.ExpiryDate      = DateTime.UtcNow.AddMonths(12);
                userRole.CreateUserid    = createdBy.SmUserId;
                userRole.EffectiveDate   = DateTime.UtcNow.AddDays(-1);

                user.UserRoles = new List <UserRole> {
                    userRole
                };
                dbContext.Users.Add(user);
            }
            else
            {
                user = dbContext.Users
                       .Include(x => x.UserRoles)
                       .Include(x => x.GroupMemberships)
                       .First(x => x.SmUserId == smUserId);

                // if the user does not have the user role, add the user role
                if (user.UserRoles == null)
                {
                    user.UserRoles = new List <UserRole>();
                }

                // if the role does not exist for the user, add the user role for the user
                if (user.UserRoles.FirstOrDefault(x => x.RoleId == roleId) == null)
                {
                    userRole.Role            = dbContext.Roles.First(x => x.Id == roleId);
                    userRole.CreateTimestamp = DateTime.UtcNow;
                    userRole.ExpiryDate      = DateTime.UtcNow.AddMonths(12);
                    userRole.CreateUserid    = createdBy.SmUserId;
                    userRole.EffectiveDate   = DateTime.UtcNow.AddDays(-1);
                    user.UserRoles.Add(userRole);
                }

                user.LastUpdateUserid = createdBy.SmUserId;
                user.CreateTimestamp  = DateTime.UtcNow;
                user.Active           = true;
                dbContext.Users.Update(user);
            }
        }