Example #1
0
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (!File.Exists(CobieFile.Text))
                return;


            var filters = new List<string>();
            filters.Add("text file|*.txt");
            //filters.Add(@"Automation format|*.json");
            //filters.Add(@"Automation format|*.xml");

            var file = GetSaveFileName("Select destination file", filters);
            if (file == "")
                return;
            
            string read;
            _f = Facility.ReadCobie(CobieFile.Text, out read);
            var flogger = new FileInfo(file);
            using (var logger = flogger.CreateText())
            {
                _f.ValidateUK2012(logger, true);
            }
            if (flogger.Exists)
            {
                Process.Start(flogger.FullName);
                ImproveCObie.IsEnabled = true;
            }
        }
        public void ConvertDPoWToCOBieLite()
        {
            //var pow = PlanOfWork.OpenJson("NewtownHighSchool.new.dpow");
            var pow = PlanOfWork.OpenJson("013-Lakeside_Restaurant.dpow");
            const string dir = "..\\..\\COBieLiteUK";
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            var outputs = new List<string>();
            string msg;
            foreach (var stage in pow.ProjectStages)
            {
                var facility = new Xbim.COBieLiteUK.Facility();
                var exchanger = new DPoWToCOBieLiteUKExchanger(pow, facility, stage);
                exchanger.Convert();
                var output = Path.Combine(dir, stage.Name + ".cobieliteUK.json");
                var xls = Path.Combine(dir, stage.Name + ".xlsx");
                outputs.Add(output);
                facility.WriteJson(output, true);
                facility.WriteCobie(xls, out msg);
            }

            //check all result files exist
            foreach (var output in outputs)
            {
                Assert.IsTrue(File.Exists(output));
            }

            //try to reload to make sure serialization and deserilization works in both directions
            foreach (var output in outputs)
            {
                var facility = Xbim.COBieLiteUK.Facility.ReadJson(output);
            }
        }
Example #3
0
        private void SetFacility(Facility facility)
        {
            if (facility == null)
            {
                IsFileOpen = false;
                return;
            }
            ViewFacility = facility;
            // todo: initialise component viewmodel 
            // FacilityViewer.DataContext = new DPoWFacilityViewModel(ReqFacility);

            IsFileOpen = true;

            try
            {
                Classifications.ItemsSource = facility.AssetTypes.Where(at => at.Categories != null)
                    .SelectMany(x => x.Categories)
                    .Select(c => c.Code)
                    .Distinct().ToList();
                if (Classifications.Items.Count > 0)
                {
                    Classifications.SelectedItem = 0;
                }
            }
            catch
            {
                // ignored
            }
        }
Example #4
0
        public void WriteLine(Facility to, Facility from)
        {
            if (logger != null)
            {
                StringBuilder sb = new StringBuilder();
                logger.WriteLine();
                if (from != null)
                {
                    sb.Append("Facility(");
                    sb.Append(from.Name);
                    sb.Append(":");
                    sb.Append(from.ExternalId);
                    sb.Append(") ");
                }
                sb.Append(" =======================INTO====================>>>> ");
                if (to != null)
                {
                    sb.Append("Facility(");
                    sb.Append(to.Name);
                    sb.Append(":");
                    sb.Append(to.ExternalId);
                    sb.Append(") ");
                }

                

                
                logger.WriteLine(sb.ToString());
                logger.WriteLine();
            }
        }
 /// <summary>
 /// Creates the report.
 /// </summary>
 /// <param name="facility">the result of a DPoW validation to be transformed into report form.</param>
 /// <param name="filename">target file for the spreadsheet</param>
 /// <returns>true if successful, errors are cought and passed to Logger</returns>
 public bool Create(Facility facility, String filename)
 {
     if (filename == null)
         return false;
     SpreadSheetFormat format;
     var ext = Path.GetExtension(filename).ToLowerInvariant();
     if (ext != "xlsx")
         format = SpreadSheetFormat.Xlsx;
     else if (ext != "xls")
         format = SpreadSheetFormat.Xls;
     else
         return false;
     return Create(facility, filename, format);
 }
Example #6
0
        public void ConvertDPoWToAll()
        {
            var          pow = PlanOfWork.OpenJson("001-Lakeside_Restaurant.dpow");
            const string dir = "..\\..\\COBieLiteUK";

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string msg;

            foreach (var stage in pow.ProjectStages)
            {
                var json = Path.Combine(dir, stage.Name + ".cobie.json");
                var xlsx = Path.Combine(dir, stage.Name + ".xlsx");
                var ifc  = Path.Combine(dir, stage.Name + ".ifc");

                var facility       = new Xbim.COBieLiteUK.Facility();
                var cobieExchanger = new DPoWToCOBieLiteUKExchanger(pow, facility, stage);
                cobieExchanger.Convert(DateTime.Now);

                facility.WriteJson(json, true);
                facility.WriteCobie(xlsx, out msg);


                //using (var ifcModel = XbimModel.CreateTemporaryModel())
                //{
                //    ifcModel.Initialise("Xbim Tester", "XbimTeam", "Xbim.Exchanger", "Xbim Development Team", "3.0");
                //    using (var txn = ifcModel.BeginTransaction("Conversion from COBie"))
                //    {
                //        ifcModel.Header.FileName.Name = stage.Name;
                //        ifcModel.ReloadModelFactors();
                //        var ifcExchanger = new XbimExchanger.COBieLiteUkToIfc.CoBieLiteUkToIfcExchanger(facility, ifcModel);
                //        ifcExchanger.Convert();
                //        txn.Commit();
                //    }
                //    ifcModel.SaveAs(ifc, XbimStorageType.IFC);
                //    ifcModel.Close();
                //}
            }
        }
 /// <summary>
 /// Creates the report in file format
 /// </summary>
 /// <param name="facility">the result of a DPoW validation to be transformed into report form.</param>
 /// <param name="suggestedFilename">target file for the spreadsheet (warning, the extension is automatically determined depending on the format)</param>
 /// <param name="format">determines the excel format to use</param>
 /// <returns>true if successful, errors are cought and passed to Logger</returns>
 public bool Create(Facility facility, string suggestedFilename, SpreadSheetFormat format)
 {
     var ssFileName = Path.ChangeExtension(suggestedFilename, format == SpreadSheetFormat.Xlsx ? "xlsx" : "xls");
     if (File.Exists(ssFileName))
     {
         File.Delete(ssFileName);
     }
     try
     {
         using (var spreadsheetStream = new FileStream(ssFileName, FileMode.Create, FileAccess.Write))
         {
             var result = Create(facility, spreadsheetStream, format);
             spreadsheetStream.Close();
             return result;
         }
     }
     catch (Exception e)
     {
         Logger.ErrorFormat("Failed to save {0}, {1}", ssFileName, e.Message);
         return false;
     }
 }
        public DpoWFacilityViewModel(Facility model)
        {
            _model = model;
            if (_model == null)
                return;

            // asset types
            //
            if (_model.AssetTypes != null)
            {
                // prepare Avalable classifications
                //
                var s = _model.AssetTypes.Where(at => at.Categories != null)
                    .SelectMany(x => x.Categories)
                    .Select(c => c.Classification)
                    .Distinct().ToList();
                AvailableClassifications = new ObservableCollection<string>(s);

                SelectedClassification =
                    s.Contains(Settings.Default.PreferredClassification)
                        ? Settings.Default.PreferredClassification
                        : AvailableClassifications.FirstOrDefault();
            }
            
            // documents
            //
            if (_model.Documents != null)
            {
                var lst = _model.Documents.Select(document => new DocumentViewModel(document)).ToList();
                Documents = new ObservableCollection<object>(lst);
            }
            else
                Documents = new ObservableCollection<object>();

            // command
            // SaveCommand = new FacilitySaveCommand(_model, this);
        }
Example #9
0
        public void ConvertDPoWToCOBieLite()
        {
            //var pow = PlanOfWork.OpenJson("NewtownHighSchool.new.dpow");
            var          pow = PlanOfWork.OpenJson("013-Lakeside_Restaurant.dpow");
            const string dir = "..\\..\\COBieLiteUK";

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var    outputs = new List <string>();
            string msg;

            foreach (var stage in pow.ProjectStages)
            {
                var facility  = new Xbim.COBieLiteUK.Facility();
                var exchanger = new DPoWToCOBieLiteUKExchanger(pow, facility, stage);
                exchanger.Convert();
                var output = Path.Combine(dir, stage.Name + ".cobieliteUK.json");
                var xls    = Path.Combine(dir, stage.Name + ".xlsx");
                outputs.Add(output);
                facility.WriteJson(output, true);
                facility.WriteCobie(xls, out msg);
            }

            //check all result files exist
            foreach (var output in outputs)
            {
                Assert.IsTrue(File.Exists(output));
            }

            //try to reload to make sure serialization and deserilization works in both directions
            foreach (var output in outputs)
            {
                var facility = Xbim.COBieLiteUK.Facility.ReadJson(output);
            }
        }
Example #10
0
        public void CustomEnumerationTests()
        {
            var f = new Facility();
            Assert.AreEqual(AreaUnit.notdefined, f.AreaUnits);

            f.AreaUnits = AreaUnit.squarefeet;
            Assert.AreEqual(AreaUnit.squarefeet, f.AreaUnits);

            //this should be qualified as a user defined value
            f.AreaUnitsCustom = "aaa";
            Assert.AreEqual(AreaUnit.userdefined, f.AreaUnits);

            //this should be picked from aliases
            f.AreaUnitsCustom = "Square centimeters";
            Assert.AreEqual(AreaUnit.squarecentimeters, f.AreaUnits);

            //this shouldn't change the value
            f.AreaUnits = AreaUnit.userdefined;
            Assert.AreEqual(AreaUnit.squarecentimeters, f.AreaUnits);

            //this should set custom area units to null
            f.AreaUnits = AreaUnit.notdefined;
            Assert.IsNull(f.AreaUnitsCustom);
        }
        public void ConvertDPoWToAll()
        {
            var pow = PlanOfWork.OpenJson("001-Lakeside_Restaurant.dpow");
            const string dir = "..\\..\\COBieLiteUK";
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            string msg;
            foreach (var stage in pow.ProjectStages)
            {
                var json = Path.Combine(dir, stage.Name + ".cobie.json");
                var xlsx = Path.Combine(dir, stage.Name + ".xlsx");
                var ifc = Path.Combine(dir, stage.Name + ".ifc");

                var facility = new Xbim.COBieLiteUK.Facility();
                var cobieExchanger = new DPoWToCOBieLiteUKExchanger(pow, facility, stage);
                cobieExchanger.Convert(DateTime.Now);

                facility.WriteJson(json, true);
                facility.WriteCobie(xlsx, out msg);


                //using (var ifcModel = XbimModel.CreateTemporaryModel())
                //{
                //    ifcModel.Initialise("Xbim Tester", "XbimTeam", "Xbim.Exchanger", "Xbim Development Team", "3.0");
                //    using (var txn = ifcModel.BeginTransaction("Conversion from COBie"))
                //    {
                //        ifcModel.Header.FileName.Name = stage.Name;
                //        ifcModel.ReloadModelFactors();
                //        var ifcExchanger = new XbimExchanger.COBieLiteUkToIfc.CoBieLiteUkToIfcExchanger(facility, ifcModel);
                //        ifcExchanger.Convert();
                //        txn.Commit();
                //    }
                //    ifcModel.SaveAs(ifc, XbimStorageType.IFC);
                //    ifcModel.Close();
                //}
            }
        }
Example #12
0
 private void CloseFile(object sender, RoutedEventArgs e)
 {
     ReqFacility = null;
     LstAssets.ItemsSource = null;
     Classifications.ItemsSource = null;
     IsFileOpen = false;
 }
Example #13
0
        public void CoBieLiteUkCreation()
        {
            var facility = new Facility
            {
                CreatedOn = DateTime.Now,
                CreatedBy = new ContactKey {Email = "*****@*****.**"},
                Categories =
                    new List<Category>
                    {
                        new Category {Code = "Bd_34_54", Description = "Schools", Classification = "Sample"}
                    },
                ExternalId = Guid.NewGuid().ToString(),
                AreaUnits = AreaUnit.squaremeters,
                CurrencyUnit = CurrencyUnit.GBP,
                LinearUnits = LinearUnit.millimeters,
                VolumeUnits = VolumeUnit.cubicmeters,
                AreaMeasurement = "NRM",
                Phase = "Phase A",
                Description = "New facility description",
                Name = "Ellison Building",
                Project = new Project
                {
                    ExternalId = Guid.NewGuid().ToString(),
                    Name = "Project A"
                },
                Site = new Site
                {
                    ExternalId = Guid.NewGuid().ToString(),
                    Name = "Site A"
                },
                Zones = new List<Zone>
                {
                    new Zone
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        ExternalId = Guid.NewGuid().ToString(),
                        Name = "Zone A",
                        Categories = new List<Category> {new Category {Code = "45.789.78", Classification = "Sample"}},
                        Description = "Description of the zone A",
                        Spaces = new List<SpaceKey>
                        {
                            new SpaceKey {Name = "A001 - Front Room"},
                            new SpaceKey {Name = "A002 - Living Room"},
                            new SpaceKey {Name = "A003 - Bedroom"},
                        }
                    }
                },
                Contacts = new List<Contact>
                {
                    new Contact
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        Categories = new List<Category> {new Category {Code = "12.45.56", Classification = "Sample"}},
                        FamilyName = "Martin",
                        Email = "*****@*****.**",
                        GivenName = "Cerny"
                    },
                    new Contact
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        Categories = new List<Category> {new Category {Code = "12.45.56", Classification = "Sample"}},
                        FamilyName = "Peter",
                        Email = "*****@*****.**",
                        GivenName = "Pan"
                    },
                    new Contact
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        Categories = new List<Category> {new Category {Code = "12.45.56", Classification = "Sample"}},
                        FamilyName = "Paul",
                        Email = "*****@*****.**",
                        GivenName = "McCartney"
                    }
                },
                Floors = new List<Floor>
                {
                    new Floor
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        Elevation = 15000,
                        Height = 3400,
                        Spaces = new List<Space>
                        {
                            new Space
                            {
                                CreatedOn = DateTime.Now,
                                CreatedBy = new ContactKey {Email = "*****@*****.**"},
                                Categories =
                                    new List<Category> {new Category {Code = "Sp_02_78_98", Classification = "Sample"}},
                                Description = "First front room in COBieLiteUK ever",
                                Name = "A001 - Front Room",
                                UsableHeight = 3500,
                                NetArea = 6
                            },
                            new Space
                            {
                                CreatedOn = DateTime.Now,
                                CreatedBy = new ContactKey {Email = "*****@*****.**"},
                                Categories =
                                    new List<Category> {new Category {Code = "Sp_02_78_98", Classification = "Sample"}},
                                Description = "First living room in COBieLiteUK ever",
                                Name = "A002 - Living Room",
                                UsableHeight = 4200,
                                NetArea = 55
                            },
                            new Space
                            {
                                CreatedOn = DateTime.Now,
                                CreatedBy = new ContactKey {Email = "*****@*****.**"},
                                Categories =
                                    new List<Category> {new Category {Code = "Sp_02_78_98", Classification = "Sample"}},
                                Description = "First bedroom in COBieLiteUK ever",
                                Name = "A003 - Bedroom",
                                UsableHeight = 4100,
                                NetArea = 25
                            }
                        }
                    }
                },
                AssetTypes = new List<AssetType>
                {
                    new AssetType
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        Name = "Brick layered wall",
                        Assets = new List<Asset>
                        {
                            new Asset
                            {
                                CreatedOn = DateTime.Now,
                                Name = "120mm partition wall",
                                Representations = new List<Representation>
                                {
                                    new Representation
                                    {
                                        CreatedOn = DateTime.Now,
                                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                                        X = 0,
                                        Y = 0,
                                        Z = 0,
                                        SizeX = 1000,
                                        SizeY = 2000,
                                        SizeZ = 200,
                                        Name = Guid.NewGuid().ToString()
                                    }
                                },
                                CreatedBy = new ContactKey {Email = "*****@*****.**"}
                            },
                            new Asset
                            {
                                CreatedOn = DateTime.Now,
                                Name = "180mm partition wall",
                                Representations = new List<Representation>
                                {
                                    new Representation
                                    {
                                        CreatedOn = DateTime.Now,
                                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                                        X = 0,
                                        Y = 0,
                                        Z = 0,
                                        SizeX = 1000,
                                        SizeY = 2000,
                                        SizeZ = 200,
                                        Name = Guid.NewGuid().ToString()
                                    }
                                },
                                CreatedBy = new ContactKey {Email = "*****@*****.**"}
                            },
                            new Asset
                            {
                                CreatedOn = DateTime.Now,
                                Name = "350mm external brick wall",
                                Representations = new List<Representation>
                                {
                                    new Representation
                                    {
                                        CreatedOn = DateTime.Now,
                                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                                        X = 0,
                                        Y = 0,
                                        Z = 0,
                                        SizeX = 1000,
                                        SizeY = 2000,
                                        SizeZ = 200,
                                        Name = Guid.NewGuid().ToString()
                                    }
                                },
                                CreatedBy = new ContactKey {Email = "*****@*****.**"}
                            }
                        }
                    }
                },
                Attributes = new List<Attribute>
                {
                    new Attribute
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        Name = "String attribute",
                        Value = new StringAttributeValue {Value = "Almukantarant"},
                        Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                    },
                    new Attribute
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        Name = "Boolean attribute",
                        Value = new BooleanAttributeValue {Value = true},
                        Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                    },
                    new Attribute
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        Name = "Datetime attribute",
                        Value = new DateTimeAttributeValue {Value = DateTime.Now},
                        Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                    },
                    new Attribute
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        Name = "Decimal attribute",
                        Value = new DecimalAttributeValue {Value = 256.2},
                        Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                    },
                    new Attribute
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        Name = "Integer attribute",
                        Value = new IntegerAttributeValue {Value = 7},
                        Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                    },
                    new Attribute
                    {
                        CreatedOn = DateTime.Now,
                        CreatedBy = new ContactKey {Email = "*****@*****.**"},
                        Name = "Null attribute"
                    }
                },
                Stages = new List<ProjectStage>(new[]
                {
                    new ProjectStage
                    {
                        Name = "Stage 0",
                        CreatedOn = DateTime.Now,
                        Start = DateTime.Now.AddDays(5),
                        End = DateTime.Now.AddDays(10),
                        CreatedBy = new ContactKey {Email = "*****@*****.**"}
                    },
                    new ProjectStage
                    {
                        Name = "Stage 1",
                        CreatedOn = DateTime.Now,
                        Start = DateTime.Now.AddDays(10),
                        End = DateTime.Now.AddDays(20),
                        CreatedBy = new ContactKey {Email = "*****@*****.**"}
                    },
                    new ProjectStage
                    {
                        Name = "Stage 2",
                        CreatedOn = DateTime.Now,
                        Start = DateTime.Now.AddDays(20),
                        End = DateTime.Now.AddDays(110),
                        CreatedBy = new ContactKey {Email = "*****@*****.**"}
                    },
                    new ProjectStage
                    {
                        Name = "Stage 3",
                        CreatedOn = DateTime.Now,
                        Start = DateTime.Now.AddDays(110),
                        End = DateTime.Now.AddDays(300),
                        CreatedBy = new ContactKey {Email = "*****@*****.**"}
                    },
                })
            };

            //save model to file to check it
            string msg;
            const string xmlFile = "facility.cobielite.xml";
            const string jsonFile = "facility.cobielite.json";
            const string xlsxFile = "facility.cobielite.xlsx";
            facility.WriteXml(xmlFile, true);
            facility.WriteJson(jsonFile, true);
            facility.WriteCobie(xlsxFile, out msg);

            var facility2 = Facility.ReadXml(xmlFile);
            var facility3 = Facility.ReadJson(jsonFile);
        }
Example #14
0
        // xml navigation sample at http://support.microsoft.com/kb/308333
        private void OpenFile(object sender, RoutedEventArgs e)
        {
            var supportedFiles = new []
            {
                "All supprted files|*.xlsx;*.xls;*.xml;*.json",
                "Validation requirement Excel|*.xlsx;*.xls",
                "Validation requirement XML|*.xml",
                "Validation requirement json|*.json"
            };

            var openFile = new OpenFileDialog();
            openFile.Filter = string.Join("|", supportedFiles);

            var res = openFile.ShowDialog();

            if (res.HasValue && res.Value)
            {
                var r = new FacilityReader();
                ReqFacility = r.LoadFacility(openFile.FileName);
                TestValidation();
            }
        }
Example #15
0
 private void TestValidation()
 {
     if (ReqFacility == null || ModelFacility == null)
         return;
     var f = new FacilityValidator();
     ValFacility = f.Validate(ReqFacility, ModelFacility);
     SetFacility(ValFacility);
 }
Example #16
0
 /// <summary>
 /// Generate a XML File
 /// </summary>
 /// <param name="parameters">Params</param>
 /// <param name="fileName">Root file name</param>
 /// <param name="facility">Facility</param>
 /// <returns>file name</returns>
 private string CreateXmlFile(Params parameters, string fileName, Facility facility)
 {
     var xmlName = Path.ChangeExtension(fileName, ".xml");
     Worker.ReportProgress(0, string.Format("Creating file: {0}", xmlName));
     facility.ReportProgress.Progress = Worker.ReportProgress;
     facility.WriteXml(xmlName, true);
     return xmlName;
 }
Example #17
0
        public void AttributeTest()
        {
            var facility = new Facility
            {
                Attributes = new List<Attribute>
                {
                    new Attribute
                    {
                        Name = "Boolean",
                        Value = new BooleanAttributeValue {Value = true}
                    },
                    new Attribute
                    {
                        Name = "DateTime",
                        Value = new DateTimeAttributeValue {Value = DateTime.Today}
                    },
                    new Attribute
                    {
                        Name = "Decimal",
                        Value = new DecimalAttributeValue {Value = 10.0}
                    },
                    new Attribute
                    {
                        Name = "Integer",
                        Value = new IntegerAttributeValue {Value = 5}
                    },
                    new Attribute
                    {
                        Name = "String",
                        Value = new StringAttributeValue {Value = "A"}
                    },
                    new Attribute
                    {
                        Name = "Null"
                    }
                }
            };

            const string file = "attribute_test.json";

            //write to file and minified file (attribute type names minified)
            facility.WriteJson(file);

            var f2 = Facility.ReadJson(file);

            foreach (var f in new []{f2})
            {
                Assert.AreEqual((f.Attributes.FirstOrDefault(a => a.Name == "Boolean").Value as BooleanAttributeValue).Value, true);
                Assert.AreEqual((f.Attributes.FirstOrDefault(a => a.Name == "DateTime").Value as DateTimeAttributeValue).Value, DateTime.Today);
                Assert.AreEqual((f.Attributes.FirstOrDefault(a => a.Name == "Decimal").Value as DecimalAttributeValue).Value ?? 0, 10.0, 0.0000001);
                Assert.AreEqual((f.Attributes.FirstOrDefault(a => a.Name == "Integer").Value as IntegerAttributeValue).Value, 5);
                Assert.AreEqual((f.Attributes.FirstOrDefault(a => a.Name == "String").Value as StringAttributeValue).Value, "A");
                Assert.IsNull(f.Attributes.FirstOrDefault(a => a.Name == "Null").Value);
            }

        }
 public DocumentsValidator(List<Document> requiredDocuments, Facility destinationFacility)
 {
     HasFailures = false;
     _requiredDocuments = requiredDocuments.Where(doc => doc.IsClassifiedAsRequirement()).ToList();
     _destinationFacility = destinationFacility;
 }
 /// <returns>true if it has failures</returns>
 private bool ValidateAssetTypes(Facility requirement, Facility submitted, Facility retFacility)
 {
     if (requirement.AssetTypes == null) 
         return true;
     var ret = false;
     foreach (var assetTypeRequirement in requirement.AssetTypes)
     {
         var v = new CobieObjectValidator<AssetType, Asset>(assetTypeRequirement)
         {
             TerminationMode = TerminationMode
         };
         if (! v.HasRequirements)
             continue;
         var candidates = v.GetCandidates(submitted.AssetTypes).ToList();
         
         if (candidates.Any())
         {
             foreach (var candidate in candidates)
             {
                 if (retFacility.AssetTypes == null)
                     retFacility.AssetTypes = new List<AssetType>();
                 retFacility.AssetTypes.Add(v.Validate(candidate, retFacility));
             }
         }
         else
         {
             if (retFacility.AssetTypes == null)
                 retFacility.AssetTypes = new List<AssetType>();
             retFacility.AssetTypes.Add(v.Validate((AssetType) null, retFacility));
         }
         ret |= v.HasFailures;
     }
     return ret;
 }
        /// <summary>
        /// Performs the validation
        /// </summary>
        /// <param name="requirement">a requirement facility</param>
        /// <param name="submitted">the submission model to be validated</param>
        /// <returns></returns>
        public Facility Validate(Facility requirement, Facility submitted)
        {
            var retFacility = new Facility {Categories = new List<Category>()};
            var sb = new StringBuilder();

            // facility validation is carried out through the validation of:
            // a) local values
            // b) Project
            // c) AssetTypes/Assets
            // d) Zones/Spaces 
            // e) Documents

            if (!requirement.IsClassifiedAsRequirement())
            {
                retFacility.Categories.Add(FailedCat);
                retFacility.Name = "Invalid.";
                retFacility.Description = "Cannot validate submitted facility: requirement file is invalid.";
                return retFacility;
            }

            // a)
            // area units
            if (requirement.AreaUnitsCustom != submitted.AreaUnitsCustom)
            {
                retFacility.AreaUnitsCustom = string.Format("{0} (should be '{1}')", submitted.AreaUnitsCustom, requirement.AreaUnitsCustom);
                sb.AppendFormat("{0} failure: {1}\r\n", "Area units", retFacility.AreaUnitsCustom);
                HasFailures = true;
            }
            else
            {
                retFacility.AreaUnitsCustom = submitted.AreaUnitsCustom;
            }

            // linear units
            if (requirement.LinearUnitsCustom != submitted.LinearUnitsCustom)
            {
                retFacility.LinearUnitsCustom = string.Format("{0} (should be '{1}')", submitted.LinearUnitsCustom, requirement.LinearUnitsCustom);
                sb.AppendFormat("{0} failure: {1}\r\n", "Linear units", retFacility.LinearUnitsCustom);
                HasFailures = true;
            }
            else
            {
                retFacility.LinearUnitsCustom = submitted.LinearUnitsCustom;
            }

            // Volume units
            if (requirement.VolumeUnitsCustom != submitted.VolumeUnitsCustom)
            {
                retFacility.VolumeUnitsCustom = string.Format("{0} (should be '{1}')", submitted.VolumeUnitsCustom, requirement.VolumeUnitsCustom);
                sb.AppendFormat("{0} failure: {1}\r\n", "Volume units", retFacility.VolumeUnitsCustom);
                HasFailures = true;
            }
            else
            {
                retFacility.VolumeUnitsCustom = submitted.VolumeUnitsCustom;
            }

            // Currency units
            if (requirement.CurrencyUnitCustom != submitted.CurrencyUnitCustom)
            {
                retFacility.CurrencyUnitCustom = string.Format("{0} (should be '{1}')", submitted.CurrencyUnitCustom, requirement.CurrencyUnitCustom);
                sb.AppendFormat("{0} failure: {1}\r\n", "Currency units", retFacility.CurrencyUnitCustom);
                HasFailures = true;
            }
            else
            {
                retFacility.CurrencyUnitCustom = submitted.CurrencyUnitCustom;
            }

            if (requirement.Project != null)
            {
                // to be added project level validation here.
                var pv = new ProjectValidator(requirement.Project);
                retFacility.Project = pv.Validate(submitted.Project);

                if (pv.HasFailures)
                {
                    sb.AppendFormat("Validation of Project information fails, see project information for detail.\r\n");
                    HasFailures = true;
                }
            }
            // c) AssetTypes/Assets
            HasFailures |= ValidateAssetTypes(requirement, submitted, retFacility);
            // d) Zones/Spaces
            HasFailures |= ValidateZones(requirement, submitted, retFacility);

            // e) Documents
            HasFailures |= ValidateDocuments(requirement, submitted, retFacility);

            retFacility.Description = sb.ToString();
            retFacility.Categories.Add(HasFailures ? FailedCat : PassedCat);

            return retFacility;
        }
Example #21
0
 /// <summary>
 /// Generate a Excel File
 /// </summary>
 /// <param name="parameters">Params</param>
 /// <param name="fileName">Root file name</param>
 /// <param name="facility">Facility</param>
 /// <returns>file name</returns>
 private string CreateExcelFile(Params parameters, string fileName, Facility facility)
 {
     ExcelTypeEnum excelType = (ExcelTypeEnum)Enum.Parse(typeof(ExcelTypeEnum), parameters.ExportType.ToString(),true);
     var excelName = Path.ChangeExtension(fileName, excelType == ExcelTypeEnum.XLS ? ".xls" : ".xlsx");
     Worker.ReportProgress(0, string.Format("Creating file: {0}", excelName));
     string msg;
     using (var file = File.Create(excelName))
     {
         facility.ReportProgress.Progress = Worker.ReportProgress;
         facility.WriteCobie(file, excelType, out msg, parameters.Filter, parameters.TemplateFile, true);
     }
     //_worker.ReportProgress(0, msg); //removed for now, kill app for some reason
     return excelName;
 }
Example #22
0
        /// <summary>
        /// This method searches through the facilities to look
        /// for properties inside the property sets of Assets
        /// to look for values that match Regex classification 
        /// formats, set out in the DataReader. It then adds any
        /// values that match the Regular Expression as a category
        /// of assets which conforms with the Schema.
        /// </summary>
        private static void AddClassificationsToAssets(Facility facility)
        {
            var dataReader = new ClassificationMappingReader();//DataReader Object which will create and populate the mappings table.
            //Get Each AssetType
            foreach (AssetType at in facility.AssetTypes)
            {
                //Get Each Asset
                foreach (Asset a in at.Assets)
                {
                    //Create a new Category for the Asset
                    a.Categories = new List<Category>();

                    //Get Each Property
                    foreach (var attr in a.Attributes)
                    {
                        if (attr.Value.GetStringValue() != null && a.Categories.Count == 0)
                        {
                            //Get the Inferred Classifications

                            var inferredClassifications = FindInferredClassifications(attr.Value.GetStringValue(), dataReader);

                            foreach (var ic in inferredClassifications)
                            {
                                bool UniclassMatch = false;
                                bool NbsMatch = false;
                                bool NrmMatch = false;

                                foreach (var cat in a.Categories)
                                {
                                    if (ic.UniclassCode != null && cat.Code == ic.UniclassCode)
                                    {
                                        UniclassMatch = true;
                                    }
                                    if (ic.NbsCode != null && cat.Code == ic.NbsCode)
                                    {
                                        NbsMatch = true;
                                    }
                                    if (ic.NrmCode != null && cat.Code == ic.NrmCode)
                                    {
                                        NrmMatch = true;
                                    }
                                }
                                //Add the Classifications as categories if they exist.
                                if (ic.UniclassCode != null && !UniclassMatch)
                                {
                                    var uniClass = new Xbim.COBieLiteUK.Category();
                                    uniClass.Classification = "Uniclass 2015 Reference (Inferred)";
                                    uniClass.Code = ic.UniclassCode;
                                    uniClass.Description = ic.UniclassDescription;
                                    a.Categories.Add(uniClass);
                                }
                                if (ic.NbsCode != null && !NbsMatch)
                                {
                                    Xbim.COBieLiteUK.Category Nbs = new Xbim.COBieLiteUK.Category();
                                    Nbs.Classification = "NBS Reference (Inferred)";
                                    Nbs.Code = ic.NbsCode;
                                    Nbs.Description = ic.NbsDescription;
                                    a.Categories.Add(Nbs);
                                }
                                if (ic.NrmCode != null && !NrmMatch)
                                {
                                    Xbim.COBieLiteUK.Category Nrm = new Xbim.COBieLiteUK.Category();
                                    Nrm.Classification = "NRM Reference (Inferred)";
                                    Nrm.Code = ic.NrmCode;
                                    Nrm.Description = ic.NrmDescription;
                                    a.Categories.Add(Nrm);
                                }
                            }

                        }
                    }
                }
            }
        }
Example #23
0
        public static Facility ReadCobie(Stream stream, ExcelTypeEnum type, out string message,
                                         string version = "UK2012")
        {
            //use NPOI to open and access spreadsheet data
            IWorkbook workbook;

            switch (type)
            {
            case ExcelTypeEnum.XLS:
                workbook = new HSSFWorkbook(stream);
                break;

            case ExcelTypeEnum.XLSX:
                workbook = new XSSFWorkbook(stream);
                break;

            default:
                throw new ArgumentOutOfRangeException("type");
            }

            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            string msg;
            var    flatList = ReadAllCobieObjects(workbook, out msg, version);

            message = msg ?? "";

            Debug.WriteLine("Reading all COBie objects: " + stopWatch.ElapsedMilliseconds);
            stopWatch.Reset();
            stopWatch.Start();

            var facilities = flatList.OfType <Facility>().ToArray();

            if (facilities.Count() > 1)
            {
                message +=
                    String.Format(
                        "There are {0} facilities in the data. Only first facility {1} will be used. This is an invalid COBie spreadsheet. \n",
                        facilities.Length, facilities[0].Name);
            }
            var facility = facilities.FirstOrDefault();

            if (facility == null)
            {
                message +=
                    "There is no facility in the data. Default facility will be created as a root object. This is an invalid COBie spreadsheet. \n";
                facility = new Facility {
                    Name = "Default facility"
                };
                flatList.Add(facility);
            }

            //create structure hierarchy
            var parallelMessage = new[] { "" };
            var newTypes        = new List <AssetType>();
            var typeDictionary  = CreateTypeDictionary(flatList);

            Parallel.ForEach(flatList.ToArray(), o =>
            {
                string addToParentMsg;
                o.AddToParent(typeDictionary, facility, newTypes, out addToParentMsg, version);
                lock (parallelMessage)
                {
                    parallelMessage[0] += addToParentMsg;
                }
            });
            message += parallelMessage[0];

            //foreach (var cobieObject in flatList.ToArray())
            //{
            //    cobieObject.AddToParent(typeDictionary, facility, newTypes, out msg, version);
            //    message += msg;
            //}

            flatList.AddRange(newTypes);
            foreach (var cobieObject in flatList)
            {
                cobieObject.AfterCobieRead();
            }

            Debug.WriteLine("Building COBieLite hierarchy: " + stopWatch.ElapsedMilliseconds);
            stopWatch.Reset();
            stopWatch.Start();


            //load metadate from the first sheet
            facility.Metadata = new Metadata();
            var log = new StringWriter();

            facility.Metadata.LoadFromCobie(workbook, log, version);
            message += log.ToString();

            //set facility for all objects
            facility.SetFacility(facility);

            return(facility);
        }
Example #24
0
        private string CreateIfcFile(Params parameters, string fileName, Facility facility)
        {
            var ifcName = Path.ChangeExtension(fileName, ".ifc");
            if (File.Exists(ifcName))
            {
                DateTime now = DateTime.Now;
                ifcName = Path.GetDirectoryName(ifcName)+ "\\" + Path.GetFileNameWithoutExtension(ifcName) + "(" + DateTime.Now.ToString("HH-mm-ss") + ").ifc";
            }
            var xbimFile = Path.ChangeExtension(ifcName, "xbim");
            Worker.ReportProgress(0, string.Format("Creating file: {0}", xbimFile));
            facility.ReportProgress.Progress = Worker.ReportProgress;
            using (var ifcModel = XbimModel.CreateModel(xbimFile))
            {
                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
                ifcModel.Initialise(fvi.CompanyName, fvi.CompanyName, fvi.ProductName, fvi.CompanyName, fvi.ProductVersion);
                ifcModel.ReloadModelFactors();
                using (var txn = ifcModel.BeginTransaction("Convert from COBieLiteUK"))
                {
                    var coBieLiteUkToIfcExchanger = new CoBieLiteUkToIfcExchanger(facility, ifcModel);
                    coBieLiteUkToIfcExchanger.Convert();
                    txn.Commit();
                }
                Worker.ReportProgress(0, string.Format("Creating file: {0}", ifcName));
                ifcModel.SaveAs(ifcName, XbimStorageType.IFC);
                ifcModel.Close();
            }

            return ifcName;
        }
Example #25
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 /// <param name="validationResultFacility">The result of a validation process to report over.</param>
 public FacilityReport(Facility validationResultFacility)
 {
     _validationResult = validationResultFacility;
 }
        /// <summary>
        /// Creates the report.
        /// </summary>
        /// <param name="reportFacility">the result of a DPoW validation to be transformed into report form.</param>
        /// <param name="destinationStream">target stream for the spreadsheet</param>
        /// <param name="format">determines the excel format to use</param>
        /// <returns>true if successful, errors are cought and passed to Logger</returns>
        public bool Create(Facility reportFacility, Stream destinationStream, SpreadSheetFormat format)
        {
            var workBook = format == SpreadSheetFormat.Xlsx
                // ReSharper disable once RedundantCast
                ? (IWorkbook)new XSSFWorkbook()
                // ReSharper disable once RedundantCast
                : (IWorkbook)new HSSFWorkbook();
            

            var facReport = new FacilityReport(reportFacility);

            
            var summaryPage = workBook.CreateSheet("Summary");
            if (!CreateSummarySheet(summaryPage, reportFacility)) 
                return false;
            
            // reports on Documents
            //
            if (reportFacility.Documents != null)
            {
                var documentsPage = workBook.CreateSheet("Documents");
                if (!CreateDocumentDetailsSheet(documentsPage, reportFacility.Documents))
                    return false;
            }

            var iRunningWorkBook = 1;
            // reports on AssetTypes details
            //
            // ReSharper disable once LoopCanBeConvertedToQuery // might restore once code is stable
            foreach (var assetType in facReport.AssetRequirementGroups)
            {
                // only report items with any assets submitted (a different report should probably be provided otherwise)

                if (assetType.GetSubmittedAssetsCount() < 1)
                    continue;
                var firstOrDefault = assetType.RequirementCategories.FirstOrDefault(cat => cat.Classification == @"Uniclass2015");
                if (firstOrDefault == null) 
                    continue;
                var tName = firstOrDefault.Code;
                var validName = WorkbookUtil.CreateSafeSheetName(string.Format(@"{0} {1}", iRunningWorkBook++, tName));

                var detailPage = workBook.CreateSheet(validName);
                if (!CreateDetailSheet(detailPage, assetType))
                    return false;
            }

            // reports on Zones details

            // ReSharper disable once LoopCanBeConvertedToQuery // might restore once code is stable
            foreach (var zoneGroup in facReport.ZoneRequirementGroups)
            {
                // only report items with any assets submitted (a different report should probably be provided otherwise)
                if (zoneGroup.GetSubmittedAssetsCount() < 1)
                    continue;
                var firstOrDefault = zoneGroup.RequirementCategories.FirstOrDefault(cat => cat.Classification == @"Uniclass2015");
                if (firstOrDefault == null) 
                    continue;
                var tName = firstOrDefault.Code;
                var validName = WorkbookUtil.CreateSafeSheetName(string.Format(@"{0} {1}", iRunningWorkBook++, tName));

                var detailPage = workBook.CreateSheet(validName);
                if (!CreateDetailSheet(detailPage, zoneGroup))
                    return false;
            }
            try
            {
                workBook.Write(destinationStream);
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("Failed to stream excel report: {1}", e.Message);
                return false;
            }
            return true;
        }
 private bool ValidateDocuments(Facility requirement, Facility submitted, Facility retFacility)
 {
     if (requirement.Documents == null)
         return true;
     var dv = new DocumentsValidator(requirement.Documents, retFacility) {TerminationMode = TerminationMode};
     if (retFacility.Documents == null)
         retFacility.Documents = new List<Document>();
     var bAnyDocs = false;
     foreach (var doc in dv.ValidatedDocs(submitted.Documents))
     {
         bAnyDocs = true;
         retFacility.Documents.Add(doc);
     }
     if (!bAnyDocs)
         retFacility.Documents = null; // if empty then remove the list for cleanness
     return dv.HasFailures;
 }
Example #28
0
        public void DeepSearchTest()
        {
            #region Model

            var facility = new Facility
            {
                Contacts = new List<Contact>(new[]
                {
                    new Contact
                    {
                        Name = "*****@*****.**"
                    }
                }),
                Floors = new List<Floor>(new[]
                {
                    new Floor
                    {
                        Name = "Floor 0",
                        Spaces = new List<Space>(new[]
                        {
                            new Space
                            {
                                Name = "Space A",
                                Attributes = new List<Attribute>(new[]
                                {
                                    new Attribute {Name = "Space A attribute 1"},
                                    new Attribute {Name = "Space A attribute 2"},
                                })
                            },
                            new Space
                            {
                                Name = "Space B",
                                Attributes = new List<Attribute>(new[]
                                {
                                    new Attribute {Name = "Space B attribute 1"},
                                    new Attribute {Name = "Space B attribute 2"},
                                })
                            }
                        })
                    },
                    new Floor
                    {
                        Name = "Floor 1",
                        Spaces = new List<Space>(new[]
                        {
                            new Space
                            {
                                Name = "Space C",
                                Attributes = new List<Attribute>(new[]
                                {
                                    new Attribute {Name = "Space C attribute 1"},
                                    new Attribute {Name = "Space C attribute 2"},
                                })
                            },
                            new Space
                            {
                                Name = "Space D",
                                Attributes = new List<Attribute>(new[]
                                {
                                    new Attribute {Name = "Space D attribute 1"},
                                    new Attribute {Name = "Space D attribute 2"},
                                })
                            }
                        })
                    },
                    new Floor
                    {
                        Name = "Floor 2",
                        Spaces = new List<Space>(new[]
                        {
                            new Space
                            {
                                Name = "Space E",
                                Attributes = new List<Attribute>(new[]
                                {
                                    new Attribute {Name = "Space E attribute 1"},
                                    new Attribute {Name = "Space E attribute 2"},
                                })
                            },
                            new Space
                            {
                                Name = "Space F",
                                Attributes = new List<Attribute>(new[]
                                {
                                    new Attribute {Name = "Space F attribute 1"},
                                    new Attribute {Name = "Space F attribute 2"},
                                })
                            }
                        })
                    }
                })
            };

            #endregion

            var allAttributes = facility.Get<Attribute>();
            Assert.AreEqual(12, allAttributes.Count());

            var allSpaces = facility.Get<Space>();
            Assert.AreEqual(6, allSpaces.Count());

            var spaceA = facility.Get<Space>(s => s.Name == "Space A");
            Assert.AreEqual(1, spaceA.Count());

            var self = facility.Get<Facility>().FirstOrDefault();
            Assert.IsNotNull(self);

            var contact =
                facility.Get<CobieObject>(
                    c => c.GetType() == typeof (Contact) && c.Name == "*****@*****.**");
        }
        /// <returns>true if it has failures</returns>
        private bool ValidateZones(Facility requirement, Facility submitted, Facility retFacility)
        {
            if (requirement.Zones == null) 
                return false;
            var ret = false;
            // hack: create a fake modelFacility candidates from spaces.
            var fakeSubmittedFacility = new Facility();
            fakeSubmittedFacility.Floors = fakeSubmittedFacility.Clone(submitted.Floors as IEnumerable<Floor>).ToList();
            fakeSubmittedFacility.Zones = new List<Zone>();
            var lSpaces = submitted.Get<Space>().ToList();

            foreach (var zoneRequirement in requirement.Zones)
            {
                var v = new CobieObjectValidator<Zone, Space>(zoneRequirement)
                {
                    TerminationMode = TerminationMode
                };
                if (! v.HasRequirements)
                    continue;

                // hack: now create a fake Zone based on candidates from spaces.
                var fakeZone = fakeSubmittedFacility.Create<Zone>();
                fakeZone.Categories = zoneRequirement.Categories.Clone().ToList();
                fakeZone.Name = zoneRequirement.Name;
                fakeZone.ExternalEntity = zoneRequirement.ExternalEntity;
                fakeZone.ExternalSystem = zoneRequirement.ExternalSystem;
                fakeZone.ExternalId = zoneRequirement.ExternalId;
                fakeZone.Spaces = new List<SpaceKey>();

                var candidateSpaces = v.GetCandidates(lSpaces).ToList();

                if (candidateSpaces.Any())
                {
                    foreach (var spaceMatch in candidateSpaces)
                    {
                        var mSpace = spaceMatch.MatchedObject as Space;
                        if (mSpace == null)
                            continue;
                        var sk = new SpaceKey {Name = mSpace.Name};
                        fakeZone.Spaces.Add(sk);
                    }
                    if (retFacility.Zones == null)
                        retFacility.Zones = new List<Zone>();
                    var validatedZone = v.Validate(fakeZone, retFacility);
                    retFacility.Zones.Add(validatedZone);
                    var tmpFloor = retFacility.Get<Floor>(fl => fl.Name == TemporaryFloorName).FirstOrDefault();
                    if (tmpFloor == null)
                        continue;
                    // ensure that the floor and spaces are avalialale in the report facility
                    foreach (var spaceKey in validatedZone.Spaces)
                    {
                        // 1) on the floor
                        var submissionOwningFloor =
                            submitted.Get<Floor>(f => f.Spaces != null && f.Spaces.Any(sp => sp.Name == spaceKey.Name)).FirstOrDefault();
                        if (submissionOwningFloor == null)
                            continue;
                        var destFloor = retFacility.Get<Floor>(f => f.Name == submissionOwningFloor.Name).FirstOrDefault();
                        if (destFloor == null)
                        {
                            destFloor = retFacility.Create<Floor>();
                            destFloor.Name = submissionOwningFloor.Name;
                            destFloor.ExternalEntity = submissionOwningFloor.ExternalEntity;
                            destFloor.ExternalId = submissionOwningFloor.ExternalId;
                            destFloor.ExternalSystem = submissionOwningFloor.ExternalSystem;
                            destFloor.Elevation = submissionOwningFloor.Elevation;
                            destFloor.Spaces = new List<Space>();
                            retFacility.Floors.Add(destFloor); // finally add it in the facility tree
                        }
                        // 2) now on the space.

                        var sourceSpace = tmpFloor.Spaces.FirstOrDefault(sp => sp.Name == spaceKey.Name);
                        if (sourceSpace != null)
                        {
                            destFloor.Spaces.Add(sourceSpace);        
                        }
                    }
                    retFacility.Floors.Remove(tmpFloor);
                }
                else
                {
                    if (retFacility.Zones == null)
                        retFacility.Zones = new List<Zone>();
                    retFacility.Zones.Add(v.Validate((Zone) null, retFacility));
                }
                ret |= v.HasFailures;   
            }
            return ret;
        }
Example #30
0
 /// <summary>
 /// Generate a JSON File
 /// </summary>
 /// <param name="parameters">Params</param>
 /// <param name="fileName">Root file name</param>
 /// <param name="facility">Facility</param>
 /// <returns>file name</returns>
 private string CreateJsonFile(Params parameters, string fileName, Facility facility)
 {
     var jsonName = Path.ChangeExtension(fileName, ".json");
     Worker.ReportProgress(0, string.Format("Creating file: {0}", jsonName));
     facility.ReportProgress.Progress = Worker.ReportProgress;
     facility.WriteJson(jsonName, true);
     return jsonName;
 }
        private bool CreateSummarySheet(ISheet summaryPage, Facility facility)
        {
            try
            {
                var excelRow = summaryPage.GetRow(0) ?? summaryPage.CreateRow(0);  
                var excelCell = excelRow.GetCell(0) ?? excelRow.CreateCell(0);
                SetHeader(excelCell);
                excelCell.SetCellValue("Facility summary");
                var iRunningRow = 2;

                if (facility.AssetTypes != null && facility.AssetTypes.Any())
                {
                    var assetTypesReport = new GroupingObjectSummaryReport<CobieObject>(facility.AssetTypes, "Asset types report");
                    iRunningRow = WriteReportToPage(summaryPage, assetTypesReport.GetReport(PreferredClassification), iRunningRow);
                }

                if (facility.Zones != null && facility.Zones.Any())
                {
                    var zonesReport = new GroupingObjectSummaryReport<CobieObject>(facility.Zones, "Zones report");
                    iRunningRow = WriteReportToPage(summaryPage, zonesReport.GetReport(PreferredClassification),
                        iRunningRow);
                }

                if (facility.Documents != null && facility.Documents.Any())
                {
                    var docReport = new DocumentsReport(facility.Documents);
                    iRunningRow = WriteReportToPage(summaryPage, docReport.GetReport("ResponsibleRole"), iRunningRow);
                }

                Debug.WriteLine(iRunningRow);
                return true;
            }
            catch (Exception e)
            {
                //log the error
                Logger.Error("Failed to create Summary Sheet", e);
                return false;
            }
        }
        private void AddDeepAttributes(Facility facility, bool change)
        {
            var addlist1 = new List<Attribute>
                    {
                        new Attribute
                        {
                            CreatedOn = DateTime.Now,
                            CreatedBy = new ContactKey {Email = "*****@*****.**"},
                            Name = "String attribute 1",
                            Value = new StringAttributeValue {Value = "Depth 1a"},
                            Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                        },
                        new Attribute
                        {
                            CreatedOn = DateTime.Now,
                            CreatedBy = new ContactKey {Email = "*****@*****.**"},
                            Name = "String attribute 2",
                            Value =  new StringAttributeValue {Value = "Depth 1b"},
                            Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                        },
                        new Attribute
                        {
                            CreatedOn = DateTime.Now,
                            CreatedBy = new ContactKey {Email = "*****@*****.**"},
                            Name = "String attribute 3",
                            Value =  new StringAttributeValue {Value = "Depth 1c"},
                            Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                        },
            };
            if (facility.Attributes != null)
            {
                facility.Attributes.AddRange(addlist1);

            }
            else
                facility.Attributes = addlist1;

            var addlist2 = new List<Attribute>
                    {
                        new Attribute
                        {
                            CreatedOn = DateTime.Now,
                            CreatedBy = new ContactKey {Email = "*****@*****.**"},
                            Name = "String attribute 1",
                            Value = new StringAttributeValue {Value = "Depth 2a"},
                            Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                        },
                        new Attribute
                        {
                            CreatedOn = DateTime.Now,
                            CreatedBy = new ContactKey {Email = "*****@*****.**"},
                            Name = "String attribute 2",
                            Value =  new StringAttributeValue {Value = "Depth 2b"},
                            Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                        },
                        new Attribute
                        {
                            CreatedOn = DateTime.Now,
                            CreatedBy = new ContactKey {Email = "*****@*****.**"},
                            Name = "String attribute 3",
                            Value =  new StringAttributeValue {Value = "Depth 2c"},
                            Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                        },
            };
            if (facility.Attributes.Last().Attributes != null)
            {
                facility.Attributes.Last().Attributes.AddRange(addlist2);
            }
            else
                facility.Attributes.Last().Attributes = addlist2;

            var addlist3 = new List<Attribute>
                    {
                        new Attribute
                        {
                            CreatedOn = DateTime.Now,
                            CreatedBy = new ContactKey {Email = "*****@*****.**"},
                            Name = "String attribute 1",
                            Value = new StringAttributeValue {Value = "Depth 3a"},
                            Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                        },
                        new Attribute
                        {
                            CreatedOn = DateTime.Now,
                            CreatedBy = new ContactKey {Email = "*****@*****.**"},
                            Name = !change ? "String attribute 2" :  "String attribute 2 modified",
                            Value =  new StringAttributeValue {Value = "Depth 3b"},
                            Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                        },
                        new Attribute
                        {
                            CreatedOn = DateTime.Now,
                            CreatedBy = new ContactKey {Email = "*****@*****.**"},
                            Name = "String attribute 3",
                            Value =  new StringAttributeValue {Value = !change ? "Depth 3c" : "Depth 3 modified"},
                            Categories = new List<Category> {new Category {Code = "Submitted", Classification = "Sample"}},
                        },
            };
            if (facility.Attributes.Last().Attributes.Last().Attributes != null)
            {
                facility.Attributes.Last().Attributes.Last().Attributes.AddRange(addlist3);
            }
            else
                facility.Attributes.Last().Attributes.Last().Attributes = addlist3;


        }