public DbOperationResult<IssueTypeSubType> AddIssueTypeSubType(IssueType issueType, IssueSubType issueSubType)
        {
            var result = new DbOperationResult<IssueTypeSubType>();

            //guard against duplicate.
            using (var cee = new CmsEntities())
            {
                int k = (from x in cee.IssueTypeSubTypes where x.IssueTypeId == issueType.Id && x.IssueSubTypeId == issueSubType.Id select x.Id).Count();

                if (k > 0)
                {
                    result.ServerErrorMessages.Add(string.Format("Insert Failed. An IssueTypeSubType with the combination IssueType Name: '{0}' and Issue SubType Name: '{1}' already exists.", issueType.Name, issueSubType.Name));
                    return result;
                }

                var typeSubType = new IssueTypeSubType
                {
                    IssueSubTypeId = issueSubType.Id,
                    IssueTypeId = issueType.Id,
                    Ordinal = 0
                };

                cee.IssueTypeSubTypes.Add(typeSubType);
                cee.SaveChanges();
                result.EntityResult = typeSubType;
            }

            return result;
        }
        public DbOperationResult DeleteRole(int roleId)
        {
            using (CmsEntities cee = new CmsEntities())
            {
                Role role = (from x in cee.Roles where x.Id == roleId select x).FirstOrDefault();

                if (role == null)
                {
                    DbOperationResult result = new DbOperationResult();

                    result.ServerErrorMessages.Add(string.Format("Cannot find the Role to delete with Id = {0}", role.Id));
                    return result;
                }

                cee.Roles.Remove(role);
                try
                {
                    cee.SaveChanges();
                }
                catch (Exception ex)
                {
                    log.Error("", ex, ex.ToString());
                    DbOperationResult result = new DbOperationResult();

                    result.ServerErrorMessages.Add(ex.Message);
                    return result;
                }
            }

            return new DbOperationResult();
        }
        public DbOperationResult DeletePromptGroup(int promptGroupId)
        {
            var result = new DbOperationResult();

            try
            {
                using (var cee = new CmsEntities())
                {
                    PromptGroup deleteCandidate = (from x in cee.PromptGroups where x.Id == promptGroupId select x).FirstOrDefault();

                    if (deleteCandidate != null)
                    {
                        //Check if it not used in Promps
                        Prompt promptInUse = (from x in cee.Prompts where x.PromptGroupId == promptGroupId select x).FirstOrDefault();

                        if (promptInUse != null)
                        {
                            result.ServerErrorMessages.Add(string.Format("Promp Group is assigned to '{0}' prompt.", promptInUse.Name));
                        }
                        else
                        {
                            cee.PromptGroups.Remove(deleteCandidate);
                            cee.SaveChanges();
                        }
                        return result;
                    }

                    result.ServerErrorMessages.Add(string.Format("coult not get EmailNotificationRule by Id '{0}'.  Delete Failed.", promptGroupId));
                    return result;
                }
            }
            catch (Exception ex)
            {
                return BuildOperationalErrorResults(ex);
            }
        }
Beispiel #4
0
        public DbOperationResult DeletePipeProperty(int pipePipePropertyId)
        {
            DbOperationResult result = new DbOperationResult();
            try
            {
                using (CmsEntities cee = new CmsEntities())
                {
                    cee.Configuration.LazyLoadingEnabled = true;
                    var componentTypeProperties = (from x in cee.PipeComponentTypeProperties
                                                   where x.PipePropertyId == pipePipePropertyId
                                                   select x).ToList();

                    if (componentTypeProperties.Any())
                    {

                        result.ServerErrorMessages.Add(String.Format("Can't delete Property '{0}' as it is assigned to {1} Pipe Component Types.",
                                                                     componentTypeProperties[0].PipeProperty.Name,
                                                                     componentTypeProperties.Count));
                    }
                    else
                    {
                        var pipeProperty = (from x in cee.PipeProperties where x.Id == pipePipePropertyId select x).FirstOrDefault();
                        cee.PipeProperties.Remove(pipeProperty);
                    }
                    cee.SaveChanges();
                }
            }

            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());
                result.ServerErrorMessages.Add(string.Format("Could not delete Mechanical Property.{0}{1}", Environment.NewLine, ex.Message));
            }

            return result;
        }
Beispiel #5
0
        public DbOperationResult<PipeComponentType> AddEditPipeComponentType(PipeComponentType pipeComponentType)
        {
            DbOperationResult<PipeComponentType> result = new DbOperationResult<PipeComponentType>();

            try
            {

                if (!pipeComponentType.InheritArea && pipeComponentType.Area == null)
                {
                    throw new Exception("Area has not been set and InheritArea is false.");
                }

                PipeComponentType newPct = new PipeComponentType();

                using (CmsEntities cee = new CmsEntities())
                {
                    //Check if this component type already exist
                    PipeComponentType pct = (from x in cee.PipeComponentTypes
                                             where x.Id == pipeComponentType.Id
                                             select x).FirstOrDefault();

                    if (pct != null)
                    {

                        //Edit the Component Type
                        pct.Name = pipeComponentType.Name;
                        pct.Description = pipeComponentType.Description;
                        pct.Code = pipeComponentType.Code;
                        pct.Ordinal = pipeComponentType.Ordinal;

                        pct.InheritArea = pipeComponentType.InheritArea;
                        pct.DefaultAreadId = pipeComponentType.DefaultAreadId;
                        cee.SaveChanges();
                    }
                    else
                    {
                        //Add new Component Type
                        pct = new PipeComponentType
                        {
                            Name = pipeComponentType.Name,
                            Description = pipeComponentType.Description,
                            Code = pipeComponentType.Code,
                            Ordinal = pipeComponentType.Ordinal,
                            InheritArea = pipeComponentType.InheritArea
                        };

                        if (pipeComponentType.Area != null)
                        {
                            pct.DefaultAreadId = pipeComponentType.Area.Id;
                        }

                        cee.PipeComponentTypes.Add(pct);
                        cee.SaveChanges();
                    }

                    newPct.Id = pct.Id;
                    newPct.Name = pct.Name;
                    newPct.Description = pct.Description;
                    newPct.Ordinal = pct.Ordinal;
                    newPct.DefaultAreadId = pct.DefaultAreadId;
                    newPct.InheritArea = pct.InheritArea;

                    result.EntityResult = newPct;
                    return result;

                }
            }
            catch (Exception ex)
            {
                return BuildOperationalErrorResults<PipeComponentType>(ex);
            }
        }
        /// <summary>
        ///     Save role with Privileges
        /// </summary>
        /// <param name="loggedInUserId"></param>
        /// <param name="role">The role.</param>
        /// <returns></returns>
        public DbOperationResult<Role> SaveRolePrivileges(int loggedInUserId, Role role)
        {
            DbOperationResult<Role> result = new DbOperationResult<Role>();

            using (CmsEntities cee = new CmsEntities())
            {
                var loggedInUserName = (from x in cee.Users where x.Id == loggedInUserId select x.FirstName + " " + x.LastName).FirstOrDefault();

                //delete all current privileges and categories for the role

                cee.DeleteWhere<RolePrivilege>(cee, x => x.RoleId == role.Id);
                cee.DeleteWhere<RoleApprovalCategory>(cee, x => x.RoleId == role.Id);

                //Update role
                //Check if the Role exists
                var originalRole = (from x in cee.Roles where x.Id == role.Id select x).FirstOrDefault();

                if (originalRole == null)
                {
                    //Add new Role
                    role.RolePrivileges = null;
                    role.LastModified = String.Format("Last modified {0} by {1}", DateTime.Now, loggedInUserName);
                    originalRole = cee.Roles.Add(role);
                }
                else
                {
                    //Update Role
                    originalRole.Name = role.Name;
                    originalRole.Description = role.Description;
                    originalRole.IsKeyStakeholder = role.IsKeyStakeholder;
                    originalRole.LastModified = String.Format("Last modified {0} by {1}", DateTime.Now, loggedInUserName);
                }

                cee.SaveChanges();

                //Assignt RoleApprovalCategories

                var k = (from x in role.RoleApprovalCategories where x.IsDefault select x).Count();

                if (k > 1)
                {
                    result.ServerErrorMessages.Add("Only one role per category should be the default.");
                    return result;
                }

                foreach (var roleApprovalCategory in role.RoleApprovalCategories)
                {
                    originalRole.RoleApprovalCategories.Add(new RoleApprovalCategory
                    {
                        RoleId = originalRole.Id,
                        IssueCategoryId = roleApprovalCategory.IssueCategoryId,
                        IsDefault = roleApprovalCategory.IsDefault
                    });
                }

                //Assign privileges
                foreach (var rolePrivilege in role.RolePrivileges)
                {
                    originalRole.RolePrivileges.Add(rolePrivilege);
                }

                cee.SaveChanges();

                //saves the IsKeyStakeholder and othe name,desc properties
                role = SaveRole(role);

                role = (from x in cee.Roles
                                     .Include("RolePrivileges")
                                     .Include("RolePrivileges.SecurityObject")
                                     .Include("RolePrivileges.Privilege")
                        where x.Id == role.Id
                        select x).FirstOrDefault();

                result.EntityResult = role;

                return result;
            }
        }
        public DbOperationResult DeleteInstrumentProperty(int instrumentPropertyId)
        {
            DbOperationResult result = new DbOperationResult();
            try
            {
                using (CmsEntities cee = new CmsEntities())
                {
                    cee.Configuration.LazyLoadingEnabled = true;
                    var instrumentProperty = (from x in cee.InstrumentProperties
                                              where x.Id == instrumentPropertyId
                                              select x).FirstOrDefault();

                    if (instrumentProperty != null)
                    {
                        List<InstrumentPropertyValue> propertyValues = (from x in cee.InstrumentPropertyValues
                                                                        where x.InstrumentPropertyId == instrumentProperty.Id
                                                                        select x).ToList();
                        if (propertyValues.Count > 0)
                        {
                            result.ServerErrorMessages.Add(String.Format("Can't delete the property named '{0}' because it is currently being used by {1} Component(s).",
                                                                         instrumentProperty.Name, propertyValues.Count));
                        }
                        else
                        {
                            cee.InstrumentProperties.Remove(instrumentProperty);
                            cee.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());
                result.ServerErrorMessages.Add(string.Format("Could not remove Instrument Component Property.{0}{1}", Environment.NewLine, ex.Message));
            }

            return result;
        }
        public DbOperationResult SaveInstrumentComponents(List<InstrumentComponent> instrumentComponents, int userId)
        {
            DbOperationResult result = new DbOperationResult();

            using (CmsEntities cee = new CmsEntities())
            {
                try
                {
                    foreach (var instrumentComponent in instrumentComponents)
                    {
                        var q = (from x in cee.InstrumentComponents
                                 where x.Id == instrumentComponent.Id
                                 select x).FirstOrDefault();

                        if (q != null)
                        {

                            if (q.LastInspectedDate != instrumentComponent.LastInspectedDate)
                            {
                                InstrumentRevisionHistory rv = new InstrumentRevisionHistory
                                {
                                    InstrumentId = instrumentComponent.InstrumentId,
                                    Date = DateTime.Now,
                                    UserId = userId,
                                    Description = string.Format("Component '{0}': Last Inspected Date changed from '{1}' to '{2}'.", instrumentComponent.Name, q.LastInspectedDate, instrumentComponent.LastInspectedDate),
                                    IsSystemMessage = true
                                };
                                AddInstrumentRevisionHistoryInternal(rv, cee);
                            }

                            //Update Instrument Componet
                            cee.Entry(q).CurrentValues.SetValues(instrumentComponent);
                        }
                        else
                        {
                            q = new InstrumentComponent();
                            q.InstrumentId = instrumentComponent.InstrumentId;
                            q.InstrumentComponentTypeId = instrumentComponent.InstrumentComponentTypeId;
                            q.Name = instrumentComponent.Name;
                            q.Ordinal = instrumentComponent.Ordinal;
                            q.NextInspectionDate = instrumentComponent.NextInspectionDate;
                            q.LastInspectedById = instrumentComponent.LastInspectedById;
                            q.LastInspectedDate = instrumentComponent.LastInspectedDate;
                            q.LastModifiedById = instrumentComponent.LastModifiedById;
                            q.LastModifiedDate = instrumentComponent.LastModifiedDate;
                            q.Description = instrumentComponent.Description;
                            q.ManufacturerId = instrumentComponent.ManufacturerId;
                            q.ModelId = instrumentComponent.ModelId;

                            //Add new Instrument Component
                            cee.InstrumentComponents.Add(q);
                        }

                        foreach (var instrumentComponentPropertyValue in instrumentComponent.InstrumentPropertyValues)
                        {
                            var qq = (from x in cee.InstrumentPropertyValues
                                      where x.Id == instrumentComponentPropertyValue.Id
                                      select x).FirstOrDefault();

                            if (qq != null)
                            {
                                cee.Entry(qq).CurrentValues.SetValues(instrumentComponentPropertyValue);
                            }
                            else
                            {
                                cee.InstrumentPropertyValues.Add(instrumentComponentPropertyValue);
                            }
                        }
                        cee.SaveChanges();
                    }
                }
                catch (Exception ex)
                {

                    result.ServerErrorMessages.Add(String.Format("Error moving components: {0}", ex.Message));
                }
            }
            return result;
        }
        private DbOperationResult<IssueSubType> UpdateIssueSubType(IssueSubType issueSubType)
        {
            var result = new DbOperationResult<IssueSubType>();
            using (var cee = new CmsEntities())
            {
                int k = (from x in cee.IssueSubTypes
                         where x.Name.Equals(issueSubType.Name, StringComparison.CurrentCultureIgnoreCase)
                               && x.Id != issueSubType.Id
                         select x.Id).Count();

                if (k > 0)
                {
                    result.ServerErrorMessages.Add(string.Format("Save Failed.  An IssueSubType with the Name '{0}' already exists.", issueSubType.Name));
                }

                IssueSubType dbMatch = (from x in cee.IssueSubTypes where x.Id == issueSubType.Id select x).FirstOrDefault();

                if (dbMatch == null)
                {
                    result.ServerErrorMessages.Add(string.Format("Save Failed.  ssueSubType with the Id '{0}' does not exist.", issueSubType.Id));
                    return result;
                }

                dbMatch.Name = issueSubType.Name;
                dbMatch.Description = issueSubType.Description;
                dbMatch.Code = issueSubType.Code;
                dbMatch.Ordinal = issueSubType.Ordinal;

                cee.SaveChanges();
                result.EntityResult = dbMatch;
            }
            return result;
        }
Beispiel #10
0
        public DbOperationResult DeleteVendor(int vendorId)
        {
            var result = new DbOperationResult();

            try
            {
                using (var cee = new CmsEntities())
                {
                    Vendor deleteCandidate = (from x in cee.Vendors where x.Id == vendorId select x).FirstOrDefault();

                    if (deleteCandidate != null)
                    {
                        cee.Vendors.Remove(deleteCandidate);

                        cee.SaveChanges();
                        return result;
                    }

                    result.ServerErrorMessages.Add(string.Format("coult not get Vendor by Id '{0}'.  Delete Failed.", vendorId));
                    return result;
                }
            }
            catch (Exception ex)
            {
                return BuildOperationalErrorResults(ex);
            }
        }
Beispiel #11
0
        public DbOperationResult DeleteTypeClassification(int typeClassificationId)
        {
            var ds = new DbOperationResult();

            try
            {
                using (var cee = new CmsEntities())
                {
                    IssueTypeClassification typeClassification = (from x in cee.IssueTypeClassifications
                                                                  where x.Id == typeClassificationId
                                                                  select x).FirstOrDefault();

                    if (typeClassification != null)
                    {
                        cee.IssueTypeClassifications.Remove(typeClassification);
                    }
                    cee.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ds.ServerErrorMessages.Add(String.Format("Error occured: {0}", ex.Message));
                log.Error("", ex, "Error occured while trying to delete IssueTypeClassification Id '{0}'", typeClassificationId);
            }
            return ds;
        }
Beispiel #12
0
        public DbOperationResult DeletetMilestoneType(int milestoneTypeId)
        {
            var result = new DbOperationResult();

            try
            {
                using (var cee = new CmsEntities())
                {
                    IssueMilestoneType dbMatch = (from x in cee.IssueMilestoneTypes where x.Id == milestoneTypeId select x).FirstOrDefault();

                    if (dbMatch == null)
                    {
                        //can't find it
                        result.ServerErrorMessages.Add(string.Format("Cannot find MilestoneType in the database using Id '{0}'. Delete Failed.", milestoneTypeId));
                        return result;
                    }

                    List<IssueTypeMilestoneType> dbTypesInUse = (from x in cee.IssueTypeMilestoneTypes.Include("IssueType") where x.MilestoneTypeId == milestoneTypeId select x).ToList();

                    if (dbTypesInUse.Any())
                    {
                        //in use
                        List<string> names = dbTypesInUse.Select(typeSubType => typeSubType.IssueType.Name).ToList();

                        string joined = string.Join(", ", names);

                        result.ServerErrorMessages.Add(string.Format("The MilestoneType '{0}' cannot be deleted as it is in use by the following IssueTypes: '{1}'", dbMatch.Name, joined));
                        return result;
                    }

                    //delete
                    cee.IssueMilestoneTypes.Remove(dbMatch);
                    cee.SaveChanges();

                    return result;
                }
            }
            catch (Exception ex)
            {
                return BuildOperationalErrorResults(ex);
            }
        }
Beispiel #13
0
        public DbOperationResult DeletetIssueTypeSubType(int issueTypeId, int issueSubTypeId)
        {
            var result = new DbOperationResult();

            try
            {
                using (var cee = new CmsEntities())
                {
                    IssueTypeSubType dbMatch = (from x in cee.IssueTypeSubTypes where x.IssueTypeId == issueTypeId && x.IssueSubTypeId == issueSubTypeId select x).FirstOrDefault();

                    if (dbMatch == null)
                    {
                        //can't find it
                        result.ServerErrorMessages.Add(string.Format("Cannot find IssueTypeSubType in the database using IssueTypeId '{0}' and IssueSubTypeId '{1}'. Delete Failed.", issueTypeId, issueSubTypeId));
                        return result;
                    }

                    cee.IssueTypeSubTypes.Remove(dbMatch);
                    cee.SaveChanges();

                    return result;
                }
            }

            catch (Exception ex)
            {
                return BuildOperationalErrorResults(ex);
            }
        }
Beispiel #14
0
        private DbOperationResult<IssueMilestoneType> InsertMilestoneType(IssueMilestoneType milestoneType)
        {
            var result = new DbOperationResult<IssueMilestoneType>();

            //guard against duplicate.
            using (var cee = new CmsEntities())
            {
                int k = (from x in cee.IssueMilestoneTypes where x.Name.Equals(milestoneType.Name, StringComparison.CurrentCultureIgnoreCase) select x.Id).Count();

                if (k > 0)
                {
                    result.ServerErrorMessages.Add(string.Format("Insert Failed.  A MilestoneType with the Name '{0}' already exists.", milestoneType.Name));
                }

                cee.IssueMilestoneTypes.Add(milestoneType);
                cee.SaveChanges();
                result.EntityResult = milestoneType;
            }

            return result;
        }
        public DbOperationResult<ElectricalEquipmentProperty> SaveElectricalEquipmentProperty(ElectricalEquipmentProperty controlSystemProperty)
        {
            DbOperationResult<ElectricalEquipmentProperty> dbOperationResult = new DbOperationResult<ElectricalEquipmentProperty>();

            try
            {
                using (CmsEntities cee = new CmsEntities())
                {
                    ElectricalEquipmentProperty original = (from x in cee.ElectricalEquipmentProperties where x.Id == controlSystemProperty.Id select x).FirstOrDefault();

                    if (original == null)
                    {
                        cee.ElectricalEquipmentProperties.Add(controlSystemProperty);
                    }
                    else
                    {
                        cee.Entry(original).CurrentValues.SetValues(controlSystemProperty);
                    }

                    cee.SaveChanges();
                    dbOperationResult.EntityResult = controlSystemProperty;
                }

            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());
                dbOperationResult.ServerErrorMessages = BuildOperationalErrorResults(ex).ServerErrorMessages;
                return dbOperationResult;
            }
            return dbOperationResult;
        }
        public DbOperationResult<DocumentPurchaseOrder> SaveDocumentPurchaseOrder(DocumentPurchaseOrder documentPurchaseOrder)
        {
            DbOperationResult<DocumentPurchaseOrder> dbOperationResult = new DbOperationResult<DocumentPurchaseOrder>();
            try
            {
                using (CmsEntities cee = new CmsEntities())
                {
                    DocumentPurchaseOrder original = (from x in cee.DocumentPurchaseOrders where x.Id == documentPurchaseOrder.Id select x).FirstOrDefault();

                    if (original == null)
                    {
                        documentPurchaseOrder.IsActive = true;
                        cee.DocumentPurchaseOrders.Add(documentPurchaseOrder);
                        dbOperationResult.EntityResult = documentPurchaseOrder;
                    }
                    else
                    {
                        original.Name = documentPurchaseOrder.Name;
                        original.Description = documentPurchaseOrder.Description;
                        original.IsActive = documentPurchaseOrder.IsActive;
                        dbOperationResult.EntityResult = original;
                    }

                    cee.SaveChanges();
                }

                return dbOperationResult;
            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());
                dbOperationResult.ServerErrorMessages = BuildOperationalErrorResults(ex).ServerErrorMessages;
                return dbOperationResult;
            }
        }
        public DbOperationResult SaveElectricalEquipmentComponent(ElectricalEquipmentComponent electricalEquipmentComponent)
        {
            DbOperationResult result = new DbOperationResult();

            if (electricalEquipmentComponent == null)
            {
                result.ServerInformationMessages.Add("Save Completed");
                return result;
            }

            using (CmsEntities cee = new CmsEntities())
            {
                var match = (from x in cee.ElectricalEquipmentComponents where x.Id == electricalEquipmentComponent.Id select x).FirstOrDefault();

                if (match == null)
                {
                    //So component doesnt exist in the database so lets create it
                    electricalEquipmentComponent.ElectricalEquipment = null;
                    electricalEquipmentComponent.ElectricalEquipmentComponentType = null;
                    cee.ElectricalEquipmentComponents.Add(electricalEquipmentComponent);
                }
                else
                {
                    if (match.LastInspectedDate != electricalEquipmentComponent.LastInspectedDate)
                    {
                        ElectricalEquipmentRevisionHistory rv = new ElectricalEquipmentRevisionHistory();
                        rv.ElectricalEquipmentId = electricalEquipmentComponent.ElectricalEquipmentId;
                        rv.Date = DateTime.Now;
                        if (electricalEquipmentComponent.LastModifiedById.HasValue)
                        {
                            rv.UserId = electricalEquipmentComponent.LastModifiedById.Value;
                        }
                        rv.Description = string.Format("Last Inspected Date changed from '{0}' to '{1}'.", match.LastInspectedDate, electricalEquipmentComponent.LastInspectedDate);
                        rv.IsSystemMessage = true;
                        AddElectricalRevisionHistoryInternal(rv, cee);

                    }
                    //Compoent exist, change the ID of Equipment
                    match.ElectricalEquipmentId = electricalEquipmentComponent.ElectricalEquipmentId;
                }

                cee.SaveChanges();
                result.ServerInformationMessages.Add("Save Completed");
                return result;
            }
        }
        public DbOperationResult<DocumentVersion> SaveDocumentVersion(DocumentVersion documentVersion, int userId)
        {
            DbOperationResult<DocumentVersion> result = new DbOperationResult<DocumentVersion>();

            using (CmsEntities cee = new CmsEntities())
            {
                DocumentVersion originalObject = (from x in cee.DocumentVersions where x.Id == documentVersion.Id select x).FirstOrDefault();

                if (originalObject != null)
                {

                    cee.Entry(originalObject).CurrentValues.SetValues(documentVersion);

                    if (documentVersion.AutoIncrement)
                    {
                        IncrementVersionNumber(originalObject, cee, true);
                        originalObject.AutoIncrement = false; // keeping this false so next time the contro is loaded it is re-set to false by default. the property has done it's job already.
                    }

                    cee.SaveChanges();

                    result.EntityResult = (from x in cee.DocumentVersions.Include("User") where x.Id == documentVersion.Id select x).FirstOrDefault();
                }
            }

            return result;
        }
        public DbOperationResult<CalibrationComponentType> AddCalibrationComponentType(CalibrationComponentType calibrationComponentType)
        {
            DbOperationResult<CalibrationComponentType> result = new DbOperationResult<CalibrationComponentType>();

            try
            {
                CalibrationComponentType newCalibrationComponentType = new CalibrationComponentType();

                using (CmsEntities cee = new CmsEntities())
                {
                    //Check if this component type already exist
                    CalibrationComponentType originalCalibrationComponentType = (from x in cee.CalibrationComponentTypes
                                                                                 where x.Id == calibrationComponentType.Id
                                                                                 select x).FirstOrDefault();

                    if (originalCalibrationComponentType != null)
                    {

                        int nameCount = (from x in cee.CalibrationComponentTypes where x.Name.ToLower() == calibrationComponentType.Name.ToLower() && x.Id!= calibrationComponentType.Id select x.Id).Count();
                        if (nameCount > 0)
                        {
                            throw new Exception(string.Format("The Calibration Component Type with Name '{0}' already exists.", calibrationComponentType.Name));
                        }

                        int codeCount = (from x in cee.CalibrationComponentTypes where x.Code.ToLower() == calibrationComponentType.Code.ToLower() && x.Id!= calibrationComponentType.Id select x.Id).Count();
                        if (codeCount > 0)
                        {
                            throw new Exception(string.Format("The Calibration Component Type with Code '{0}' already exists.", calibrationComponentType.Code));
                        }

                        //Edit the Component Type
                        originalCalibrationComponentType.Name = calibrationComponentType.Name;
                        originalCalibrationComponentType.Description = calibrationComponentType.Description;
                        originalCalibrationComponentType.Ordinal = calibrationComponentType.Ordinal;
                        cee.SaveChanges();
                    }
                    else
                    {
                        int nameCount = (from x in cee.CalibrationComponentTypes where x.Name.ToLower() == calibrationComponentType.Name.ToLower() select x.Id).Count();
                        if (nameCount > 0)
                        {
                            throw new Exception(string.Format("The Calibration Component Type with Name '{0}' already exists.", calibrationComponentType.Name));
                        }

                        int codeCount = (from x in cee.CalibrationComponentTypes where x.Code.ToLower() == calibrationComponentType.Code.ToLower() select x.Id).Count();
                        if (codeCount > 0)
                        {
                            throw new Exception(string.Format("The Calibration Component Type with Code '{0}' already exists.", calibrationComponentType.Code));
                        }

                        //Add new Component Type
                        originalCalibrationComponentType = new CalibrationComponentType();
                        originalCalibrationComponentType.Name = calibrationComponentType.Name;
                        originalCalibrationComponentType.Description = calibrationComponentType.Description;
                        originalCalibrationComponentType.Code = calibrationComponentType.Name.Replace(" ", "");
                        originalCalibrationComponentType.Ordinal = calibrationComponentType.Ordinal;
                        originalCalibrationComponentType.IsActive = true;

                        cee.CalibrationComponentTypes.Add(originalCalibrationComponentType);
                        cee.SaveChanges();
                    }

                    newCalibrationComponentType.Id = originalCalibrationComponentType.Id;
                    newCalibrationComponentType.Name = originalCalibrationComponentType.Name;
                    newCalibrationComponentType.Description = originalCalibrationComponentType.Description;
                    newCalibrationComponentType.Ordinal = originalCalibrationComponentType.Ordinal;

                    result.EntityResult = newCalibrationComponentType;
                    return result;
                }
            }
            catch (Exception ex)
            {
                result = BuildOperationalErrorResults<CalibrationComponentType>(ex);
                return result;
            }
        }
        public DbOperationResult<QuickDocument> UnDeleteDocument(int documentId)
        {
            DbOperationResult<QuickDocument> result = new DbOperationResult<QuickDocument>();

            try
            {
                using (CmsEntities cee = new CmsEntities())
                {
                    Document dbDocument = (from x in cee.Documents where x.Id == documentId select x).FirstOrDefault();

                    if (dbDocument != null)
                    {
                        dbDocument.IsActive = true;
                        cee.SaveChanges();

                        var doc = (from x in cee.Documents
                                   orderby x.Name
                                   where x.Id == dbDocument.Id
                                   select new QuickDocument
                                       {
                                           Id = x.Id,
                                           Name = x.Name,
                                           Description = x.Description,
                                           IsActive = x.IsActive
                                       }).FirstOrDefault();
                        result.EntityResult = doc;
                    }
                    else
                    {
                        throw new Exception(string.Format("Document not found using Id '{0}'.", documentId));
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());
                result.ServerErrorMessages.Add(ex.Message);
                return result;
            }

            return result;
        }
        public DbOperationResult DeleteUser(int userId)
        {
            using (CmsEntities cee = new CmsEntities())
            {
                User user = (from x in cee.Users where x.Id == userId select x).FirstOrDefault();

                if (user == null)
                {
                    DbOperationResult result = new DbOperationResult();

                    result.ServerErrorMessages.Add(string.Format("Cannot find the User to delete with Id = {0}", user.Id));
                    return result;
                }

                cee.Users.Remove(user);
                try
                {
                    cee.SaveChanges();
                }
                catch (Exception ex)
                {
                    log.Error("", ex, ex.ToString());
                    if (ex.InnerException != null)
                    {
                        log.Error("", ex.InnerException, ex.InnerException.ToString());
                    }

                    DbOperationResult result = BuildOperationalErrorResults(ex);
                    result.ServerErrorMessages.Add(ex.Message);
                    return result;
                }
            }

            return new DbOperationResult();
        }
        public DbOperationResult DeleteAttachmentType(int attachmentTypeId)
        {
            DbOperationResult dbo = new DbOperationResult();
            try
            {
                using (CmsEntities cee = new CmsEntities())
                {
                    AttachmentType attachmentType = (from x in cee.AttachmentTypes where x.Id == attachmentTypeId select x).FirstOrDefault();

                    if (attachmentType != null)
                    {
                        cee.AttachmentTypes.Remove(attachmentType);
                        cee.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());
                dbo.ServerErrorMessages.Add(String.Format("Error occured while deleting attachement type: {0}", ex.Message));
            }

            return dbo;
        }
        ///// <summary>
        /////   Return list of Users
        ///// </summary>
        ///// <returns></returns>
        //public List<User> GetUsers(CmsEntities cee)
        //{
        //    var users = (from x in cee.Users orderby x.UserName select x).ToList();
        //    return users;
        //}
        /// <summary>
        ///     Save/Update User
        /// </summary>
        /// <param name="loggedInUserId"></param>
        /// <param name="user">The user.</param>
        /// <returns></returns>
        public DbOperationResult<User> SaveUser(int loggedInUserId, User user)
        {
            try
            {
                DbOperationResult<User> result = new DbOperationResult<User>();

                using (CmsEntities cee = new CmsEntities())
                {
                    var loggedInUserName = (from x in cee.Users where x.Id == loggedInUserId select x.FirstName + " " + x.LastName).FirstOrDefault();

                    //Check if the user exist
                    var originalUser = (from x in cee.Users.Include("Role").Include("UserPreference") where x.Id == user.Id select x).FirstOrDefault();

                    if (originalUser == null)
                    {
                        //Add new User
                        user.Role = null;
                        user.LastModified = String.Format("Last modified {0} by {1}", DateTime.Now, loggedInUserName);
                        cee.Users.Add(user);

                        cee.SaveChanges();
                        result.EntityResult = user;
                    }
                    else
                    {
                        //Update existing
                        originalUser.ActiveUser = user.ActiveUser;
                        originalUser.UserName = user.UserName;
                        originalUser.FirstName = user.FirstName;
                        originalUser.LastName = user.LastName;
                        originalUser.Password = user.Password;
                        originalUser.RoleId = user.Role.Id;
                        originalUser.Department = user.Department;

                        originalUser.JobTitle = user.JobTitle;
                        originalUser.BusinessPhone = user.BusinessPhone;
                        originalUser.MobilePhone = user.MobilePhone;
                        originalUser.EmailAddress = user.EmailAddress;

                        originalUser.LastModified = String.Format("Last modified {0} by {1}", DateTime.Now, loggedInUserName);

                        if (originalUser.UserPreference == null)
                        {
                            originalUser.UserPreference = new UserPreference();
                        }

                        originalUser.UserPreference.SummaryTabsExpanded = user.UserPreference.SummaryTabsExpanded;
                        originalUser.UserPreference.RevisionHistoryExpanded = user.UserPreference.RevisionHistoryExpanded;
                        originalUser.UserPreference.ShowDocumentPreview = user.UserPreference.ShowDocumentPreview;
                        originalUser.UserPreference.LoadDefaultSearchFilterAtStart = user.UserPreference.LoadDefaultSearchFilterAtStart;
                        originalUser.UserPreference.IgnoreCCEmail = user.UserPreference.IgnoreCCEmail;
                        originalUser.UserPreference.OpenMyIntrayFromEmailLinks = user.UserPreference.OpenMyIntrayFromEmailLinks;
                        originalUser.UserPreference.IncludeOnHoldRejectedInMyInTray = user.UserPreference.IncludeOnHoldRejectedInMyInTray;
                        originalUser.UserPreference.MyFavouriteNotifcationEmailOn = user.UserPreference.MyFavouriteNotifcationEmailOn;

                        originalUser.UserPreference.IssuePanelWidth = user.UserPreference.IssuePanelWidth;
                        originalUser.UserPreference.ControlPanelWidth = user.UserPreference.ControlPanelWidth;
                        originalUser.UserPreference.ElectricalPanelWidth = user.UserPreference.ElectricalPanelWidth;
                        originalUser.UserPreference.InstrumentPanelWidth = user.UserPreference.InstrumentPanelWidth;
                        originalUser.UserPreference.MechanicalPanelWidth = user.UserPreference.MechanicalPanelWidth;
                        originalUser.UserPreference.MobilePanelWidth = user.UserPreference.MobilePanelWidth;
                        originalUser.UserPreference.PipePanelWidth = user.UserPreference.PipePanelWidth;
                        originalUser.UserPreference.DocumentPanelWidth = user.UserPreference.DocumentPanelWidth;
                        originalUser.UserPreference.AdminPanelWidth = user.UserPreference.AdminPanelWidth;

                        cee.SaveChanges();
                        result.EntityResult = originalUser;
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());

                return BuildOperationalErrorResults<User>(ex);
            }
        }
        public DbOperationResult DeleteDocument(int documentId, int userId)
        {
            DbOperationResult dbOperationResult = new DbOperationResult();

            try
            {
                using (CmsEntities cee = new CmsEntities())
                {
                    Document dbDocument = (from x in cee.Documents where x.Id == documentId select x).FirstOrDefault();
                    dbDocument.IsActive = false;

                    BuildRevisonHistoryForMadeInactive(dbDocument, cee, userId);

                    cee.SaveChanges();

                    return dbOperationResult;
                }
            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());

                dbOperationResult.ServerErrorMessages.Add(ex.Message);
                if (ex.InnerException != null)
                {
                    dbOperationResult.ServerErrorMessages.Add(ex.InnerException.Message);
                }
                return dbOperationResult;
            }
        }
Beispiel #25
0
        public DbOperationResult MovePipeComponent(PipeComponent pipeComponent)
        {
            DbOperationResult result = new DbOperationResult();

            if (pipeComponent == null)
            {
                result.ServerInformationMessages.Add("Save Completed");
                return result;
            }

            using (CmsEntities cee = new CmsEntities())
            {
                var match = (from x in cee.PipeComponents where x.Id == pipeComponent.Id select x).FirstOrDefault();

                if (match == null)
                {
                    //So component doesnt exist in the database so lets create it
                    pipeComponent.Pipe = null;
                    pipeComponent.PipeComponentType = null;
                    cee.PipeComponents.Add(pipeComponent);
                }
                else
                {
                    //Compoent exist, change the ID of Equipment
                    match.PipeId = pipeComponent.PipeId;
                }

                cee.SaveChanges();
                result.ServerInformationMessages.Add("Save Completed");
                return result;
            }
        }
        public DbOperationResult<DocumentVersion> DeleteDocumentVersion(DocumentVersion documentVersion, int userId)
        {
            DbOperationResult<DocumentVersion> dbOperationResult = new DbOperationResult<DocumentVersion>();

            try
            {
                using (CmsEntities cee = new CmsEntities())
                {
                    DocumentVersion toBeDeleted = (from x in cee.DocumentVersions
                                                   where x.Id == documentVersion.Id &&
                                                         x.Path.ToLower() == documentVersion.Path.ToLower()
                                                   select x).FirstOrDefault();

                    if (toBeDeleted == null)
                    {
                        dbOperationResult.ServerWarningMessages.Add("That File Version did not 'physically' exist. The database record will be cleaned up when Saved.");
                    }
                    else
                    {
                        //First try to delete the file from HDD

                        string settingValue = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.UploadedDocumentsPathRoot);
                        string folderPath = String.Format(@"{0}\{1}", settingValue, toBeDeleted.Path);

                        if (!Directory.Exists(folderPath))
                        {
                            dbOperationResult.ServerWarningMessages.Add("Folder Path does not exist.");
                        }
                        else
                        {
                            string[] files = Directory.GetFiles(folderPath);

                            if (files.Length == 0)
                            {
                                string message = string.Format("No Files exists in Folder Path {0}", folderPath);

                                log.Warning("", message);
                                dbOperationResult.ServerWarningMessages.Add(message);
                            }

                            foreach (var file in Directory.GetFiles(folderPath))
                            {
                                File.Delete(file);
                            }

                            Directory.Delete(folderPath, true);
                        }

                        BuildRevisonHistoryForDeletedDocumentVersion(documentVersion.DocumentId, cee, userId, toBeDeleted);

                        //Delete from database
                        cee.DocumentVersions.Remove(toBeDeleted);
                        cee.SaveChanges();
                        dbOperationResult.ServerInformationMessages.Add("File Version Deleted Sucessfully");
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());
                dbOperationResult.ServerErrorMessages = BuildOperationalErrorResults(ex).ServerErrorMessages;
                return dbOperationResult;
            }

            return dbOperationResult;
        }
Beispiel #27
0
        public DbOperationResult DeletePipeComponentType(int pipeComponentTypeId)
        {
            DbOperationResult ds = new DbOperationResult();

            try
            {
                using (CmsEntities cee = new CmsEntities())
                {
                    cee.Configuration.LazyLoadingEnabled = true;

                    var pipeComponentType = (from x in cee.PipeComponentTypes
                                             where x.Id == pipeComponentTypeId
                                             select x).FirstOrDefault();

                    if (pipeComponentType != null)
                    {
                        //Check  if the Pip Component Type has Property
                        if (pipeComponentType.PipeComponentTypeProperties.Any())
                        {
                            //this property is assigned - can't delete it

                            ds.ServerErrorMessages.Add(String.Format("Can't delete '{0}' component type as it has assigned '{1}' property.",
                                                                     pipeComponentType.Name, pipeComponentType.PipeComponentTypeProperties[0].PipeProperty.Name));
                        }

                        if (!ds.HasErrors)
                        {
                            //check if pipe component is assigned to a pipe
                            var pipe = (from x in cee.PipeComponents
                                        where x.PipeComponentTypeId == pipeComponentTypeId
                                        select x.Pipe).FirstOrDefault();

                            if (pipe != null)
                            {
                                ds.ServerErrorMessages.Add(String.Format("Can't delete '{0}' component type as it is assigned to '{1}' pipe.",
                                                                         pipeComponentType.Name, pipe.Name));
                            }
                            else
                            {
                                cee.PipeComponentTypes.Remove(pipeComponentType);
                            }
                        }
                    }
                    cee.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());
                ds.ServerErrorMessages.Add(string.Format("Could not remove Pipe Component Property Type.{0}{1}",
                                                         Environment.NewLine, ex.Message));
            }
            return ds;
        }
        public DbOperationResult<byte[]> GetDocumentVersionContent(DocumentVersion documentVersion)
        {
            DbOperationResult<byte[]> result = new DbOperationResult<byte[]>();

            if (documentVersion == null)
            {
                documentVersion = new DocumentVersion();
                documentVersion.Filename = "NO.VERSIONS.EXIST.pdf";
                documentVersion.Path = string.Empty;
            }

            string settingValue = GetAppSettingValue(CommonUtils.AppSettingKey.UploadedDocumentsPathRoot);

            if (string.IsNullOrEmpty(settingValue))
            {
                result.ServerErrorMessages.Add("Could not find app setting for UploadedDocumentsPathRoot");
                return result;
            }

            string fullFilePath = Path.Combine(settingValue, documentVersion.Path, documentVersion.Filename);

            if (!File.Exists(fullFilePath))
            {
                documentVersion = new DocumentVersion();
                documentVersion.Filename = "FILE.NOT.FOUND.pdf";
                documentVersion.Path = string.Empty;
                fullFilePath = Path.Combine(settingValue, documentVersion.Path, documentVersion.Filename);
            }

            byte[] fileContent = File.ReadAllBytes(fullFilePath);

            if (fileContent.Length == 0)
            {
                result.ServerErrorMessages.Add("file contents were empty. byte array is zero length.");
                return result;
            }

            result.ServerInformationMessages.Add(documentVersion.Filename);
            result.EntityResult = fileContent;
            return result;
        }
Beispiel #29
0
        public DbOperationResult DeletePipeSpecialFeature(int pipeSpecialFeatureId)
        {
            DbOperationResult ds = new DbOperationResult();

            using (CmsEntities cee = new CmsEntities())
            {
                cee.Configuration.LazyLoadingEnabled = true;

                var pipeSpecialFeature = (from x in cee.PipeSpecialFeatures
                                          where x.Id == pipeSpecialFeatureId
                                          select x).FirstOrDefault();

                if (pipeSpecialFeature != null)
                {
                    if (pipeSpecialFeature.Pipes.Count() > 0)
                    {
                        //this area is assigned - can't delete it
                        ds.ServerErrorMessages.Add(String.Format("Can't delete '{0}' Special Feature as it is assigned to '{1}' pipe.",
                                                                 pipeSpecialFeature.Name, pipeSpecialFeature.Pipes[0].Name));
                        return ds;
                    }
                    else
                    {
                        cee.PipeSpecialFeatures.Remove(pipeSpecialFeature);
                    }
                }

                cee.SaveChanges();
                return ds;
            }
        }
Beispiel #30
0
        public DbOperationResult DeletePromptCategory(int promptCategoryId)
        {
            var result = new DbOperationResult();

            try
            {
                using (var cee = new CmsEntities())
                {
                    PromptCategory deleteCandidate = (from x in cee.PromptCategories where x.Id == promptCategoryId select x).FirstOrDefault();

                    if (deleteCandidate != null)
                    {
                        cee.PromptCategories.Remove(deleteCandidate);
                        cee.SaveChanges();
                        return result;
                    }
                }

                result.ServerErrorMessages.Add(string.Format("coult not get EmailNotificationRule by Id '{0}'.  Delete Failed.", promptCategoryId));
                return result;
            }

            catch (Exception ex)
            {
                return BuildOperationalErrorResults(ex);
            }
        }