protected override void beforeEach()
 {
     view1 = ViewForModel <ViewModel1>();
     view2 = ViewForModel <ViewModel2>();
     view3 = ViewForModel <ViewModel3>();
     view4 = ViewForModel <ViewModel4>();
 }
예제 #2
0
        public static void Push(HttpContextBase context, ITemplateFile template)
        {
            Precondition.Require(context, () => Error.ArgumentNull("context"));
            Precondition.Require(template, () => Error.ArgumentNull("template"));

            Stack(context).Push(template);
        }
예제 #3
0
		public static void Push(HttpContextBase context, ITemplateFile template)
		{
			Precondition.Require(context, () => Error.ArgumentNull("context"));
			Precondition.Require(template, () => Error.ArgumentNull("template"));

			Stack(context).Push(template);
		}
예제 #4
0
 public void SetUp()
 {
     view1 = ViewForModel <ViewModel1>();
     view2 = ViewForModel <ViewModel2>();
     view3 = ViewForModel <ViewModel3>();
     view4 = ViewForModel <ViewModel4>();
 }
        private async Task SyncCategories()
        {
            using (ProvisioningAppDBContext context = GetContext())
            {
                // Find the category file
                ITemplateFile file = (await _cloneProvider.GetAsync(SYSTEM_PATH, WriteLog)).FindFile(CATEGORIES_NAME);
                if (file == null)
                {
                    throw new InvalidOperationException($"Cannot find file {CATEGORIES_NAME}");
                }

                // Deserialize the json
                var categories = await file.DownloadAsJsonAsync(new
                {
                    categories = new[]
                    {
                        new { id = "", displayName = "" }
                    }
                });

                var existingDbCategories = context.Categories.ToDictionary(c => c.Id, StringComparer.OrdinalIgnoreCase);
                foreach (var category in categories.categories)
                {
                    // Update category, if already exists
                    if (existingDbCategories.TryGetValue(category.id, out Category dbCategory))
                    {
                        dbCategory.DisplayName          = category.displayName;
                        context.Entry(dbCategory).State = EntityState.Modified;
                    }
                    else
                    {
                        // Add new category
                        dbCategory = new Category
                        {
                            Id          = category.id,
                            DisplayName = category.displayName
                        };
                        context.Entry(dbCategory).State = EntityState.Added;
                    }

                    existingDbCategories.Remove(category.id);
                }

                // Remove exceed categories
                var objectStateManager = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager;
                foreach (var dbCategory in existingDbCategories)
                {
                    await context.Entry(dbCategory.Value).Collection(d => d.Packages).LoadAsync();

                    foreach (var dbPackage in dbCategory.Value.Packages.ToArray())
                    {
                        objectStateManager.ChangeRelationshipState(dbCategory.Value, dbPackage, d => d.Packages, EntityState.Deleted);
                    }

                    context.Entry(dbCategory.Value).State = EntityState.Deleted;
                }

                await context.SaveChangesAsync();
            }
        }
예제 #6
0
        private async Task SyncPlatforms()
        {
            using (ProvisioningAppDBContext context = GetContext())
            {
                // Find the platforms file
                ITemplateFile file = (await _cloneProvider.GetAsync(SYSTEM_PATH, WriteLog)).FindFile(PLATFORMS_NAME);
                if (file == null)
                {
                    throw new InvalidOperationException($"Cannot find file {PLATFORMS_NAME}");
                }

                // Deserialize the json
                var platforms = await file.DownloadAsJsonAsync(new
                {
                    platforms = new[]
                    {
                        new { id = "", displayName = "" }
                    }
                });

                var existingDbPlatforms = context.Platforms.ToDictionary(c => c.Id, StringComparer.OrdinalIgnoreCase);
                foreach (var platform in platforms.platforms)
                {
                    // Update platform, if already exists
                    if (existingDbPlatforms.TryGetValue(platform.id, out Platform dbPlatform))
                    {
                        dbPlatform.DisplayName          = platform.displayName;
                        context.Entry(dbPlatform).State = EntityState.Modified;
                    }
                    else
                    {
                        // Add new platform
                        dbPlatform = new Platform
                        {
                            Id          = platform.id,
                            DisplayName = platform.displayName,
                        };
                        context.Entry(dbPlatform).State = EntityState.Added;
                    }

                    existingDbPlatforms.Remove(platform.id);
                }

                // Remove exceed platforms
                var objectStateManager = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager;
                foreach (var dbPlatform in existingDbPlatforms)
                {
                    await context.Entry(dbPlatform.Value).Collection(p => p.Packages).LoadAsync();

                    foreach (var dbPackage in dbPlatform.Value.Packages.ToArray())
                    {
                        objectStateManager.ChangeRelationshipState(dbPlatform.Value, dbPackage, p => p.Packages, EntityState.Deleted);
                    }

                    context.Entry(dbPlatform.Value).State = EntityState.Deleted;
                }

                await context.SaveChangesAsync();
            }
        }
예제 #7
0
        private async Task <string> GetFileContentAsync(string path, string fileName)
        {
            ITemplateFile contentFile = (await _sourceProvider.GetAsync(path, WriteLog)).FindFile(fileName);

            if (contentFile == null)
            {
                return(null);
            }

            ITemplateFile cloneContentFile = (await _cloneProvider.GetAsync(path, WriteLog)).FindFile(fileName);

            // Get the file content
            using (var httpClient = new HttpClient())
            {
                // Get the content
                var contentStream = await contentFile.DownloadAsync();

                using (var sr = new StreamReader(contentStream))
                {
                    var content = await sr.ReadToEndAsync();

                    // Change relative uris
                    return(ChangeUris(cloneContentFile.DownloadUri, content));
                }
            }
        }
예제 #8
0
        private static IPackageLog getPackageLogger(ITemplateFile template)
        {
            if (PackageRegistry.Diagnostics == null)
            {
                return(new PackageLog());
            }

            return(PackageRegistry.Diagnostics.LogFor(template));
        }
예제 #9
0
 public static void Push(HttpContextBase httpContext, ITemplateFile templateFile) {
     if (templateFile == null) {
         throw new ArgumentNullException("templateFile");
     }
     if (httpContext == null) {
         throw new ArgumentNullException("httpContext");
     }
     GetStack(httpContext).Push(templateFile);
 }
        private async Task SyncFirstReleaseTenants()
        {
            using (ProvisioningAppDBContext context = GetContext())
            {
                // Find the category file
                ITemplateFile file = (await _cloneProvider.GetAsync(SYSTEM_PATH, WriteLog)).FindFile(TENANTS_NAME);
                if (file == null)
                {
                    throw new InvalidOperationException($"Cannot find file {TENANTS_NAME}");
                }

                // Deserialize the json
                var tenantsList = await file.DownloadAsJsonAsync(new
                {
                    tenants = new[]
                    {
                        new { id = "", tenantName = "", referenceOwner = "" }
                    }
                });

                var existingDbTenants = context.Tenants.ToDictionary(t => t.Id, StringComparer.OrdinalIgnoreCase);
                foreach (var tenant in tenantsList.tenants)
                {
                    // Update tenant, if already exists
                    if (existingDbTenants.TryGetValue(tenant.id, out Tenant dbTenant))
                    {
                        dbTenant.TenantName           = tenant.tenantName;
                        dbTenant.ReferenceOwner       = tenant.referenceOwner;
                        context.Entry(dbTenant).State = EntityState.Modified;
                    }
                    else
                    {
                        // Add new tenant
                        dbTenant = new Tenant
                        {
                            Id             = tenant.id,
                            TenantName     = tenant.tenantName,
                            ReferenceOwner = tenant.referenceOwner
                        };
                        context.Entry(dbTenant).State = EntityState.Added;
                    }

                    existingDbTenants.Remove(tenant.id);
                }

                // Remove exceed categories
                var objectStateManager = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager;
                foreach (var dbTenant in existingDbTenants)
                {
                    context.Entry(dbTenant.Value).State = EntityState.Deleted;
                }

                await context.SaveChangesAsync();
            }
        }
예제 #11
0
 internal static string ResolvePath(ITemplateFile templateFile, HttpContextBase httpContext, string virtualPath) {
     Debug.Assert(!String.IsNullOrEmpty(virtualPath));
     string basePath;
     if (templateFile != null) {
         // If a page is available resolve paths relative to it.
         basePath = templateFile.TemplateInfo.VirtualPath;
     }
     else {
         basePath = httpContext.Request.AppRelativeCurrentExecutionFilePath;
     }
     return VirtualPathUtility.Combine(basePath, virtualPath);
 }
예제 #12
0
 public static void Push(HttpContextBase httpContext, ITemplateFile templateFile)
 {
     if (templateFile == null)
     {
         throw new ArgumentNullException("templateFile");
     }
     if (httpContext == null)
     {
         throw new ArgumentNullException("httpContext");
     }
     GetStack(httpContext).Push(templateFile);
 }
예제 #13
0
        public static async Task <T> DownloadAsJsonAsync <T>(this ITemplateFile file, T sample)
        {
            string json;

            // Download the file
            using (Stream stream = await file.DownloadAsync())
            {
                json = await new StreamReader(stream).ReadToEndAsync();
            }

            // Deserialize the json
            return(JsonConvert.DeserializeAnonymousType(json, sample));
        }
예제 #14
0
        internal static string ResolvePath(ITemplateFile templateFile, HttpContextBase httpContext, string virtualPath)
        {
            Debug.Assert(!String.IsNullOrEmpty(virtualPath));
            string basePath;

            if (templateFile != null)
            {
                // If a page is available resolve paths relative to it.
                basePath = templateFile.TemplateInfo.VirtualPath;
            }
            else
            {
                basePath = httpContext.Request.AppRelativeCurrentExecutionFilePath;
            }
            return(VirtualPathUtility.Combine(basePath, virtualPath));
        }
예제 #15
0
        private async Task <string> GetHtmlContentAsync(string path, string fileName)
        {
            IMarkdownFile contentFile = (await _sourceProvider.GetAsync(path, WriteLog)).FindFile(fileName) as IMarkdownFile;

            if (contentFile == null)
            {
                return(null);
            }

            ITemplateFile cloneContentFile = (await _cloneProvider.GetAsync(path, WriteLog)).FindFile(fileName);

            // Get the markdown
            using (var httpClient = new HttpClient())
            {
                // Get html
                string html = await contentFile.GetHtmlAsync();

                // Change relative uris
                return(ChangeUris(cloneContentFile.DownloadUri, html));
            }
        }
예제 #16
0
        private async Task <string> GetDescriptionAsync(string path)
        {
            IMarkdownFile readmeFile = (await _sourceProvider.GetAsync(path, WriteLog)).FindFile(README_NAME) as IMarkdownFile;

            if (readmeFile == null)
            {
                return(null);
            }

            ITemplateFile cloneReadmeFile = (await _cloneProvider.GetAsync(path, WriteLog)).FindFile(README_NAME);

            // Get the markdown
            using (var httpClient = new HttpClient())
            {
                // Get html
                string html = await readmeFile.GetHtmlAsync();

                // Change relative uris
                return(ChangeUris(cloneReadmeFile.DownloadUri, html));
            }
        }
 protected override void beforeEach()
 {
     view1 = ViewForModel<ViewModel1>();
     view2 = ViewForModel<ViewModel2>();
     view3 = ViewForModel<ViewModel3>();
     view4 = ViewForModel<ViewModel4>();
 }
예제 #18
0
 public void Log(ITemplateFile template, string text)
 {
     _trace(template, text);
 }
예제 #19
0
 public static bool FromHost(this ITemplateFile template)
 {
     return(template.Origin == TemplateConstants.HostOrigin);
 }
예제 #20
0
        private async Task FillPackageAsync(DomainModel.Package package, ITemplateFile packageFile)
        {
            using (Stream stream = await packageFile.DownloadAsync())
            {
                // Crate a copy of the source stream
                MemoryStream mem = new MemoryStream();
                await stream.CopyToAsync(mem);

                mem.Position = 0;

                // Prepare the output hierarchy
                ProvisioningHierarchy hierarchy = null;

                if (packageFile.Path.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase))
                {
                    // That's an XML Provisioning Template file

                    XDocument xml = XDocument.Load(mem);
                    mem.Position = 0;

                    // Deserialize the stream into a provisioning hierarchy reading any
                    // dependecy with the Azure Blob Storage connector
                    var formatter           = XMLPnPSchemaFormatter.GetSpecificFormatter(xml.Root.Name.NamespaceName);
                    var templateLocalFolder = $"{ConfigurationManager.AppSettings["BlobTemplatesProvider:ContainerName"]}/{packageFile.Path.Substring(0, packageFile.Path.LastIndexOf('/'))}";

                    var provider = new XMLAzureStorageTemplateProvider(
                        ConfigurationManager.AppSettings["BlobTemplatesProvider:ConnectionString"],
                        templateLocalFolder);
                    formatter.Initialize(provider);

                    // Get the full hierarchy
                    hierarchy = ((IProvisioningHierarchyFormatter)formatter).ToProvisioningHierarchy(mem);
                }
                else if (packageFile.Path.EndsWith(".pnp", StringComparison.InvariantCultureIgnoreCase))
                {
                    // That's a PnP Package file

                    // Get a provider based on the in-memory .PNP Open XML file
                    OpenXMLConnector    openXmlConnector = new OpenXMLConnector(mem);
                    XMLTemplateProvider provider         = new XMLOpenXMLTemplateProvider(
                        openXmlConnector);

                    // Get the .xml provisioning template file name
                    var xmlTemplateFileName = openXmlConnector.Info?.Properties?.TemplateFileName ??
                                              packageFile.Path.Substring(packageFile.Path.LastIndexOf('/') + 1)
                                              .ToLower().Replace(".pnp", ".xml");

                    // Get the full hierarchy
                    hierarchy = provider.GetHierarchy(xmlTemplateFileName);
                }

                if (hierarchy != null)
                {
                    // We se the DisplayName to the DisplayName of the hierarchy if we don't have a siteTitle in the settings.json file
                    if (string.IsNullOrEmpty(package.DisplayName))
                    {
                        package.DisplayName = hierarchy.DisplayName;
                    }
                    package.ImagePreviewUrl = ChangeUri(packageFile.DownloadUri, hierarchy?.ImagePreviewUrl ?? String.Empty);
                    package.Description     = await GetDescriptionAsync(packageFile.GetDirectoryPath()) ?? hierarchy?.Description ?? "";

                    package.Version           = hierarchy?.Version.ToString();
                    package.PackageProperties = JsonConvert.SerializeObject(hierarchy.Parameters);
                }
            }
        }
예제 #21
0
 public static bool IsPartial(this ITemplateFile template)
 {
     return(Path.GetFileName(template.FilePath).StartsWith("_"));
 }
예제 #22
0
 public static string GetDirectoryPath(this ITemplateFile file)
 {
     return(Path.GetDirectoryName(file.Path).Replace("\\", "/"));
 }
        private async Task <DomainModel.Package> GetPackageAsync(ITemplateFolder folder, ProvisioningAppDBContext context)
        {
            var items = await _cloneProvider.GetAsync(folder.Path, WriteLog);

            // Read settings file
            ITemplateFile settingsFile = items.OfType <ITemplateFile>().FindFile(SETTINGS_NAME);

            if (settingsFile == null)
            {
                WriteLog($"Cannot find file {SETTINGS_NAME}");
                return(null);
            }

            var settings = await settingsFile.DownloadAsJsonAsync(new
            {
                @abstract         = "",
                sortOrder         = 0,
                categories        = new string[0],
                packageFile       = "",
                promoted          = false,
                sortOrderPromoted = 0,
                preview           = false,
                metadata          = new {
                    properties = new[] {
                        new {
                            name           = "",
                            caption        = "",
                            description    = "",
                            editor         = "",
                            editorSettings = "",
                        }
                    }
                }
            });

            // Read the package file
            ITemplateFile packageFile = items.FindFile(settings.packageFile);

            if (packageFile == null)
            {
                WriteLog($"Cannot find file {settings.packageFile}");
                return(null);
            }

            var package = new DomainModel.Package
            {
                Id         = Guid.NewGuid(),
                PackageUrl = packageFile.DownloadUri.ToString(),
                // New properties for Wave2
                Promoted           = settings.promoted,
                Preview            = settings.preview,
                TimesApplied       = 0,
                PropertiesMetadata = JsonConvert.SerializeObject(settings.metadata),
                // New properties for Wave 5
                Abstract              = settings.@abstract,
                SortOrder             = settings.sortOrder,
                SortOrderPromoted     = settings.sortOrderPromoted,
                RepositoryRelativeUrl = folder.Path,
            };

            // Read the instructions.md and the provisioning.md files
            String instructionsContent = await GetHtmlContentAsync(folder.Path, INSTRUCTIONS_NAME);

            String provisioningContent = await GetHtmlContentAsync(folder.Path, PROVISIONING_NAME);

            package.Instructions   = instructionsContent;
            package.ProvisionRecap = provisioningContent;

            // Find the categories to apply
            var dbCategories = settings.categories.Select(c =>
            {
                Category dbCategory = context.Categories.Find(c);
                if (dbCategory == null)
                {
                    WriteLog($"Cannot find category with id {c}");
                }

                return(dbCategory);
            }).ToArray();

            package.Categories.AddRange(dbCategories);

            // Find then author and fill his informations
            await FillAuthorAsync(package, packageFile.Path);

            // Open the package and set info
            await FillPackageAsync(package, packageFile);

            return(package);
        }
예제 #24
0
 public void Log(ITemplateFile template, string format, params object[] args)
 {
     _format(template, format, args);
 }
예제 #25
0
 public void Log(ITemplateFile template, string text)
 {
 }
예제 #26
0
 public static string Name(this ITemplateFile template)
 {
     return(Path.GetFileNameWithoutExtension(template.FilePath));
 }
예제 #27
0
 public void Log(ITemplateFile template, string text) { }
예제 #28
0
 private static void trace(ITemplateFile template, string text)
 {
     getPackageLogger(template).Trace(text);
 }
예제 #29
0
 private static void formatTrace(ITemplateFile template, string format, object[] args)
 {
     getPackageLogger(template).Trace(format, args);
 }
예제 #30
0
        private static IPackageLog getPackageLogger(ITemplateFile template)
        {
            if (PackageRegistry.Diagnostics == null) return new PackageLog();

            return PackageRegistry.Diagnostics.LogFor(template);
        }
예제 #31
0
 public TemplateVirtualFile(string virtualPath)
     : base(virtualPath)
 {
     _virtualPath = virtualPath;
     _templateFile = new TemplateFile();
 }
예제 #32
0
        private async Task <DomainModel.Package> GetPackageAsync(ITemplateFolder folder, ProvisioningAppDBContext context)
        {
            var items = await _cloneProvider.GetAsync(folder.Path, WriteLog);

            // Read settings file
            ITemplateFile settingsFile = items.OfType <ITemplateFile>().FindFile(SETTINGS_NAME);

            if (settingsFile == null)
            {
                WriteLog($"Cannot find file {SETTINGS_NAME}");
                return(null);
            }

            #region Prepare the settings file and its outline

            var settings = await settingsFile.DownloadAsJsonAsync(new TemplateSettings());

            #endregion

            // Read the package file
            ITemplateFile packageFile = items.FindFile(settings.packageFile);
            if (packageFile == null)
            {
                WriteLog($"Cannot find file {settings.packageFile}");
                return(null);
            }

            #region Fix the Preview Image URLs

            // Fix the URLs in the metadata settings
            if (settings?.metadata?.displayInfo?.previewImages != null)
            {
                int previewImagesCount = settings.metadata.displayInfo.previewImages.Length;
                for (var n = 0; n < previewImagesCount; n++)
                {
                    var previewImageUrl = settings.metadata.displayInfo.previewImages[n].url;
                    settings.metadata.displayInfo.previewImages[n].url =
                        ChangeUri(packageFile.DownloadUri, previewImageUrl);
                }
            }

            if (settings?.metadata?.displayInfo?.detailItemCategories != null)
            {
                int detailItemCategoriesCount = settings.metadata.displayInfo.detailItemCategories.Length;
                for (var n = 0; n < detailItemCategoriesCount; n++)
                {
                    if (settings.metadata.displayInfo.detailItemCategories[n].items != null)
                    {
                        var detailItemCategoryItemsCount = settings.metadata.displayInfo.detailItemCategories[n].items.Length;
                        for (var m = 0; m < detailItemCategoryItemsCount; m++)
                        {
                            var detailItemCategoryItemPreviewImageUrl = settings.metadata.displayInfo.detailItemCategories[n].items[m].previewImage;
                            if (!String.IsNullOrEmpty(detailItemCategoryItemPreviewImageUrl))
                            {
                                settings.metadata.displayInfo.detailItemCategories[n].items[m].previewImage =
                                    ChangeUri(packageFile.DownloadUri, detailItemCategoryItemPreviewImageUrl);
                            }
                        }
                    }
                }
            }

            #endregion

            var package = new DomainModel.Package
            {
                Id         = Guid.NewGuid(),
                PackageUrl = packageFile.DownloadUri.ToString(),
                // New properties for Wave2
                Promoted           = settings.promoted,
                Preview            = settings.preview,
                TimesApplied       = 0,
                PropertiesMetadata = JsonConvert.SerializeObject(settings.metadata),
                // New properties for Wave 5
                Abstract                   = settings.@abstract,
                SortOrder                  = settings.sortOrder,
                SortOrderPromoted          = settings.sortOrderPromoted,
                RepositoryRelativeUrl      = folder.Path,
                MatchingSiteBaseTemplateId = settings.matchingSiteBaseTemplateId,
                ForceNewSite               = settings.forceNewSite,
                Visible        = settings.visible,
                PageTemplateId = settings.metadata?.displayInfo?.pageTemplateId,
            };

            // Read the instructions.md and the provisioning.md files
            String instructionsContent = await GetHtmlContentAsync(folder.Path, INSTRUCTIONS_NAME);

            String provisioningContent = await GetHtmlContentAsync(folder.Path, PROVISIONING_NAME);

            package.Instructions   = instructionsContent;
            package.ProvisionRecap = provisioningContent;

            // Find the categories to apply
            if (settings.categories != null && settings.categories.Length > 0)
            {
                var dbCategories = settings.categories.Select(c =>
                {
                    Category dbCategory = context.Categories.Find(c);
                    if (dbCategory == null)
                    {
                        WriteLog($"Cannot find category with id {c}");
                    }

                    return(dbCategory);
                }).ToArray();
                package.Categories.AddRange(dbCategories);
            }

            // Find the platforms to apply
            if (settings.platforms != null && settings.platforms.Length > 0)
            {
                var dbPlatforms = settings.platforms.Select(p =>
                {
                    Platform dbPlatform = context.Platforms.Find(p);
                    if (dbPlatform == null)
                    {
                        WriteLog($"Cannot find platform with id {p}");
                    }

                    return(dbPlatform);
                }).ToArray();
                package.TargetPlatforms.AddRange(dbPlatforms);
            }

            // Find then author and fill his informations
            await FillAuthorAsync(package, packageFile.Path);

            // Open the package and set info
            await FillPackageAsync(package, packageFile);

            return(package);
        }
예제 #33
0
 public void Log(ITemplateFile template, string text)
 {
     _trace(template, text);
 }
예제 #34
0
 private static IPackageLog getPackageLogger(ITemplateFile template)
 {
     return PackageRegistry.Diagnostics.LogFor(template);
 }
예제 #35
0
 public static bool IsRazorView(this ITemplateFile template)
 {
     return(template.FilePath.FileExtension().EqualsIgnoreCase(".cshtml") ||
            template.FilePath.FileExtension().EqualsIgnoreCase(".vbhtml"));
 }
예제 #36
0
 public static string RelativePath(this ITemplateFile template)
 {
     return(template.FilePath.PathRelativeTo(template.RootPath));
 }
예제 #37
0
 private static void formatTrace(ITemplateFile template, string format, object[] args)
 {
     getPackageLogger(template).Trace(format, args);
 }
예제 #38
0
        private async Task <DomainModel.Package> GetPackageAsync(ITemplateFolder folder, ProvisioningAppDBContext context)
        {
            var items = await _cloneProvider.GetAsync(folder.Path, WriteLog);

            // Read settings file
            ITemplateFile settingsFile = items.OfType <ITemplateFile>().FindFile(SETTINGS_NAME);

            if (settingsFile == null)
            {
                WriteLog($"Cannot find file {SETTINGS_NAME}");
                return(null);
            }

            #region Prepare the settings file and its outline

            var settings = await settingsFile.DownloadAsJsonAsync(new TemplateSettings());

            #endregion

            // Read the package file
            ITemplateFile packageFile = items.FindFile(settings.packageFile);
            if (packageFile == null)
            {
                WriteLog($"Cannot find file {settings.packageFile}");
                return(null);
            }

            #region Fix the Preview Image URLs

            // Fix the URLs in the metadata settings
            if (settings?.metadata?.displayInfo?.previewImages != null)
            {
                int previewImagesCount = settings.metadata.displayInfo.previewImages.Length;
                for (var n = 0; n < previewImagesCount; n++)
                {
                    var previewImageUrl = settings.metadata.displayInfo.previewImages[n].url;
                    settings.metadata.displayInfo.previewImages[n].url =
                        ChangeUri(packageFile.DownloadUri, previewImageUrl);
                }
            }

            if (settings?.metadata?.displayInfo?.detailItemCategories != null)
            {
                int detailItemCategoriesCount = settings.metadata.displayInfo.detailItemCategories.Length;
                for (var n = 0; n < detailItemCategoriesCount; n++)
                {
                    if (settings.metadata.displayInfo.detailItemCategories[n].items != null)
                    {
                        var detailItemCategoryItemsCount = settings.metadata.displayInfo.detailItemCategories[n].items.Length;
                        for (var m = 0; m < detailItemCategoryItemsCount; m++)
                        {
                            var detailItemCategoryItemPreviewImageUrl = settings.metadata.displayInfo.detailItemCategories[n].items[m].previewImage;
                            if (!String.IsNullOrEmpty(detailItemCategoryItemPreviewImageUrl))
                            {
                                settings.metadata.displayInfo.detailItemCategories[n].items[m].previewImage =
                                    ChangeUri(packageFile.DownloadUri, detailItemCategoryItemPreviewImageUrl);
                            }
                        }
                    }
                }
            }

            #endregion

            var package = new DomainModel.Package
            {
                Id         = !string.IsNullOrEmpty(settings.templateId) ? new Guid(settings.templateId) : Guid.NewGuid(),
                PackageUrl = packageFile.DownloadUri.ToString(),
                // New properties for Wave2
                Promoted           = settings.promoted,
                Preview            = settings.preview,
                TimesApplied       = 0,
                PropertiesMetadata = JsonConvert.SerializeObject(settings.metadata),
                // New properties for Wave 5
                Abstract                   = settings.@abstract,
                SortOrder                  = settings.sortOrder,
                SortOrderPromoted          = settings.sortOrderPromoted,
                RepositoryRelativeUrl      = folder.Path,
                MatchingSiteBaseTemplateId = settings.matchingSiteBaseTemplateId,
                ForceNewSite               = settings.forceNewSite,
                Visible        = settings.visible,
                PageTemplateId = settings.metadata?.displayInfo?.pageTemplateId,
                // New properties for Wave 12
                DisplayName       = settings.metadata?.displayInfo?.siteTitle,
                ForceExistingSite = settings.forceExistingSite,
            };

            // Read the instructions.md and the provisioning.md files
            String instructionsContent = await GetHtmlContentAsync(folder.Path, INSTRUCTIONS_NAME);

            String provisioningContent = await GetHtmlContentAsync(folder.Path, PROVISIONING_NAME);

            package.Instructions   = instructionsContent;
            package.ProvisionRecap = provisioningContent;

            // Read any pre-requirement content files
            var preRequirementContents = items.FindFiles(i =>
                                                         i.Path.ToLower().Contains("prerequirement-") &&
                                                         i.Path.EndsWith(".md", StringComparison.InvariantCultureIgnoreCase));

            // Process content for pre-requirements, if any
            if (preRequirementContents != null)
            {
                // Get the existing content pages for the current folder
                var existingDbContentPages = context.ContentPages
                                             .ToList()
                                             .Where(cp => cp.Id.StartsWith(folder.Path, StringComparison.InvariantCultureIgnoreCase))
                                             .ToDictionary(cp => cp.Id, StringComparer.OrdinalIgnoreCase);

                foreach (var prc in preRequirementContents)
                {
                    // Get the file content
                    String fileContent = await GetHtmlContentAsync(folder.Path, prc.Path.Substring(prc.Path.LastIndexOf('/') + 1));

                    // Update Content Page, if already exists
                    if (existingDbContentPages.TryGetValue(prc.Path, out ContentPage dbContentPage))
                    {
                        dbContentPage.Content = fileContent;
                        context.Entry(dbContentPage).State = EntityState.Modified;
                    }
                    else
                    {
                        // Add new Content Page
                        dbContentPage = new ContentPage
                        {
                            Id      = prc.Path,
                            Content = fileContent,
                        };
                        context.Entry(dbContentPage).State = EntityState.Added;
                    }

                    existingDbContentPages.Remove(prc.Path);
                }

                // Remove leftover content pages, if any
                var objectStateManager = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager;
                foreach (var dbContentPage in existingDbContentPages)
                {
                    context.Entry(dbContentPage.Value).State = EntityState.Deleted;
                }
            }

            // Find the categories to apply
            if (settings.categories != null && settings.categories.Length > 0)
            {
                var dbCategories = settings.categories.Select(c =>
                {
                    Category dbCategory = context.Categories.Find(c);
                    if (dbCategory == null)
                    {
                        WriteLog($"Cannot find category with id {c}");
                    }

                    return(dbCategory);
                }).ToArray();
                package.Categories.AddRange(dbCategories);
            }

            // Find the platforms to apply
            if (settings.platforms != null && settings.platforms.Length > 0)
            {
                var dbPlatforms = settings.platforms.Select(p =>
                {
                    Platform dbPlatform = context.Platforms.Find(p);
                    if (dbPlatform == null)
                    {
                        WriteLog($"Cannot find platform with id {p}");
                    }

                    return(dbPlatform);
                }).ToArray();
                package.TargetPlatforms.AddRange(dbPlatforms);
            }

            // Find then author and fill her/his information
            await FillAuthorAsync(package, packageFile.Path);

            // Open the package and set info
            await FillPackageAsync(package, packageFile);

            return(package);
        }
예제 #39
0
 private static void trace(ITemplateFile template, string text)
 {
     getPackageLogger(template).Trace(text);
 }
예제 #40
0
 public ViewWriter(ITemplateFile view)
 {
     _view = view;
 }
예제 #41
0
 private IActivationLog getPackageLogger(ITemplateFile template)
 {
     return(_diagnostics.LogFor(template));
 }
예제 #42
0
 private IActivationLog getPackageLogger(ITemplateFile template)
 {
     return _diagnostics.LogFor(template);
 }
예제 #43
0
 public void Log(ITemplateFile template, string format, params object[] args)
 {
     _format(template, format, args);
 }