Example #1
0
        public static ArgumentResult ParseArgumentTemplate(string template)
        {
            var result = new ArgumentResult();

            foreach (var token in TemplateTokenizer.Tokenize(template))
            {
                if (token.TokenKind == TemplateToken.Kind.ShortName ||
                    token.TokenKind == TemplateToken.Kind.LongName)
                {
                    throw TemplateException.ArgumentCannotContainOptions(template, token);
                }

                if (token.TokenKind == TemplateToken.Kind.OptionalValue ||
                    token.TokenKind == TemplateToken.Kind.RequiredValue)
                {
                    if (!string.IsNullOrWhiteSpace(result.Value))
                    {
                        throw TemplateException.MultipleValuesAreNotSupported(template, token);
                    }
                    if (string.IsNullOrWhiteSpace(token.Value))
                    {
                        throw TemplateException.ValuesMustHaveName(template, token);
                    }

                    result.Value    = token.Value;
                    result.Required = token.TokenKind == TemplateToken.Kind.RequiredValue;
                }
            }
            return(result);
        }
Example #2
0
 /// <summary>
 /// Throw exception.
 /// </summary>
 /// <param name="ctx"></param>
 /// <param name="e">Represents errors that occur during application execution.</param>
 /// <param name="tag">Represents errors tag.</param>
 /// <param name="writer">See the <see cref="System.IO.TextWriter"/>.</param>
 public static void ThrowException(this TemplateContext ctx, TemplateException e, ITag tag, System.IO.TextWriter writer)
 {
     ctx.AddError(e);
     if (ctx.ThrowExceptions)
     {
         writer.Write(tag.ToSource());
     }
 }
Example #3
0
 /// <summary>
 /// Throw exception.
 /// </summary>
 /// <param name="ctx"></param>
 /// <param name="e">Represents errors that occur during application execution.</param>
 /// <param name="tag">Represents errors tag.</param>
 /// <param name="writer">See the <see cref="System.IO.TextWriter"/>.</param>
 public static async Task ThrowExceptionAsync(this TemplateContext ctx, TemplateException e, ITag tag, System.IO.TextWriter writer)
 {
     ctx.AddError(e);
     if (!ctx.ThrowExceptions)
     {
         await writer.WriteAsync(tag.ToSource());
     }
 }
Example #4
0
 public ITile Get(string name)
 {
     try
     {
         return(cache[name]);
     }
     catch (KeyNotFoundException)
     {
         throw TemplateException.TemplateNotFound(name).HavingHttpErrorCode(404);
     }
 }
 private void RenderTemplateException(TemplateException ex, ModuleInfo module)
 {
     DotNetNuke.UI.Skins.Skin.AddPageMessage(Page, "OpenContent RenderModule SkinObject", "<p><b>Template error</b></p>" + ex.MessageAsHtml(), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
     if (LogContext.IsLogActive)
     {
         var logKey = "Error in tempate";
         LogContext.Log(module.ModuleID, logKey, "Error", ex.MessageAsList());
         LogContext.Log(module.ModuleID, logKey, "Model", ex.TemplateModel);
         LogContext.Log(module.ModuleID, logKey, "Source", ex.TemplateSource);
     }
     LoggingUtils.ProcessLogFileException(this, module, ex);
 }
Example #6
0
        public void TestUnkownTile()
        {
            var ts = new TilesSet();

            try
            {
                var x = ts["?"];
                Assert.Fail("Expected exception on " + x);
            }
            catch (TemplateException Te)
            {
                Assert.That(Te.Message, Is.EqualTo(TemplateException.TemplateNotFound("?").Message));
            }
        }
Example #7
0
        public void UnkownTileShouldThrowExceptionThroughIndexed()
        {
            var ts = new TilesMap();

            try
            {
                var x = ts["?"];
                Assert.Fail("Expected exception on " + x);
            }
            catch (TemplateException Te)
            {
                Assert.That(Te.Message, Is.EqualTo(TemplateException.TemplateNotFound("?").Message));
            }
        }
Example #8
0
        internal static bool RemoveTemplate(Templates form, TemplateObjectList templateObjectList)
        {
            TreeView templateTreeView   = form.templateTreeView;
            TextBox  descriptionTextBox = form.descriptionTextBox;
            TextBox  textTextBox        = form.textTextBox;
            Button   removeButton       = form.removeButton;

            int indexNodeToRemove      = templateTreeView.SelectedNode.Index;
            int templatePositionInList = GetTemplatePositionInList(templateObjectList, descriptionTextBox.Text);

            if (templatePositionInList == -1)
            {
                String            error     = LanguageUtil.GetCurrentLanguageString("ErrorRemoving", className);
                TemplateException exception = new TemplateException(error);
                WindowManager.ShowErrorBox(form, error, exception);
                return(false);
            }
            templateObjectList.RemoveAt(templatePositionInList);

            templateTreeView.Focus();
            templateTreeView.Nodes.Remove(templateTreeView.SelectedNode);

            if (templateTreeView.Nodes.Count == 0)
            {
                descriptionTextBox.Text = String.Empty;
                textTextBox.Text        = String.Empty;

                descriptionTextBox.Enabled = false;
                textTextBox.Enabled        = false;
                removeButton.Enabled       = false;
            }
            else if (templateTreeView.Nodes.Count > indexNodeToRemove)
            {
                templateTreeView.SelectedNode = templateTreeView.Nodes[indexNodeToRemove];

                descriptionTextBox.Enabled = true;
                textTextBox.Enabled        = true;
                removeButton.Enabled       = true;
            }
            else
            {
                templateTreeView.SelectedNode = templateTreeView.Nodes[indexNodeToRemove - 1];

                descriptionTextBox.Enabled = true;
                textTextBox.Enabled        = true;
                removeButton.Enabled       = true;
            }

            return(true);
        }
Example #9
0
        public void WhenTheTileIsNotAvailableAndNoFallBackIsAvailableGuardInitShouldFail()
        {
            var map  = new TilesMap();
            var tile = new TileReference("name", map);

            try
            {
                tile.GuardInit();
                Assert.Fail("Expected exception");
            }
            catch (TemplateException Te)
            {
                Assert.That(Te.Message, Is.EqualTo(TemplateException.TemplateNotFound("name").Message));
            }
        }
        public void TilesViewEngine_Should_Throw_Template_Exception_Incase_Of_UndefinedView_And_Non_Http_Errors()
        {
            TestController controller   = GetController();
            var            result       = (ViewResult)controller.Index();
            var            engineResult = new TilesViewEngine().FindView(null, "NonExisting", null, false);
            var            viewContext  = new ViewContext(controller.ControllerContext, engineResult.View, result.ViewData,
                                                          new TempDataDictionary());

            Assert.That(((TilesView)engineResult.View).HttpErrors, Is.False);
            try {
                (engineResult.View).Render(viewContext, null);
            }
            catch (TemplateException Te)
            {
                Assert.That(Te.Message, Is.EqualTo(TemplateException.TemplateNotFound("NonExisting").Message));
            }
        }
Example #11
0
 private void RenderTemplateException(TemplateException ex)
 {
     DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "<p><b>Template error</b></p>" + ex.MessageAsHtml(), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
     //DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "<p><b>Template source</b></p>" + Server.HtmlEncode(ex.TemplateSource).Replace("\n", "<br/>"), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.BlueInfo);
     //DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "<p><b>Template model</b></p> <pre>" + JsonConvert.SerializeObject(ex.TemplateModel, Formatting.Indented)/*.Replace("\n", "<br/>")*/+"</pre>", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.BlueInfo);
     //lErrorMessage.Text = ex.HtmlMessage;
     //lErrorModel.Text = "<pre>" + JsonConvert.SerializeObject(ex.TemplateModel, Formatting.Indented)/*.Replace("\n", "<br/>")*/+"</pre>";
     if (LogContext.IsLogActive)
     {
         var logKey = "Error in tempate";
         LogContext.Log(ModuleContext.ModuleId, logKey, "Error", ex.MessageAsList());
         LogContext.Log(ModuleContext.ModuleId, logKey, "Model", ex.TemplateModel);
         LogContext.Log(ModuleContext.ModuleId, logKey, "Source", ex.TemplateSource);
         //LogContext.Log(logKey, "StackTrace", ex.StackTrace);
         //DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "<p>More info is availale on de browser console (F12)</p>", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.BlueInfo);
     }
     LoggingUtils.ProcessLogFileException(this, ex);
 }
 public void WrongFileName()
 {
     try
     {
         new TemplateTile("name", new FileTemplate("somepath.htm"), null);
         Assert.Fail("Expected exception");
     }
     catch (TemplateException Te)
     {
         var expected = ResourceException.FileNotFound(Path.GetFullPath("somepath.htm"));
         Assert.That(
             Te.InnerException.Message,
             Is.EqualTo(expected.Message)
             );
         Assert.That(
             Te.Message,
             Is.EqualTo(TemplateException.TemplateFailedToInitialize(Path.GetFullPath("somepath.htm"), expected).Message));
     }
 }
Example #13
0
 protected override void Load()
 {
     try
     {
         _template = Formatter.LocatorBasedFormatter(_factory.Lib, _name, _locator, _factory).ParsedTemplate;
     }
     catch (ResourceException FNFe)
     {
         throw TemplateException.TemplateFailedToInitialize(_name, FNFe).WithHttpErrorCode(404);
     }
     catch (ExceptionWithContext EWC)
     {
         throw TemplateExceptionWithContext.ErrorInTemplate(_name, EWC).AddErrorCodeIfNull(500);
     }
     catch (Exception e)
     {
         throw TemplateException.ErrorInTemplate(_name, e).WithHttpErrorCode(500);
     }
 }
Example #14
0
        internal static bool SaveDescription(Templates form, TemplateObjectList templateObjectList)
        {
            TreeView templateTreeView   = form.templateTreeView;
            TextBox  descriptionTextBox = form.descriptionTextBox;

            if (String.IsNullOrEmpty(descriptionTextBox.Text))
            {
                WindowManager.ShowAlertBox(form, LanguageUtil.GetCurrentLanguageString("NameNotEmpty", className));
                descriptionTextBox.Focus();
                return(true);
            }

            TemplateObject selectedTemplateObject = null;

            foreach (TemplateObject templateObject in templateObjectList)
            {
                if (templateObject.Description != templateTreeView.SelectedNode.Text && templateObject.Description == descriptionTextBox.Text)
                {
                    WindowManager.ShowAlertBox(form, LanguageUtil.GetCurrentLanguageString("AlreadyExists", className));
                    descriptionTextBox.Focus();
                    return(true);
                }

                if (templateObject.Description == templateTreeView.SelectedNode.Text)
                {
                    selectedTemplateObject = templateObject;
                }
            }

            if (selectedTemplateObject == null)
            {
                String            error     = LanguageUtil.GetCurrentLanguageString("ErrorSaving", className);
                TemplateException exception = new TemplateException(error);
                WindowManager.ShowErrorBox(form, error, exception);
                return(false);
            }

            selectedTemplateObject.Description = descriptionTextBox.Text;
            templateTreeView.SelectedNode.Text = selectedTemplateObject.Description;

            return(true);
        }
        public void TestLastExceptionIsFilled()
        {
            var tempTile = Path.GetTempFileName();

            File.Copy("a.htm", tempTile, true);
            try
            {
                var ft = new FileTemplate(tempTile);
                Assert.That(ft.TileLastModified, Is.EqualTo(ft.ResourceLastModified));
                File.Delete(tempTile);
                Assert.That(ft.RefreshException, Is.Null);
                ft.Refresh();
                Assert.That(ft.RefreshException, Is.Not.Null);
                Assert.That(ft.RefreshException.Message, Is.EqualTo(TemplateException.TemplateFailedToInitialize(tempTile, ResourceException.FileNotFound(tempTile)).Message));
            }
            finally
            {
                File.Delete(tempTile);
            }
        }
        private static TemplateToken ReadValue(TextBuffer buffer, bool required)
        {
            var start = required ? '<' : '[';
            var end   = required ? '>' : ']';

            var position = buffer.Position;
            var kind     = required ? TemplateToken.Kind.RequiredValue : TemplateToken.Kind.OptionalValue;

            // Consume start of value character (< or [).
            buffer.Consume(start);

            var builder = new StringBuilder();

            while (!buffer.ReachedEnd)
            {
                var character = buffer.Peek();
                if (character == end)
                {
                    break;
                }

                buffer.Read();
                builder.Append(character);
            }

            if (buffer.ReachedEnd)
            {
                var name  = builder.ToString();
                var token = new TemplateToken(kind, position, name, $"{start}{name}");
                throw TemplateException.UnterminatedValueName(buffer.Original, token);
            }

            // Consume end of value character (> or ]).
            buffer.Consume(end);

            // Get the value (the text within the brackets).
            var value = builder.ToString();

            // Create a token and return it.
            return(new TemplateToken(kind, position, value, required ? $"<{value}>" : $"[{value}]"));
        }
Example #17
0
        public static IReadOnlyList <TemplateToken> Tokenize(string template)
        {
            using var buffer = new TextBuffer(template);
            var result = new List <TemplateToken>();

            while (!buffer.ReachedEnd)
            {
                EatWhitespace(buffer);

                if (!buffer.TryPeek(out var character))
                {
                    break;
                }

                if (character == '-')
                {
                    result.Add(ReadOption(buffer));
                }
                else if (character == '|')
                {
                    buffer.Consume('|');
                }
                else if (character == '<')
                {
                    result.Add(ReadValue(buffer, true));
                }
                else if (character == '[')
                {
                    result.Add(ReadValue(buffer, false));
                }
                else
                {
                    throw TemplateException.UnexpectedCharacter(buffer.Original, buffer.Position, character);
                }
            }

            return(result);
        }
Example #18
0
        public static OptionResult ParseOptionTemplate(string template)
        {
            var result = new OptionResult();

            foreach (var token in TemplateTokenizer.Tokenize(template))
            {
                if (token.TokenKind == TemplateToken.Kind.LongName || token.TokenKind == TemplateToken.Kind.ShortName)
                {
                    if (string.IsNullOrWhiteSpace(token.Value))
                    {
                        throw TemplateException.OptionsMustHaveName(template, token);
                    }

                    if (char.IsDigit(token.Value[0]))
                    {
                        throw TemplateException.OptionNamesCannotStartWithDigit(template, token);
                    }

                    foreach (var character in token.Value)
                    {
                        if (!char.IsLetterOrDigit(character) && character != '-' && character != '_')
                        {
                            throw TemplateException.InvalidCharacterInOptionName(template, token, character);
                        }
                    }
                }

                if (token.TokenKind == TemplateToken.Kind.LongName)
                {
                    if (token.Value.Length == 1)
                    {
                        throw TemplateException.LongOptionMustHaveMoreThanOneCharacter(template, token);
                    }

                    result.LongNames.Add(token.Value);
                }

                if (token.TokenKind == TemplateToken.Kind.ShortName)
                {
                    if (token.Value.Length > 1)
                    {
                        throw TemplateException.ShortOptionMustOnlyBeOneCharacter(template, token);
                    }

                    result.ShortNames.Add(token.Value);
                }

                if (token.TokenKind == TemplateToken.Kind.RequiredValue ||
                    token.TokenKind == TemplateToken.Kind.OptionalValue)
                {
                    if (!string.IsNullOrWhiteSpace(result.Value))
                    {
                        throw TemplateException.MultipleOptionValuesAreNotSupported(template, token);
                    }

                    foreach (var character in token.Value)
                    {
                        if (!char.IsLetterOrDigit(character) &&
                            character != '=' && character != '-' && character != '_')
                        {
                            throw TemplateException.InvalidCharacterInValueName(template, token, character);
                        }
                    }

                    result.Value           = token.Value.ToUpperInvariant();
                    result.ValueIsOptional = token.TokenKind == TemplateToken.Kind.OptionalValue;
                }
            }

            if (result.LongNames.Count == 0 &&
                result.ShortNames.Count == 0)
            {
                throw TemplateException.MissingLongAndShortName(template, null);
            }

            return(result);
        }