internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper) {
            ViewDataDictionary viewData = html.ViewContext.ViewData;
            TemplateInfo templateInfo = viewData.TemplateInfo;
            ModelMetadata modelMetadata = viewData.ModelMetadata;
            StringBuilder builder = new StringBuilder();

            if (modelMetadata.Model == null) {    // DDB #225237
                return modelMetadata.NullDisplayText;
            }

            if (templateInfo.TemplateDepth > 1) {    // DDB #224751
                return modelMetadata.SimpleDisplayText;
            }

            foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => pm.ShowForDisplay && !templateInfo.Visited(pm))) {
                if (!propertyMetadata.HideSurroundingChrome) {
                    string label = propertyMetadata.GetDisplayName();
                    if (!String.IsNullOrEmpty(label)) {
                        builder.AppendFormat(CultureInfo.InvariantCulture, "<div class=\"display-label\">{0}</div>", label);
                        builder.AppendLine();
                    }

                    builder.Append("<div class=\"display-field\">");
                }

                builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.ReadOnly));

                if (!propertyMetadata.HideSurroundingChrome) {
                    builder.AppendLine("</div>");
                }
            }

            return builder.ToString();
        }
        internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper) {
            ViewDataDictionary viewData = html.ViewContext.ViewData;
            TemplateInfo templateInfo = viewData.TemplateInfo;
            ModelMetadata modelMetadata = viewData.ModelMetadata;
            StringBuilder builder = new StringBuilder();

            if (templateInfo.TemplateDepth > 1) {    // DDB #224751
                return modelMetadata.Model == null ? modelMetadata.NullDisplayText : modelMetadata.SimpleDisplayText;
            }

            foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => pm.ShowForEdit && !templateInfo.Visited(pm))) {
                if (!propertyMetadata.HideSurroundingChrome) {
                    string label = LabelExtensions.LabelHelper(html, propertyMetadata, propertyMetadata.PropertyName).ToHtmlString();
                    if (!String.IsNullOrEmpty(label)) {
                        builder.AppendFormat(CultureInfo.InvariantCulture, "<div class=\"editor-label\">{0}</div>\r\n", label);
                    }

                    builder.Append("<div class=\"editor-field\">");
                }

                builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.Edit));

                if (!propertyMetadata.HideSurroundingChrome) {
                    builder.Append(" ");
                    builder.Append(html.ValidationMessage(propertyMetadata.PropertyName, "*"));
                    builder.Append("</div>\r\n");
                }
            }

            return builder.ToString();
        }
        internal static string CollectionTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper)
        {
            ViewDataDictionary viewData = html.ViewContext.ViewData;
            object model = viewData.ModelMetadata.Model;
            if (model == null)
            {
                return String.Empty;
            }

            IEnumerable collection = model as IEnumerable;
            if (collection == null)
            {
                throw new InvalidOperationException(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        MvcResources.Templates_TypeMustImplementIEnumerable,
                        model.GetType().FullName));
            }

            Type typeInCollection = typeof(string);
            Type genericEnumerableType = TypeHelpers.ExtractGenericInterface(collection.GetType(), typeof(IEnumerable<>));
            if (genericEnumerableType != null)
            {
                typeInCollection = genericEnumerableType.GetGenericArguments()[0];
            }
            bool typeInCollectionIsNullableValueType = TypeHelpers.IsNullableValueType(typeInCollection);

            string oldPrefix = viewData.TemplateInfo.HtmlFieldPrefix;

            try
            {
                viewData.TemplateInfo.HtmlFieldPrefix = String.Empty;

                string fieldNameBase = oldPrefix;
                StringBuilder result = new StringBuilder();
                int index = 0;

                foreach (object item in collection)
                {
                    Type itemType = typeInCollection;
                    if (item != null && !typeInCollectionIsNullableValueType)
                    {
                        itemType = item.GetType();
                    }
                    ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => item, itemType);
                    string fieldName = String.Format(CultureInfo.InvariantCulture, "{0}[{1}]", fieldNameBase, index++);
                    string output = templateHelper(html, metadata, fieldName, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */);
                    result.Append(output);
                }

                return result.ToString();
            }
            finally
            {
                viewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;
            }
        }
예제 #4
0
        public void GeneratedSnippet_DoesNotContainCollectStatic_IfDisableCollectStatic_IsTrue()
        {
            // Arrange
            var snippetProps = new PythonBashBuildSnippetProperties(
                virtualEnvironmentName: null,
                virtualEnvironmentModule: null,
                virtualEnvironmentParameters: null,
                packagesDirectory: "packages_dir",
                disableCollectStatic: true);

            // Act
            var text = TemplateHelpers.Render(TemplateHelpers.TemplateResource.PythonSnippet, snippetProps);

            // Assert
            Assert.DoesNotContain("manage.py collectstatic", text);
        }
예제 #5
0
        public void ExecuteTemplateThrowsWhenNoTemplatesMatch()
        {
            using (new MockViewEngine()) {
                // Arrange
                HtmlHelper html = MakeHtmlHelper(new ExecuteTemplateModel {
                    MyProperty = "Hello"
                });
                ModelMetadata      metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);
                ViewDataDictionary viewData = MakeViewData(html, metadata);

                // Act & Assert
                ExceptionHelper.ExpectInvalidOperationException(
                    () => TemplateHelpers.ExecuteTemplate(html, viewData, "templateName", DataBoundControlMode.Edit, delegate { return(new string[0]); }),
                    "Unable to locate an appropriate template for type System.String.");
            }
        }
예제 #6
0
        public void TemplateHelperAddsNonNullModelToVisitedObjects()      // DDB #224750
        {
            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel {
                MyProperty = "Hello"
            });
            ModelMetadata      metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);
            ViewDataDictionary viewData = null;

            // Act
            TemplateHelpers.TemplateHelper(html, metadata, "htmlFieldName", "templateName", DataBoundControlMode.ReadOnly, null /* additionalViewData */,
                                           (_html, _viewData, _templateName, _mode, _getViews) => { viewData = _viewData; return(String.Empty); });

            // Assert
            Assert.IsNotNull(viewData);
            Assert.IsTrue(viewData.TemplateInfo.VisitedObjects.Contains("Hello"));
        }
예제 #7
0
        public void TemplateHelperAppliesDisplayFormatStringInReadOnlyMode()
        {
            // Arrange
            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel {
                MyProperty = "Hello"
            });
            ModelMetadata metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);

            metadata.DisplayFormatString = "{0} world!";

            // Act
            string result = TemplateHelpers.TemplateHelper(html, metadata, "htmlFieldName", "templateName", DataBoundControlMode.ReadOnly, null /* additionalViewData */, ExecuteTemplateSpy);

            // Assert
            Assert.AreEqual("Model = Hello, ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = Hello world!, HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly", result);
        }
예제 #8
0
        public void TemplateHelperConvertsEmptyStringsToNull()
        {
            // Arrange
            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel {
                MyProperty = ""
            });
            ModelMetadata metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);

            metadata.ConvertEmptyStringToNull = true;

            // Act
            string result = TemplateHelpers.TemplateHelper(html, metadata, "htmlFieldName", "templateName", DataBoundControlMode.ReadOnly, null /* additionalViewData */, ExecuteTemplateSpy);

            // Assert
            Assert.AreEqual("Model = (null), ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = , HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly", result);
        }
예제 #9
0
        public void GetViewNamesFullOrderingOfInterfaceThatRequiresIEnumerable()
        {
            // Arrange
            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(IList <int>));

            // Act
            List <string> result = TemplateHelpers.GetViewNames(metadata, "UIHint", "DataType").ToList();

            // Assert
            Assert.AreEqual(5, result.Count);
            Assert.AreEqual("UIHint", result[0]);
            Assert.AreEqual("DataType", result[1]);
            Assert.AreEqual("IList`1", result[2]);
            Assert.AreEqual("Collection", result[3]);
            Assert.AreEqual("Object", result[4]);
        }
예제 #10
0
        public ViewsExportImport(IServerPaths serverPaths,
                                 TemplateHelpers appHelpers,
                                 IEnvironmentLogger envLogger,
                                 Lazy <CmsManager> cmsManagerLazy,
                                 Lazy <JsonBundleSerializer> jsonBundleLazy,
                                 IContextOfSite context) : base("Bck.Views")
        {
            _serverPaths    = serverPaths;
            _appHelpers     = appHelpers;
            _envLogger      = envLogger;
            _cmsManagerLazy = cmsManagerLazy;
            _jsonBundleLazy = jsonBundleLazy;

            _site = context.Site;
            _user = context.User;
        }
예제 #11
0
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(BuildScriptGeneratorContext scriptGeneratorContext)
        {
            (string projectFile, string publishDir) = GetProjectFileAndPublishDir(scriptGeneratorContext.SourceRepo);
            if (string.IsNullOrEmpty(projectFile) || string.IsNullOrEmpty(publishDir))
            {
                return(null);
            }

            var props = new DotNetCoreBashBuildSnippetProperties {
                ProjectFile = projectFile, PublishDirectory = publishDir
            };
            string script = TemplateHelpers.Render(TemplateHelpers.TemplateResource.DotNetCoreSnippet, props, _logger);

            return(new BuildScriptSnippet {
                BashBuildScriptSnippet = script
            });
        }
예제 #12
0
        public void GetViewNamesFullOrderingOfComplexType()
        {
            // Arrange
            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(System.Net.HttpWebRequest));

            // Act
            List <string> result = TemplateHelpers.GetViewNames(metadata, "UIHint", "DataType").ToList();

            // Assert
            Assert.AreEqual(6, result.Count);
            Assert.AreEqual("UIHint", result[0]);
            Assert.AreEqual("DataType", result[1]);
            Assert.AreEqual("HttpWebRequest", result[2]);
            Assert.AreEqual("WebRequest", result[3]);
            Assert.AreEqual("MarshalByRefObject", result[4]);
            Assert.AreEqual("Object", result[5]);
        }
예제 #13
0
        /// <summary>
        /// Constructor
        /// </summary>
        public OpportunityHelpers(
            ILogger <OpportunityHelpers> logger,
            IOptions <AppOptions> appOptions,
            UserProfileHelpers userProfileHelpers,
            IRoleRepository roleRepository,
            CardNotificationService cardNotificationService,
            TemplateHelpers templateHelpers,
            ICheckListProcessService checkListProcessService,
            ICustomerDecisionProcessService customerDecisionProcessService,
            ICustomerFeedbackProcessService customerFeedbackProcessService,
            IAuthorizationService authorizationService,
            IPermissionRepository permissionRepository,
            GraphUserAppService graphUserAppService,
            IUserContext userContext,
            IProposalDocumentProcessService proposalStatusProcessService)
        {
            Guard.Against.Null(logger, nameof(logger));
            Guard.Against.Null(appOptions, nameof(appOptions));
            Guard.Against.Null(userProfileHelpers, nameof(userProfileHelpers));
            Guard.Against.Null(roleRepository, nameof(roleRepository));
            Guard.Against.Null(graphUserAppService, nameof(graphUserAppService));
            Guard.Against.Null(cardNotificationService, nameof(cardNotificationService));
            Guard.Against.Null(templateHelpers, nameof(templateHelpers));
            Guard.Against.Null(checkListProcessService, nameof(checkListProcessService));
            Guard.Against.Null(customerDecisionProcessService, nameof(customerDecisionProcessService));
            Guard.Against.Null(customerFeedbackProcessService, nameof(customerFeedbackProcessService));
            Guard.Against.Null(proposalStatusProcessService, nameof(proposalStatusProcessService));
            Guard.Against.Null(authorizationService, nameof(authorizationService));
            Guard.Against.Null(permissionRepository, nameof(permissionRepository));

            _graphUserAppService = graphUserAppService;
            _logger                         = logger;
            _appOptions                     = appOptions.Value;
            _userProfileHelpers             = userProfileHelpers;
            _roleRepository                 = roleRepository;
            _cardNotificationService        = cardNotificationService;
            _templateHelpers                = templateHelpers;
            _checkListProcessService        = checkListProcessService;
            _customerDecisionProcessService = customerDecisionProcessService;
            _customerFeedbackProcessService = customerFeedbackProcessService;
            _proposalStatusProcessService   = proposalStatusProcessService;
            _authorizationService           = authorizationService;
            _permissionRepository           = permissionRepository;
            _userContext                    = userContext;
        }
예제 #14
0
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(BuildScriptGeneratorContext context)
        {
            var buildProperties = new Dictionary <string, string>();

            buildProperties[ManifestFilePropertyKeys.OperationId] = context.OperationId;

            (string projectFile, string publishDir) = GetProjectFileAndPublishDir(context.SourceRepo);
            if (string.IsNullOrEmpty(projectFile) || string.IsNullOrEmpty(publishDir))
            {
                return(null);
            }

            bool zipAllOutput = ShouldZipAllOutput(context);

            buildProperties[ManifestFilePropertyKeys.ZipAllOutput] = zipAllOutput.ToString().ToLowerInvariant();

            _environmentSettingsProvider.TryGetAndLoadSettings(out var environmentSettings);

            (var preBuildCommand, var postBuildCommand) = PreAndPostBuildCommandHelper.GetPreAndPostBuildCommands(
                context.SourceRepo,
                environmentSettings);

            var templateProperties = new DotNetCoreBashBuildSnippetProperties
            {
                ProjectFile      = projectFile,
                PublishDirectory = publishDir,
                BuildProperties  = buildProperties,
                BenvArgs         = $"dotnet={context.DotNetCoreVersion}",
                DirectoriesToExcludeFromCopyToIntermediateDir = GetDirectoriesToExcludeFromCopyToIntermediateDir(
                    context),
                PreBuildCommand  = preBuildCommand,
                PostBuildCommand = postBuildCommand,
                ManifestFileName = FilePaths.BuildManifestFileName,
                ZipAllOutput     = zipAllOutput,
                Configuration    = GetBuildConfiguration()
            };
            var script = TemplateHelpers.Render(
                TemplateHelpers.TemplateResource.DotNetCoreSnippet,
                templateProperties,
                _logger);

            return(new BuildScriptSnippet {
                BashBuildScriptSnippet = script, IsFullScript = true
            });
        }
예제 #15
0
        private string ResolveAppPath(int appId, bool global, bool allowFullAccess)
        {
            var thisApp = Factory.Resolve <Apps.App>().InitNoData(new AppIdentity(Eav.Apps.App.AutoLookupZone, appId), Log);

            if (global && !allowFullAccess)
            {
                throw new NotSupportedException("only host user may access global files");
            }

            var appPath = TemplateHelpers.GetTemplatePathRoot(
                global
                    ? Settings.TemplateLocations.HostFileSystem
                    : Settings.TemplateLocations.PortalFileSystem
                , thisApp); // get root in global system

            appPath = _http.MapPath(appPath);
            return(appPath);
        }
예제 #16
0
        public void GeneratedSnippet_ContainsCollectStatic_IfDisableCollectStatic_IsFalse()
        {
            // Arrange
            var snippetProps = new PythonBashBuildSnippetProperties(
                virtualEnvironmentName: null,
                virtualEnvironmentModule: null,
                virtualEnvironmentParameters: null,
                packagesDirectory: "packages_dir",
                disableCollectStatic: false,
                compressVirtualEnvCommand: null,
                compressedVirtualEnvFileName: null);

            // Act
            var text = TemplateHelpers.Render(TemplateHelpers.TemplateResource.PythonSnippet, snippetProps);

            // Assert
            Assert.Contains("manage.py collectstatic", text);
        }
        private string ResolveAppPath(int appId, bool global, bool allowFullAccess)
        {
            var thisApp = GetApp.LightWithoutData(new DnnTenant(PortalSettings.Current), appId, Log);

            if (global && !allowFullAccess)
            {
                throw new NotSupportedException("only host user may access global files");
            }

            var appPath = TemplateHelpers.GetTemplatePathRoot(
                global
                    ? Settings.TemplateLocations.HostFileSystem
                    : Settings.TemplateLocations.PortalFileSystem
                , thisApp); // get root in global system

            appPath = global::System.Web.Hosting.HostingEnvironment.MapPath(appPath);
            return(appPath);
        }
예제 #18
0
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(BuildScriptGeneratorContext context)
        {
            var    packageJson          = GetPackageJsonObject(context.SourceRepo, _logger);
            string runBuildCommand      = null;
            string runBuildAzureCommand = null;

            string packageManagerCmd = context.SourceRepo.FileExists(NodeConstants.YarnLockFileName) ? NodeConstants.YarnCommand : NodeConstants.NpmCommand;

            _logger.LogInformation("Using {packageManager}", packageManagerCmd);

            var packageInstallCommand = string.Format(NodeConstants.PackageInstallCommandTemplate, packageManagerCmd);

            var scriptsNode = packageJson?.scripts;

            if (scriptsNode != null)
            {
                if (scriptsNode.build != null)
                {
                    runBuildCommand = string.Format(NodeConstants.PkgMgrRunBuildCommandTemplate, packageManagerCmd);
                }

                if (scriptsNode["build:azure"] != null)
                {
                    runBuildAzureCommand = string.Format(NodeConstants.PkgMgrRunBuildAzureCommandTemplate, packageManagerCmd);
                }
            }

            if (packageJson?.dependencies != null)
            {
                Newtonsoft.Json.Linq.JObject deps = packageJson.dependencies;
                var depSpecs = deps.ToObject <IDictionary <string, string> >();
                _logger.LogDependencies(context.Language, context.NodeVersion, depSpecs.Select(kv => kv.Key + kv.Value));
            }

            var scriptProps = new NodeBashBuildSnippetProperties(
                packageInstallCommand: packageInstallCommand,
                runBuildCommand: runBuildCommand,
                runBuildAzureCommand: runBuildAzureCommand);
            string script = TemplateHelpers.Render(TemplateHelpers.TemplateResource.NodeBuildSnippet, scriptProps, _logger);

            return(new BuildScriptSnippet {
                BashBuildScriptSnippet = script
            });
        }
예제 #19
0
        public void TemplateHelperPreservesExistingViewData()
        {
            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel());

            html.ViewData["Foo"] = "Bar";
            html.ViewData["Baz"] = 42;
            ModelMetadata      metadata         = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);
            ViewDataDictionary callbackViewData = null;

            // Act
            string result = TemplateHelpers.TemplateHelper(html, metadata, "htmlFieldName", "templateName", DataBoundControlMode.ReadOnly, null /* additionalViewData */,
                                                           (_html, _viewData, _templateName, _mode, _getViewNames) => { callbackViewData = _viewData; return(String.Empty); });

            // Assert
            Assert.AreNotSame(html.ViewData, callbackViewData);
            Assert.AreEqual(2, callbackViewData.Count);
            Assert.AreEqual("Bar", callbackViewData["Foo"]);
            Assert.AreEqual(42, callbackViewData["Baz"]);
        }
예제 #20
0
        public void GeneratedScript_ConfigureAppInsights_Condition_Satisfied(string version)
        {
            // Condition is node version have to be 8 or newer or node version is 6.12.0
            // As we don't support 6.12.0 in our build image we condition remains node 8 or newer
            // Arrange
            var otherEnvironment = new Dictionary <string, string> {
                { Constants.AppInsightsKey, "xyz" }
            };
            var scriptGenerator = GetNodePlatformInstance(
                defaultNodeVersion: version, otherEnvironment: otherEnvironment);
            var repo = new MemorySourceRepo();

            repo.AddFile(PackageJsonWithBuildScript, NodeConstants.PackageJsonFileName);
            var context = CreateScriptGeneratorContext(repo);

            context.NodeVersion = version;
            //context.LanguageVersion = version;
            var expected = new NodeBashBuildSnippetProperties(
                packageInstallCommand: NpmInstallCommand,
                runBuildCommand: "npm run build",
                runBuildAzureCommand: "npm run build:azure",
                hasProductionOnlyDependencies: true,
                productionOnlyPackageInstallCommand: string.Format(
                    NodeConstants.ProductionOnlyPackageInstallCommandTemplate,
                    NpmInstallCommand),
                compressedNodeModulesFileName: null,
                compressNodeModulesCommand: null,
                appInsightsInjectCommand: "npm install --save applicationinsights",
                appInsightsPackageName: "applicationinsights",
                appInsightsLoaderFileName: "oryx-appinsightsloader.js");

            // Act
            var snippet = scriptGenerator.GenerateBashBuildScriptSnippet(context);

            // Assert
            Assert.NotNull(snippet);
            Assert.Contains("applicationinsights", snippet.BashBuildScriptSnippet);
            Assert.Equal(
                TemplateHelpers.Render(TemplateHelpers.TemplateResource.NodeBuildSnippet, expected),
                snippet.BashBuildScriptSnippet);
            Assert.True(scriptGenerator.IsCleanRepo(repo));
        }
예제 #21
0
        public void PrePostBuildScripts_ShouldBeIncluded_IfSupplied()
        {
            // Arrange
            const string script1     = "abcdefg";
            const string script2     = "hijklmn";
            var          scriptProps = new BaseBashBuildScriptProperties()
            {
                PreBuildScriptPath  = script1,
                PostBuildScriptPath = script2
            };

            // Act
            var script = TemplateHelpers.Render(TemplateHelpers.TemplateResource.BaseBashScript, scriptProps);

            // Assert
            Assert.Contains("Executing pre-build script", script);
            Assert.Contains(script1, script);
            Assert.Contains("Executing post-build script", script);
            Assert.Contains(script2, script);
        }
예제 #22
0
        public void BuildSnippets_ShouldBeIncluded_InOrder()
        {
            // Arrange
            const string script1     = "abcdefg";
            const string script2     = "123456";
            var          scriptProps = new BaseBashBuildScriptProperties()
            {
                BuildScriptSnippets = new List <string>()
                {
                    script1, script2
                }
            };

            // Act
            var script = TemplateHelpers.Render(TemplateHelpers.TemplateResource.BaseBashScript, scriptProps);

            // Assert
            Assert.Contains(script1 + "\n\n" + script2, script); // The template engine uses UNIX-style line endings
            Assert.DoesNotContain("Executing pre-build script", script);
            Assert.DoesNotContain("Executing post-build script", script);
        }
예제 #23
0
        public void CacheIsReusedIfPresent()
        {
            // Arrange
            Hashtable items = new Hashtable();
            Mock <HttpContextBase> context = new Mock <HttpContextBase>();

            context.Expect(c => c.Items).Returns(items);
            Mock <ViewContext> viewContext = new Mock <ViewContext>();

            viewContext.Expect(c => c.HttpContext).Returns(context.Object);
            Mock <IViewDataContainer> viewDataContainer = new Mock <IViewDataContainer>();
            HtmlHelper helper = new HtmlHelper(viewContext.Object, viewDataContainer.Object);

            // Act
            Dictionary <string, TemplateHelpers.ActionCacheItem> cache1 = TemplateHelpers.GetActionCache(helper);
            Dictionary <string, TemplateHelpers.ActionCacheItem> cache2 = TemplateHelpers.GetActionCache(helper);

            // Assert
            Assert.IsNotNull(cache1);
            Assert.AreSame(cache1, cache2);
        }
예제 #24
0
        public void TemplateHelperFormatsValuesUsingCurrentCulture()
        {
            CultureInfo existingCulture = Thread.CurrentThread.CurrentCulture;

            try {
                // Arrange
                Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("es-PR");
                HtmlHelper    html     = MakeHtmlHelper(new { MyProperty = new DateTime(2009, 11, 18, 16, 12, 8, DateTimeKind.Utc) });
                ModelMetadata metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);
                metadata.DisplayFormatString = "{0:F}";

                // Act
                string result = TemplateHelpers.TemplateHelper(html, metadata, "htmlFieldName", "templateName", DataBoundControlMode.ReadOnly, null /* additionalViewData */, ExecuteTemplateSpy);

                // Assert
                Assert.AreEqual("Model = 18/11/2009 04:12:08 p.m., ModelType = System.DateTime, RealModelType = System.DateTime, PropertyName = MyProperty, FormattedModelValue = miércoles, 18 de noviembre de 2009 04:12:08 p.m., HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly", result);
            }
            finally {
                Thread.CurrentThread.CurrentCulture = existingCulture;
            }
        }
예제 #25
0
        public void CacheIsCreatedIfNotPresent()
        {
            // Arrange
            Hashtable items = new Hashtable();
            Mock <HttpContextBase> context = new Mock <HttpContextBase>();

            context.Expect(c => c.Items).Returns(items);
            Mock <ViewContext> viewContext = new Mock <ViewContext>();

            viewContext.Expect(c => c.HttpContext).Returns(context.Object);
            Mock <IViewDataContainer> viewDataContainer = new Mock <IViewDataContainer>();
            HtmlHelper helper = new HtmlHelper(viewContext.Object, viewDataContainer.Object);

            // Act
            Dictionary <string, TemplateHelpers.ActionCacheItem> cache = TemplateHelpers.GetActionCache(helper);

            // Assert
            Assert.IsNotNull(cache);
            Assert.AreEqual(0, cache.Count);
            CollectionAssert.Contains(items.Values, cache);
        }
예제 #26
0
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(BuildScriptGeneratorContext ctx)
        {
            var buildProperties = new Dictionary <string, string>();

            buildProperties[ManifestFilePropertyKeys.OperationId] = ctx.OperationId;

            _logger.LogDebug("Selected PHP version: {phpVer}", ctx.PhpVersion);
            bool composerFileExists = false;

            if (ctx.SourceRepo.FileExists(PhpConstants.ComposerFileName))
            {
                composerFileExists = true;

                try
                {
                    dynamic composerFile = ctx.SourceRepo.ReadJsonObjectFromFile(PhpConstants.ComposerFileName);
                    if (composerFile?.require != null)
                    {
                        Newtonsoft.Json.Linq.JObject deps = composerFile?.require;
                        var depSpecs = deps.ToObject <IDictionary <string, string> >();
                        _logger.LogDependencies(this.Name, ctx.PhpVersion, depSpecs.Select(kv => kv.Key + kv.Value));
                    }
                }
                catch (Exception exc)
                {
                    // Leave malformed composer.json files for Composer to handle.
                    // This prevents Oryx from erroring out when Composer itself might be able to tolerate the file.
                    _logger.LogWarning(exc, $"Exception caught while trying to deserialize {PhpConstants.ComposerFileName}");
                }
            }

            var props = new PhpBashBuildSnippetProperties {
                ComposerFileExists = composerFileExists
            };
            string snippet = TemplateHelpers.Render(TemplateHelpers.TemplateResource.PhpBuildSnippet, props, _logger);

            return(new BuildScriptSnippet {
                BashBuildScriptSnippet = snippet, BuildProperties = buildProperties
            });
        }
예제 #27
0
        public void ExecuteTemplateCallsGetViewNamesWithProvidedTemplateNameAndMetadataInformation()
        {
            using (new MockViewEngine()) {
                // Arrange
                HtmlHelper    html     = MakeHtmlHelper(new ExecuteTemplateModel());
                ModelMetadata metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);
                metadata.TemplateHint = "templateHint";
                metadata.DataTypeName = "dataType";
                string[] hints = null;

                // Act
                TemplateHelpers.ExecuteTemplate(html, MakeViewData(html, metadata), "templateName", DataBoundControlMode.ReadOnly,
                                                (_metadata, _hints) => { hints = _hints; return(new[] { "String" }); });

                // Assert
                Assert.IsNotNull(hints);
                Assert.AreEqual(3, hints.Length);
                Assert.AreEqual("templateName", hints[0]);
                Assert.AreEqual("templateHint", hints[1]);
                Assert.AreEqual("dataType", hints[2]);
            }
        }
예제 #28
0
        public void GeneratedScript_UsesNpmRunBuild_IfBuildNodeIsPresentUnderScripts()
        {
            // Arrange
            var scriptGenerator = GetNodePlatformInstance(defaultNpmVersion: "6.0.0");
            var repo            = new MemorySourceRepo();

            repo.AddFile(PackageJsonWithBuildScript, NodeConstants.PackageJsonFileName);
            var context = CreateScriptGeneratorContext(repo);

            context.LanguageVersion = "8.2.1";
            var expected = new NodeBashBuildSnippetProperties(
                packageInstallCommand: NpmInstallCommand,
                runBuildCommand: "npm run build",
                runBuildAzureCommand: "npm run build:azure");

            // Act
            var snippet = scriptGenerator.GenerateBashBuildScriptSnippet(context);

            // Assert
            Assert.NotNull(snippet);
            Assert.Equal(TemplateHelpers.Render(TemplateHelpers.TemplateResource.NodeBuildSnippet, expected), snippet.BashBuildScriptSnippet);
            Assert.True(scriptGenerator.IsCleanRepo(repo));
        }
        // Returns true if the template contains bicep _generator metadata, false otherwise
        public bool TemplateContainsBicepGeneratorMetadata(string template)
        {
            try
            {
                if (!string.IsNullOrEmpty(template))
                {
                    JToken jtoken = template.FromJson <JToken>();
                    if (TemplateHelpers.TryGetTemplateGeneratorObject(jtoken, out DeploymentTemplateGeneratorMetadata generator))
                    {
                        if (generator.Name == "bicep")
                        {
                            return(true);
                        }
                    }
                }
            }
            catch (Exception)
            {
                return(false);
            }

            return(false);
        }
예제 #30
0
        public void GeneratesScript_WithDefaultNpmVersion_ForMalformedPackageJson()
        {
            // Arrange
            var scriptGenerator = GetNodePlatformInstance(defaultNpmVersion: "5.4.2");
            var repo            = new MemorySourceRepo();

            repo.AddFile(MalformedPackageJson, NodeConstants.PackageJsonFileName);
            var context = CreateScriptGeneratorContext(repo);

            context.LanguageVersion = "8.2.1";
            var expected = new NodeBashBuildSnippetProperties(
                packageInstallCommand: NpmInstallCommand,
                runBuildCommand: null,
                runBuildAzureCommand: null);

            // Act
            var snippet = scriptGenerator.GenerateBashBuildScriptSnippet(context);

            // Assert
            Assert.NotNull(snippet);
            Assert.Equal(TemplateHelpers.Render(TemplateHelpers.TemplateResource.NodeBuildSnippet, expected), snippet.BashBuildScriptSnippet);
            Assert.True(scriptGenerator.IsCleanRepo(repo));
        }
예제 #31
0
        public void GeneratedScript_DoesNotConfigureAppInsights_IfAppInsightsEnvironmentVariable_NotSet(
            string nodeVersion)
        {
            // Arrange
            var scriptGenerator = GetNodePlatformInstance(defaultNodeVersion: nodeVersion);
            var repo            = new MemorySourceRepo();

            repo.AddFile(PackageJsonWithBuildScript, NodeConstants.PackageJsonFileName);
            var context = CreateScriptGeneratorContext(repo);

            context.NodeVersion = nodeVersion;
            var expected = new NodeBashBuildSnippetProperties(
                packageInstallCommand: NpmInstallCommand,
                runBuildCommand: "npm run build",
                runBuildAzureCommand: "npm run build:azure",
                hasProductionOnlyDependencies: true,
                productionOnlyPackageInstallCommand: string.Format(
                    NodeConstants.ProductionOnlyPackageInstallCommandTemplate,
                    NpmInstallCommand),
                compressedNodeModulesFileName: null,
                compressNodeModulesCommand: null,
                appInsightsInjectCommand: null,
                appInsightsPackageName: "applicationinsights",
                appInsightsLoaderFileName: "oryx-appinsightsloader.js");

            // Act
            var snippet = scriptGenerator.GenerateBashBuildScriptSnippet(context);

            // Assert
            Assert.NotNull(snippet);
            Assert.DoesNotContain("applicationinsights", snippet.BashBuildScriptSnippet);
            Assert.Equal(
                TemplateHelpers.Render(TemplateHelpers.TemplateResource.NodeBuildSnippet, expected),
                snippet.BashBuildScriptSnippet);
            Assert.True(scriptGenerator.IsCleanRepo(repo));
        }
예제 #32
0
        public void ExecuteTemplateUsesViewFromDefaultActionsInEditMode()
        {
            using (MockViewEngine engine = new MockViewEngine()) {
                // Arrange
                HtmlHelper html = MakeHtmlHelper(new ExecuteTemplateModel {
                    MyProperty = "Hello"
                });
                ModelMetadata metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);
                engine.Engine.Expect(e => e.FindPartialView(html.ViewContext, "EditorTemplates/String", It.IsAny <bool>()))
                .Returns(new ViewEngineResult(new string[0]))
                .Verifiable();
                ViewDataDictionary viewData = MakeViewData(html, metadata);

                // Act
                TemplateHelpers.ExecuteTemplate(html, viewData, "templateName", DataBoundControlMode.Edit,
                                                delegate { return(new[] { "String" }); });

                // Assert
                engine.Engine.Verify();
                TemplateHelpers.ActionCacheCodeItem cacheItem = TemplateHelpers.GetActionCache(html)["EditorTemplates/String"] as TemplateHelpers.ActionCacheCodeItem;
                Assert.IsNotNull(cacheItem);
                Assert.AreEqual(DefaultEditorTemplates.StringTemplate, cacheItem.Action);
            }
        }
예제 #33
0
        public string GenerateBashRunScript(RunScriptGeneratorOptions options)
        {
            if (options.SourceRepo == null)
            {
                throw new ArgumentNullException(nameof(RunScriptGeneratorOptions.SourceRepo));
            }

            string startupCommand = null;

            // Log how we detected the entrypoint command
            var commandSource = string.Empty;

            if (!string.IsNullOrWhiteSpace(options.UserStartupCommand))
            {
                startupCommand = options.UserStartupCommand.Trim();
                _logger.LogInformation("Using user-provided startup command");
                commandSource = "User";
            }
            else
            {
                var packageJson = GetPackageJsonObject(options.SourceRepo, _logger);
                startupCommand = packageJson?.scripts?.start;
                if (string.IsNullOrWhiteSpace(startupCommand))
                {
                    string mainJsFile = packageJson?.main;
                    if (string.IsNullOrEmpty(mainJsFile))
                    {
                        var candidateFiles = new[] { "bin/www", "server.js", "app.js", "index.js", "hostingstart.js" };
                        foreach (var file in candidateFiles)
                        {
                            if (options.SourceRepo.FileExists(file))
                            {
                                startupCommand = GetStartupCommandFromJsFile(options, file);
                                _logger.LogInformation("Found startup candidate {nodeStartupFile}", file);
                                commandSource = "CandidateFile";
                                break;
                            }
                        }
                    }
                    else
                    {
                        startupCommand = GetStartupCommandFromJsFile(options, mainJsFile);
                        commandSource  = "PackageJsonMain";
                    }
                }
                else
                {
                    if (options.SourceRepo.FileExists(NodeConstants.YarnLockFileName))
                    {
                        commandSource  = "PackageJsonStartYarn";
                        startupCommand = NodeConstants.YarnStartCommand;
                        _logger.LogInformation("Found startup command in package.json, and will use Yarn");
                    }
                    else
                    {
                        commandSource  = "PackageJsonStartNpm";
                        startupCommand = NodeConstants.NpmStartCommand;
                        _logger.LogInformation("Found startup command in package.json, and will use npm");
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(startupCommand))
            {
                startupCommand = GetStartupCommandFromJsFile(options, options.DefaultAppPath);
                commandSource  = "DefaultApp";
            }

            _logger.LogInformation("Finalizing entrypoint script using {commandSource}", commandSource);
            var templateValues = new NodeBashRunScriptProperties
            {
                AppDirectory   = options.SourceRepo.RootPath,
                StartupCommand = startupCommand,
                ToolsVersions  = string.IsNullOrWhiteSpace(options.PlatformVersion) ? null : $"node={options.PlatformVersion}",
                BindPort       = options.BindPort
            };
            var script = TemplateHelpers.Render(TemplateHelpers.TemplateResource.NodeRunScript, templateValues);

            return(script);
        }