public void Import_ReverseAlias( )
        {
            IEntityRepository     repository = Factory.EntityRepository;
            IEntityXmlImporter    importer   = Factory.EntityXmlImporter;
            EntityXmlImportResult result;
            string xml;
            long   entityId;

            // Import
            using (RunAsImportExportRole( ))
                using (Stream stream = GetStream("ReverseAlias.xml"))
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        xml    = reader.ReadToEnd( );
                        result = importer.ImportXml(xml, EntityXmlImportSettings.Default);
                    }

            // Check
            Assert.That(result, Is.Not.Null);
            Assert.That(result.RootEntities, Is.Not.Null);
            entityId = result.RootEntities.Single( );

            Definition type = repository.Get <Definition>(entityId);

            Assert.That(type.Fields, Has.Count.EqualTo(1));
        }
        public void Import_NoAliases_AllFields( )
        {
            IEntityRepository     repository = Factory.EntityRepository;
            IEntityXmlImporter    importer   = Factory.EntityXmlImporter;
            EntityXmlImportResult result;
            string  xml;
            long    entityId;
            IEntity entity;

            // Import
            using (RunAsImportExportRole( ))
                using (Stream stream = GetStream("AllFields.xml"))
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        xml    = reader.ReadToEnd( );
                        result = importer.ImportXml(xml, EntityXmlImportSettings.Default);
                    }

            // Check
            Assert.That(result, Is.Not.Null);
            Assert.That(result.RootEntities, Is.Not.Null);
            entityId = result.RootEntities.Single( );

            entity = repository.Get(entityId);
            try
            {
                Assert.That(entity.GetField <string>("core:name"), Is.EqualTo("ImportTest"));
                Assert.That(entity.GetField <string>("core:description"), Is.EqualTo(""));
                Assert.That(entity.GetField <string>("test:afString"), Is.EqualTo("Hello"));
                Assert.That(entity.GetField <bool>("test:afBoolean"), Is.EqualTo(true));
                Assert.That(entity.GetField <DateTime>("test:afDateTime"), Is.EqualTo(DateTime.Parse("2016-12-19 08:02:00Z", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal)));
                Assert.That(entity.GetField <DateTime>("test:afDate"), Is.EqualTo(DateTime.Parse("2016-12-24 13:00:00Z", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal)));
                Assert.That(entity.GetField <DateTime>("test:afTime"), Is.EqualTo(DateTime.Parse("1753-01-01 20:51:00Z", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal)));
                Assert.That(entity.GetField <decimal>("test:afDecimal"), Is.EqualTo(123.4M));
                Assert.That(entity.GetField <decimal>("test:afCurrency"), Is.EqualTo(123.45M));
                Assert.That(entity.GetField <int>("test:afNumber"), Is.EqualTo(123));
                Assert.That(entity.GetField <string>("test:afMultiline"), Is.EqualTo("\nMulti\nLine\n"));

                Resource resource = entity.Cast <Resource>( );
                Assert.That(resource.IsOfType?.First()?.Alias, Is.EqualTo("test:allFields"));
                Assert.That(resource.SecurityOwner?.Alias, Is.EqualTo("core:administratorUserAccount"));

                var relationships = entity.GetRelationships("test:herbs");
                Assert.That(relationships, Has.Count.EqualTo(1));
                Assert.That(relationships.Single( ).Alias, Is.EqualTo("aaBasil"));

                long snacksRelId = Entity.GetIdFromUpgradeId(new Guid("05cd3a57-7b02-4bd0-aadc-272782e971b7"));
                var  revRel      = entity.GetRelationships(snacksRelId, Direction.Reverse);
                Assert.That(revRel, Has.Count.EqualTo(1));
                Assert.That(revRel.Single( ).Alias, Is.EqualTo("aaGarlicBread"));
            }
            finally
            {
                entity.AsWritable().Delete( );
            }
        }
        public void Security_CheckInstancesSecurity(bool grant)
        {
            IEntityXmlExporter exporter = Factory.EntityXmlExporter;
            IEntityXmlImporter importer = Factory.EntityXmlImporter;
            string             xml;

            Definition type = new Definition( );

            type.Inherits.Add(UserResource.UserResource_Type);
            type.Name = Guid.NewGuid( ).ToString( );
            type.Save( );

            Resource instance = Entity.Create(type.Id).As <Resource>( );

            instance.Name = "Mordor";
            instance.Save( );

            // Generate the XML as admin
            using (RunAsImportExportRole( ))
            {
                xml = exporter.GenerateXml(instance.Id, EntityXmlExportSettings.Default);
            }

            // Create a user that can create the types, but not modify the instance
            var user = Entity.Create <UserAccount>( );

            user.Name = "Frodo";
            user.UserHasRole.Add(Entity.Get <Role>("core:importExportRole"));
            user.Save( );

            new AccessRuleFactory( ).AddAllowCreate(user.As <Subject>( ), type.As <SecurableEntity>( )).Save( );
            if (grant)
            {
                new AccessRuleFactory( ).AddAllowByQuery(user.As <Subject>( ),
                                                         type.As <SecurableEntity>( ),
                                                         new[] { Permissions.Read, Permissions.Modify },
                                                         TestQueries.Entities(new EntityRef(type.Id)).ToReport( )).Save( );
            }

            var res = new EntityAccessControlChecker( ).CheckTypeAccess(new[] { type.As <EntityType>() }, Permissions.Create, user);

            // Try to reimport as non-priv user
            using (new SetUser(user))
            {
                Action run = () => importer.ImportXml(xml, EntityXmlImportSettings.Default);

                if (grant)
                {
                    run( );
                }
                else
                {
                    Assert.That(Assert.Throws <PlatformSecurityException>(() => run( )).Message, Is.StringStarting("Frodo does not have edit access to Mordor"));
                }
            }
        }
        public void Export_Document( )
        {
            IEntityXmlImporter    importer = Factory.EntityXmlImporter;
            IEntityXmlExporter    exporter = Factory.EntityXmlExporter;
            EntityXmlImportResult result;
            long entityId;

            // Import - to set up test
            try
            {
                using (RunAsImportExportRole( ))
                    using (Stream stream = EntityXmlImporterTests.GetStream("TestDocument.xml"))
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            string xml1 = reader.ReadToEnd( );
                            result   = importer.ImportXml(xml1, EntityXmlImportSettings.Default);
                            entityId = result.RootEntities.Single( );
                        }
            }
            catch (Exception ex)
            {
                throw new Exception("Import failed during setup for export test", ex);
            }

            // Export
            string xml;

            using (RunAsImportExportRole( ))
            {
                xml = exporter.GenerateXml(entityId, EntityXmlExportSettings.Default);
            }

            // Verify
            XmlDocument doc = new XmlDocument( );

            doc.LoadXml(xml);

            XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);

            // Note: can't get xpath to work with default namespace
            ns.AddNamespace("c", "core");
            ns.AddNamespace("k", "console");

            string     expectedHash = "RV6PPKR5NJHP4GU76KIZ2HXB5BX3SPRKDQAIWQL33W7ADWUEOUJQ";
            XmlElement e            = doc.SelectSingleNode($"/c:xml/c:documents/c:document[@hash='{expectedHash}']", ns) as XmlElement;

            Assert.That(e, Is.Not.Null, "Document element missing");

            string base64 = e.InnerText;

            Assert.That(base64, Is.StringStarting("H4sIAAAAAAAEAO16ZVRcS7P2QHBCcIK7uwQJGtw").And.StringEnding("r/wGi+uxzRi0AAA=="));
        }
        public void Export_Binary( )
        {
            IEntityXmlImporter    importer = Factory.EntityXmlImporter;
            IEntityXmlExporter    exporter = Factory.EntityXmlExporter;
            EntityXmlImportResult result;
            long entityId;

            // Import - to set up test
            try
            {
                using (RunAsImportExportRole( ))
                    using (Stream stream = EntityXmlImporterTests.GetStream("TestPhoto.xml"))
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            string xml1 = reader.ReadToEnd( );
                            result   = importer.ImportXml(xml1, EntityXmlImportSettings.Default);
                            entityId = result.RootEntities.Single( );
                        }
            }
            catch (Exception ex)
            {
                throw new Exception("Import failed during setup for export test", ex);
            }

            // Export
            string xml;

            using (RunAsImportExportRole( ))
            {
                xml = exporter.GenerateXml(entityId, EntityXmlExportSettings.Default);
            }

            // Verify
            XmlDocument doc = new XmlDocument( );

            doc.LoadXml(xml);

            XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);

            // Note: can't get xpath to work with default namespace
            ns.AddNamespace("c", "core");
            ns.AddNamespace("k", "console");

            string     expectedHash = "BN7ED5KVSPBOQQL2OELSONW25BI5MBPWS2JSRHQDIO2KW4UBGGMA";
            XmlElement e            = doc.SelectSingleNode($"/c:xml/c:binaries/c:binary[@hash='{expectedHash}']", ns) as XmlElement;

            Assert.That(e, Is.Not.Null, "Binary element missing");

            string base64 = e.InnerText;

            Assert.That(base64, Is.StringStarting("H4sIAAAAAAAEAOsM8").And.StringEnding("lNAJmM74+OAQAA"));
        }
        public void Import_Nested_SimplifiedReport( )
        {
            IEntityRepository     repository = Factory.EntityRepository;
            IEntityXmlImporter    importer   = Factory.EntityXmlImporter;
            EntityXmlImportResult result;
            string xml;
            long   entityId;
            Report report;

            // Import
            using (RunAsImportExportRole( ))
                using (Stream stream = GetStream("SimplifiedReport.xml"))
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        xml    = reader.ReadToEnd( );
                        result = importer.ImportXml(xml, EntityXmlImportSettings.Default);
                    }

            // Check
            Assert.That(result, Is.Not.Null);
            Assert.That(result.RootEntities, Is.Not.Null);
            entityId = result.RootEntities.Single( );

            report = repository.Get <Report>(entityId);
            try
            {
                Assert.That(report, Is.Not.Null);
                Assert.That(report.Name, Is.EqualTo("Simple herb"));
                ResourceReportNode rootNode = report.RootNode?.As <ResourceReportNode>( );
                Assert.That(rootNode, Is.Not.Null, "Root node");
                Assert.That(rootNode.ResourceReportNodeType, Is.Not.Null);
                Assert.That(rootNode.ResourceReportNodeType.Alias, Is.EqualTo("test:herb"));
                Assert.That(report.ReportColumns, Has.Count.EqualTo(1), "ReportColumns");
                ReportColumn column = report.ReportColumns.First( );
                Assert.That(column, Is.Not.Null, "Column");
                Assert.That(column.Name, Is.EqualTo("AA_Herb"));
                Assert.That(column.ColumnIsHidden == true, Is.True, "ColumnIsHidden");
                FieldExpression fieldExpr = column.ColumnExpression?.As <FieldExpression>( );
                Assert.That(fieldExpr, Is.Not.Null, "FieldExpression");
                Assert.That(fieldExpr.FieldExpressionField.Alias, Is.EqualTo("core:name"));
                Assert.That(fieldExpr.SourceNode?.Id, Is.EqualTo(rootNode?.Id), "SourceNode");
                Assert.That(column.ColumnGrouping, Has.Count.EqualTo(1), "ColumnGrouping");
                ReportRowGroup grouping = column.ColumnGrouping.First( );
                Assert.That(grouping, Is.Not.Null, "ColumnGrouping");
                Assert.That(grouping.GroupingPriority, Is.EqualTo(1), "GroupingPriority");
            }
            finally
            {
                Entity.Delete(entityId);
            }
        }
        public void Security_CheckRole( )
        {
            IEntityXmlImporter importer = Factory.EntityXmlImporter;
            string             xml;

            var user = Entity.Create <UserAccount>( );

            using (new SetUser(user))
                using (Stream stream = GetStream("AllFields.xml"))
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        xml = reader.ReadToEnd( );
                        importer.ImportXml(xml, EntityXmlImportSettings.Default);
                    }
        }
        public HttpResponseMessage <ImportResult> ImportXmlGetData([FromUri] string fileId, [FromUri] string fileName = null, [FromUri] bool ignoreDeps = false)
        {
            IEntityXmlImporter importer = Factory.EntityXmlImporter;

            EntityXmlImportResult serviceResult;

            // Decode settings
            var settings = new EntityXmlImportSettings
            {
                IgnoreMissingDependencies = ignoreDeps
            };

            // Import
            using (Stream stream = FileRepositoryHelper.GetTemporaryFileDataStream(fileId))
                using (var xmlReader = XmlReader.Create(stream))
                {
                    serviceResult = importer.ImportXml(xmlReader, settings);
                }

            // Format result
            ImportResult webResult;

            if (serviceResult.ErrorMessage != null)
            {
                webResult = new ImportResult
                {
                    Success = false,
                    Message = serviceResult.ErrorMessage
                };
            }
            else
            {
                IEntityRepository entityRepository = Factory.EntityRepository;
                var entities = entityRepository.Get <Resource>(serviceResult.RootEntities);

                webResult = new ImportResult
                {
                    Success  = true,
                    Entities = entities.Select(FormatEntity).ToList( )
                };
            }

            return(new HttpResponseMessage <ImportResult>(webResult));
        }
        public void RoundTrip( )
        {
            IEntityXmlImporter    importer = Factory.EntityXmlImporter;
            EntityXmlImportResult result;
            string xml;
            long   entityId;

            // Import
            using (RunAsImportExportRole())
                using (Stream stream = GetStream("SimplifiedReport.xml"))
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        xml    = reader.ReadToEnd( );
                        result = importer.ImportXml(xml, EntityXmlImportSettings.Default);
                    }
            entityId = result.RootEntities.Single( );

            // Export
            IEntityXmlExporter exporter = Factory.EntityXmlExporter;
            string             xml2     = exporter.GenerateXml(entityId, EntityXmlExportSettings.Default);
        }
        public void Import_Document( )
        {
            IEntityRepository     repository = Factory.EntityRepository;
            IEntityXmlImporter    importer   = Factory.EntityXmlImporter;
            EntityXmlImportResult result;
            string  xml;
            long    entityId;
            IEntity entity;

            // Import
            using (RunAsImportExportRole( ))
                using (Stream stream = GetStream("TestDocument.xml"))
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        xml    = reader.ReadToEnd( );
                        result = importer.ImportXml(xml, EntityXmlImportSettings.Default);
                    }

            // Check
            Assert.That(result, Is.Not.Null);
            Assert.That(result.RootEntities, Is.Not.Null);
            entityId = result.RootEntities.Single( );

            entity = repository.Get(entityId);
            try
            {
                string expectedHash = "RV6PPKR5NJHP4GU76KIZ2HXB5BX3SPRKDQAIWQL33W7ADWUEOUJQ";
                string actualHash   = entity.GetField <string>("core:fileDataHash");
                Assert.That(actualHash, Is.EqualTo(expectedHash));

                using (Stream binary = Factory.DocumentFileRepository.Get(actualHash))
                {
                    Assert.That(binary.Length, Is.EqualTo(11590));
                }
            }
            finally
            {
                entity.AsWritable( ).Delete( );
            }
        }
        public void Import_Binary( )
        {
            IEntityRepository     repository = Factory.EntityRepository;
            IEntityXmlImporter    importer   = Factory.EntityXmlImporter;
            EntityXmlImportResult result;
            string  xml;
            long    entityId;
            IEntity entity;

            // Import
            using (RunAsImportExportRole( ))
                using (Stream stream = GetStream("TestPhoto.xml"))
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        xml    = reader.ReadToEnd( );
                        result = importer.ImportXml(xml, EntityXmlImportSettings.Default);
                    }

            // Check
            Assert.That(result, Is.Not.Null);
            Assert.That(result.RootEntities, Is.Not.Null);
            entityId = result.RootEntities.Single( );

            entity = repository.Get(entityId);
            try
            {
                string expectedHash = "BN7ED5KVSPBOQQL2OELSONW25BI5MBPWS2JSRHQDIO2KW4UBGGMA";
                string actualHash   = entity.GetField <string>("core:fileDataHash");
                Assert.That(actualHash, Is.EqualTo(expectedHash));

                using (Stream binary = Factory.BinaryFileRepository.Get(actualHash))
                {
                    Assert.That(binary.Length, Is.EqualTo(398));
                }
            }
            finally
            {
                entity.AsWritable( ).Delete( );
            }
        }
        public void Export_Nested_SimplifiedReport( )
        {
            IEntityRepository     repository = Factory.EntityRepository;
            IEntityXmlImporter    importer   = Factory.EntityXmlImporter;
            EntityXmlImportResult result;
            string xml;
            long   entityId = 0;

            // Import
            using (RunAsImportExportRole())
                using (Stream stream = EntityXmlImporterTests.GetStream("SimplifiedReport.xml"))
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        xml    = reader.ReadToEnd( );
                        result = importer.ImportXml(xml, EntityXmlImportSettings.Default);
                    }

            try
            {
                entityId = result.RootEntities.Single( );

                // Export
                IEntityXmlExporter exporter = Factory.EntityXmlExporter;

                string xml2;
                using (RunAsImportExportRole( ))
                {
                    xml2 = exporter.GenerateXml(entityId, EntityXmlExportSettings.Default);
                }

                XmlDocument doc = new XmlDocument( );
                doc.LoadXml(xml2);

                XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
                // Note: can't get xpath to work with default namespace
                ns.AddNamespace("c", "core");
                ns.AddNamespace("k", "console");

                XmlElement r = doc.SelectSingleNode("//c:report", ns) as XmlElement;
                Assert.That(r, Is.Not.Null);

                Assert.That(r.SelectSingleNode("@id", ns)?.Value, Is.EqualTo("7faec068-162c-4e99-995b-e84f9832fae0"));
                Assert.That(r.SelectSingleNode("@typeId", ns), Is.Null);
                Assert.That(r.SelectSingleNode("c:name", ns)?.InnerText, Is.EqualTo("Simple herb"));
                Assert.That(r.SelectSingleNode("c:rootNode", ns), Is.Not.Null);
                Assert.That(r.SelectSingleNode("c:rootNode/c:resourceReportNode[@id='5e7c086c-08e5-4aa7-99dc-b4e94d787548']", ns), Is.Not.Null);
                Assert.That(r.SelectSingleNode("c:rootNode/c:resourceReportNode[@id='5e7c086c-08e5-4aa7-99dc-b4e94d787548']/c:resourceReportNodeType", ns)?.InnerText, Is.EqualTo("a7bf22ab-6834-4d31-8133-5795acb27d69"));

                XmlElement col = r.SelectSingleNode("c:reportColumns/c:reportColumn[@id='1bb4d52c-0900-435e-9afd-dfb0a6c98b15']", ns) as XmlElement;
                Assert.That(col, Is.Not.Null);
                Assert.That(col.SelectSingleNode("c:name", ns)?.InnerText, Is.EqualTo("AA_Herb"));
                Assert.That(col.SelectSingleNode("c:columnIsHidden", ns)?.InnerText, Is.EqualTo("True"));
                Assert.That(col.SelectSingleNode("c:columnExpression", ns), Is.Not.Null);
                Assert.That(col.SelectSingleNode("c:columnExpression/c:fieldExpression[@id='1059aca5-d937-4876-9e54-661e95c14e0a']", ns), Is.Not.Null);
                Assert.That(col.SelectSingleNode("c:columnExpression/c:fieldExpression[@id='1059aca5-d937-4876-9e54-661e95c14e0a']/c:fieldExpressionField", ns)?.InnerText, Is.EqualTo("name"));
                Assert.That(col.SelectSingleNode("c:columnExpression/c:fieldExpression[@id='1059aca5-d937-4876-9e54-661e95c14e0a']/c:sourceNode", ns)?.InnerText, Is.EqualTo("5e7c086c-08e5-4aa7-99dc-b4e94d787548"));
                Assert.That(col.SelectSingleNode("c:columnGrouping/c:reportRowGroup[@id='22bf140b-78e6-4ca7-8169-3d817a8eb1d7']/c:groupingMethod", ns)?.InnerText, Is.EqualTo("groupList"));

                XmlElement a = doc.SelectSingleNode("//c:aliasMap", ns) as XmlElement;
                CheckAlias(a, ns, "c:columnExpression", "b4d64bef-e364-4786-ba7e-4a6b2c62d163", "rel");
            }
            finally
            {
                Entity.Delete(entityId);
            }
        }