public MobilePlantPropertiesViewModel(MobilePlantComponent mobilePlantComponent)
        {
            mMobilePlantComponent = mobilePlantComponent;

            LastInspectedCommand = new DelegateCommand<object>(LastInspectedHandler, CanModify);
            NextInspectionCommand = new DelegateCommand<object>(NextInspectionHandler, CanModify);

            CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

            cmsWebServiceClient.GetManufacturersCompleted +=
                (s, e) =>
                {
                    mManufacturers = e.Result;
                    RaisePropertyChanged("Manufacturers");
                    RaisePropertyChanged("Manufacturer");

                    if (mMobilePlantComponent.ManufacturerId.HasValue)
                    {
                        LoadModels(mMobilePlantComponent.ManufacturerId.Value);
                    }
                    else if (Loaded != null)
                    {
                        Loaded();
                        Loaded = null;
                    }
                };
            cmsWebServiceClient.GetManufacturersAsync((int)CommonUtils.EquipmentTypeCode.MOB);
        }
 public AddEditMobilePlantComponentViewModel(MobilePlantComponent mc, IList<string> existingComponentNames)
 {
     ExistingComponentNames = existingComponentNames;
     EditingName = mc.Name;
     mMobilePlantComponent = mc;
     Initialize();
     InEditMode = true;
 }
        public AddEditMobilePlantComponentViewModel(int electricalEquipmentId, IList<string> existingComponentNames)
        {
            Initialize();

            ExistingComponentNames = existingComponentNames;
            mMobilePlantComponent = new MobilePlantComponent();
            mMobilePlantComponent.MobilePlantPropertyValues = new List<MobilePlantPropertyValue>();
            mMobilePlantComponent.MobilePlantId = electricalEquipmentId;
            InEditMode = false;
        }
        public AddEditMobilePlantComponentDialog(MobilePlantComponent mobilePlantEquipmentComponent, IList<string> existingComponentNames)
        {
            // Required to initialize variables
            InitializeComponent();

            AddEditMobilePlantComponentViewModel addEditMobilePlantComponentViewModel = new AddEditMobilePlantComponentViewModel(mobilePlantEquipmentComponent, existingComponentNames);

            addEditMobilePlantComponentViewModel.Loaded += () =>
            {
                addEditMobilePlantComponentViewModel.View = this;
                DataContext = addEditMobilePlantComponentViewModel;
                Utils.ResetOriginalValues(LayoutRoot);
            };
        }
        private void InsertData(IList<MobilePlantComponentDataAdapter> adapters)
        {
            for (int index = 0; index < adapters.Count; index++)
            {
                MobilePlantComponentDataAdapter adapter = adapters[index];
                if (!adapter.IsValid())
                {
                    continue;
                }

                //check for duplicate Component Name in the Excell
                IList<string> componentNames = (from x in adapters select x.ComponentName).ToList();
                if (DuplicateItemNameFoundInExcell(adapter.ComponentName, componentNames, adapter.RowNumber))
                {
                    continue;
                }

                //Check for duplicate Component Name in the Database
                componentNames = (from x in mExistingComponents select x.Name).ToList();
                if (DuplicateItemNameFoundInDatabase(adapter.ComponentName, componentNames, adapter.RowNumber))
                {
                    continue;
                }

                var newComponent = new MobilePlantComponent();
                newComponent.LastModifiedDate = DateTime.Now;
                newComponent.LastModifiedById = MetaData.UserId;

                newComponent.Name = adapter.ComponentName;
                newComponent.Description = adapter.ComponentDescription;

                if (GetMobilePlant(adapter.Tag, newComponent, adapter.RowNumber))
                {
                    continue;
                }

                if (GetMobilePlantComponentType(adapter.ComponentType, newComponent, adapter.RowNumber))
                {
                    continue;
                }

                mExistingComponents = Cee.MobilePlantComponents.ToList(); //refresh!
                MobilePlantComponent existing = (from x in mExistingComponents
                                                 where string.Compare(x.Name, adapter.Tag, true, CultureInfo.CurrentCulture) == 0
                                                       && x.MobilePlantComponentTypeId == newComponent.MobilePlantComponentTypeId
                                                 select x).FirstOrDefault();
                if (existing != null)
                {
                    //error - should not already exist
                    RaiseMessage(CommonUtils.MessageType.Error, string.Format("WorkSheet '{0}' Row '{1}': '{2}' with a component type of '{3}' already exists in the database.  Skipping.",
                        WorkSheetName, adapter.RowNumber, adapter.Tag, newComponent.MobilePlantComponentType.Name));
                    continue;
                }

                bool skipRow = ChangeManufacturerModel(adapter, newComponent);

                if (skipRow) continue;

                BuildPropertyValues(newComponent, adapter);

                Cee.MobilePlantComponents.Add(newComponent);
                mSavedResults.Add(newComponent);

                const decimal incrediment = 0.001m;
                decimal revision = new decimal(1.000);

                List<decimal> foo = (from x in Cee.MobilePlantRevisionHistories where x.MobilePlantId == newComponent.MobilePlantId orderby x.Revision descending select x.Revision).ToList();

                if (foo.Count > 0)
                {
                    revision = foo[0] + incrediment;
                }

                newComponent.MobilePlant.MobilePlantRevisionHistories.Add(new MobilePlantRevisionHistory
                {
                    Date = DateTime.Now,
                    MobilePlantId = newComponent.MobilePlantId,
                    UserId = MetaData.UserId,
                    Description = BuildRevisionHistoryInsertComment(MetaData.RevisionHistoryComment),
                    IsSystemMessage = true,
                    Revision = revision
                });
            }

            if (mSavedResults.Count == 0)
            {
                RaiseMessage(CommonUtils.MessageType.Warning, string.Format("No Equipment Components were added from from worksheet '{0}'.", WorkSheetName));
            }
            else
            {
                //|---   S A V E
                Cee.SaveChanges();
            }
        }
        private bool GetMobilePlantComponentType(string typeName, MobilePlantComponent component, int rowIndex)
        {
            MobilePlantComponentType componentType = (from x in mExistingEquipmentComponentTypes
                                                      where string.Compare(typeName, x.Name, true, CultureInfo.CurrentCulture) == 0
                                                            && !string.IsNullOrEmpty(x.Name)
                                                      select x).FirstOrDefault();

            if (componentType != null)
            {
                component.MobilePlantComponentType = componentType;
                component.MobilePlantComponentTypeId = componentType.Id;
            }
            else
            {
                if (CanCreateProperties)
                {
                    string code = typeName.Replace(" ", "_").ToUpper();

                    componentType = new MobilePlantComponentType { Name = typeName, Code = code, Description = typeName + " (created by importer)", IsActive = true };
                    mExistingEquipmentComponentTypes.Add(componentType);
                    component.MobilePlantComponentType = componentType;
                }
                else
                {
                    RaiseMessage(CommonUtils.MessageType.Error, string.Format("WorkSheet '{0}' Row '{1}': Could not find MobilePlantComponentType '{2}' in database. Skipping this row.", WorkSheetName, rowIndex, typeName));
                    return true;
                }
            }
            return false;
        }
        private bool GetMobilePlant(string tag, MobilePlantComponent newComponent, int rowIndex)
        {
            bool skipRow = false;

            //Check if the Area exist in the database
            MobilePlant equipment = (from x in mExistingEquipments
                                     where string.Compare(tag, x.Name, true, CultureInfo.CurrentCulture) == 0
                                           && !string.IsNullOrEmpty(x.Name)
                                     select x).FirstOrDefault();

            if (equipment == null)
            {
                //try db
                equipment = (from x in Cee.MobilePlants
                             where string.Compare(tag, x.Name, true, CultureInfo.CurrentCulture) == 0
                                   && !string.IsNullOrEmpty(x.Name)
                             select x).FirstOrDefault();
            }

            if (equipment != null)
            {
                newComponent.MobilePlant = equipment;
                newComponent.MobilePlantId = equipment.Id;
            }
            else
            {
                RaiseMessage(CommonUtils.MessageType.Error, string.Format("WorkSheet '{0}' Row '{1}': Could not find Equipment width Tag '{2}' in database. Skipping this row.",
                    WorkSheetName, rowIndex, tag));
                skipRow = true;
            }

            return skipRow;
        }
        private bool ChangeManufacturerModel(MobilePlantComponentDataAdapter adapter, MobilePlantComponent newComponent)
        {
            //CHANGING Manufacturer
            if (!string.IsNullOrEmpty(adapter.Manufacturer))
            {
                if (adapter.Manufacturer.ToLower() != "null")
                {
                    Manufacturer manufactuer = (from x in mExistingManufacturers where x.Name.ToLower() == adapter.Manufacturer.ToLower() select x).FirstOrDefault();

                    if (manufactuer == null)
                    {
                        RaiseMessage(CommonUtils.MessageType.Error, string.Format(BuildItemNotFoundInDatabaseMessage("Manufacturer", adapter.Manufacturer, adapter.RowNumber)));
                        return false;
                    }

                    newComponent.Manufacturer = manufactuer;
                    newComponent.ManufacturerId = manufactuer.Id;

                    if (adapter.Model.ToLower() != "null")
                    {
                        //CHANGING Model
                        if (!string.IsNullOrEmpty(adapter.Model))
                        {
                            Model model = (from x in manufactuer.Models where x.Name.ToLower() == adapter.Model.ToLower() select x).FirstOrDefault();

                            if (model == null)
                            {
                                RaiseMessage(CommonUtils.MessageType.Error, string.Format(BuildItemNotFoundInDatabaseMessage("Model", adapter.Model, adapter.RowNumber)));
                                return false;
                            }

                            newComponent.Model = model;
                            newComponent.ModelId = model.Id;
                        }
                    }
                    else
                    {
                        newComponent.Model = null;
                        newComponent.ModelId = null;
                    }
                }
                else
                {
                    newComponent.Manufacturer = null;
                    newComponent.ManufacturerId = null;
                    newComponent.Model = null;
                    newComponent.ModelId = null;
                }
            }
            return false;
        }
        private MobilePlantRevisionHistory BuildRevisionHistory(MobilePlantComponent existing)
        {
            const decimal incrediment = 0.001m;
            var revision = new decimal(1.000);

            List<decimal> foo = (from x in Cee.MobilePlantRevisionHistories where x.MobilePlantId == existing.MobilePlantId orderby x.Revision descending select x.Revision).ToList();

            if (foo.Count > 0)
            {
                revision = foo[0] + incrediment;
            }

            var rvh = new MobilePlantRevisionHistory
            {
                Date = DateTime.Now,
                MobilePlantId = existing.MobilePlantId,
                UserId = MetaData.UserId,
                Description = BuildRevisionHistoryInsertVersionComment(MetaData.RevisionHistoryComment, revision),
                Revision = revision,
                IsSystemMessage = true
            };
            return rvh;
        }
        private void BuildPropertyValues(MobilePlantComponent componentIn, MobilePlantComponentDataAdapter adapter)
        {
            foreach (var pair in adapter.PropertyValues)
            {
                //DOES PROPERTY EXIST?
                MobilePlantProperty property = (from x in mExistingEquipmentProperties where x.Name.ToLower() == pair.Key.ToLower() select x).FirstOrDefault();
                if (property == null)
                {
                    if (CanCreateProperties)
                    {
                        property = new MobilePlantProperty { Name = pair.Key, DefaultValue = pair.Value, Description = " (created by importer)." };
                        mExistingEquipmentProperties.Add(property); //update cache
                    }
                    else
                    {
                        //ERROR!
                        RaiseMessage(CommonUtils.MessageType.Error, string.Format("WorkSheet '{0}' Row '{1} Tag {2} Component Name {3}' : The property does not exist.",
                            WorkSheetName, adapter.RowNumber, adapter.Tag, adapter.ComponentName));
                        continue;
                    }
                }

                //CHECK MobilePlantComponentTypeProperty Exists
                MobilePlantComponentTypeProperty equipmentComponentTypeProperty = null;
                if (mExistingEquipmentComponentTypeProperty.Any())
                {
                    equipmentComponentTypeProperty =
                        (from x in mExistingEquipmentComponentTypeProperty
                         where x.MobilePlantComponentType.Name.ToLower() == componentIn.MobilePlantComponentType.Name.ToLower()
                               && x.MobilePlantProperty.Name.ToLower() == property.Name.ToLower()
                         select x).FirstOrDefault();
                }

                if (equipmentComponentTypeProperty == null)
                {
                    if (CanCreateProperties)
                    {
                        //CREATE JOIN ROW
                        equipmentComponentTypeProperty = new MobilePlantComponentTypeProperty();
                        equipmentComponentTypeProperty.MobilePlantComponentType = componentIn.MobilePlantComponentType; //note: set the object!
                        equipmentComponentTypeProperty.MobilePlantProperty = property; //not set the object!
                        mExistingEquipmentComponentTypeProperty.Add(equipmentComponentTypeProperty); //update cache
                    }
                    else
                    {
                        //ERROR!
                        RaiseMessage(CommonUtils.MessageType.Warning, string.Format("WorkSheet '{0}' Row '{1} Tag {2} Component Type {3}' : The property {4} does not belong to the Component Type.",
                            WorkSheetName, adapter.RowNumber, adapter.Tag, componentIn.MobilePlantComponentType.Name, property.Name));
                        continue;
                    }
                }
                property.MobilePlantComponentTypeProperties.Add(equipmentComponentTypeProperty);

                //CHECK PROPERTYVALUE EXISTS
                MobilePlantPropertyValue propertyValue = null;
                if (mExistingPropertyValues.Any())
                {
                    propertyValue = (from x in mExistingPropertyValues
                                     where x.MobilePlantComponent.Name.ToLower() == componentIn.Name.ToLower()
                                           && x.MobilePlantProperty.Name.ToLower() == property.Name.ToLower()
                                     select x).FirstOrDefault();
                }

                if (propertyValue == null)
                {
                    propertyValue = new MobilePlantPropertyValue();
                    propertyValue.MobilePlantComponent = componentIn;
                    propertyValue.MobilePlantProperty = property;
                    mExistingPropertyValues.Add(propertyValue); //update cache
                }

                //set value
                if (!string.IsNullOrEmpty(pair.Value))
                {
                    propertyValue.Value = pair.Value.ChangeNullToEmptyString();
                }

                componentIn.MobilePlantPropertyValues.Add(propertyValue);
            }
        }
        public void DeleteMobilePlantComponent(MobilePlantComponent mec)
        {
            using (CmsEntities cee = new CmsEntities())
            {
                var mobilePlantPropertyValues = (from x in cee.MobilePlantPropertyValues
                                                where x.MobilePlantComponentId == mec.Id
                                                select x).ToList();

                foreach (var mobilePlantPropertyValue in mobilePlantPropertyValues)
                {
                    cee.MobilePlantPropertyValues.Remove(mobilePlantPropertyValue);
                }

                var q = (from x in cee.MobilePlantComponents
                         where x.Id == mec.Id
                         select x).FirstOrDefault();
                if (q != null)
                {
                    cee.MobilePlantComponents.Remove(q);
                    cee.SaveChanges();
                }
            }
        }
        private void SaveMobilePlantComponents(IEnumerable<MobilePlantComponent> mobilePlantComponents, CmsEntities cee, int mobilePlantEquipmentId, int userId)
        {
            foreach (var mobilePlantComponent in mobilePlantComponents)
            {
                var q = (from x in cee.MobilePlantComponents
                         where x.Id == mobilePlantComponent.Id
                         select x).FirstOrDefault();

                if (q != null)
                {
                    if (q.LastInspectedDate != mobilePlantComponent.LastInspectedDate)
                    {
                        MobilePlantRevisionHistory rv = new MobilePlantRevisionHistory
                        {
                            MobilePlantId = mobilePlantEquipmentId,
                            Date = DateTime.Now,
                            UserId = userId,
                            Description = string.Format("Component '{0}': Last Inspected Date changed from '{1}' to '{2}'.", mobilePlantComponent.Name, q.LastInspectedDate, mobilePlantComponent.LastInspectedDate),
                            IsSystemMessage = true
                        };
                        AddMobilePlantRevisionHistoryInternal(rv, cee);
                    }

                    //Update
                    cee.Entry(q).CurrentValues.SetValues(mobilePlantComponent);

                }
                else
                {
                    //Add new
                    q = new MobilePlantComponent();
                    q.MobilePlantId = mobilePlantComponent.MobilePlantId;
                    q.MobilePlantComponentTypeId = mobilePlantComponent.MobilePlantComponentTypeId;
                    q.Name = mobilePlantComponent.Name;
                    q.Ordinal = mobilePlantComponent.Ordinal;
                    q.NextInspectionDate = mobilePlantComponent.NextInspectionDate;
                    q.LastInspectedById = mobilePlantComponent.LastInspectedById;
                    q.LastInspectedDate = mobilePlantComponent.LastInspectedDate;
                    q.LastModifiedById = mobilePlantComponent.LastModifiedById;
                    q.LastModifiedDate = mobilePlantComponent.LastModifiedDate;
                    q.Description = mobilePlantComponent.Description;
                    q.ManufacturerId = mobilePlantComponent.ManufacturerId;
                    q.ModelId = mobilePlantComponent.ModelId;

                    cee.MobilePlantComponents.Add(q);
                }

                foreach (var mobilePlantComponentPropertyValue in mobilePlantComponent.MobilePlantPropertyValues)
                {
                    var qq = (from x in cee.MobilePlantPropertyValues
                              where x.Id == mobilePlantComponentPropertyValue.Id
                              select x).FirstOrDefault();

                    if (qq != null)
                    {
                        cee.Entry(qq).CurrentValues.SetValues(mobilePlantComponentPropertyValue);
                    }
                    else
                    {
                        cee.MobilePlantPropertyValues.Add(mobilePlantComponentPropertyValue);
                    }
                }
            }
        }
        public DbOperationResult SaveMobilePlantComponent(MobilePlantComponent mobilePlantComponent)
        {
            DbOperationResult result = new DbOperationResult();

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

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

                if (match == null)
                {
                    //So component doesnt exist in the database so lets create it
                    mobilePlantComponent.MobilePlant = null;
                    mobilePlantComponent.MobilePlantComponentType = null;
                    cee.MobilePlantComponents.Add(mobilePlantComponent);
                }
                else
                {
                    //Compoent exist, change the ID of Equipment
                    match.MobilePlantId = mobilePlantComponent.MobilePlantId;
                }

                cee.SaveChanges();
                result.ServerInformationMessages.Add("Save Completed");
                return result;
            }
        }