Exemplo n.º 1
0
    private void GetClassDocs(CodeTypeDeclaration type, string typeName, string fileName, IDictionary <string, string> documentation)
    {
        List <string> docs = new List <string>();

        foreach (string docFile in new[] { fileName + ".html", fileName + "-obsolete.html" })
        {
            if (documentation.ContainsKey(docFile.ToLowerInvariant()))
            {
                string classDocs = StripTags(documentation[docFile.ToLowerInvariant()]);
                Match  match     = Regex.Match(classDocs, string.Format(@"(?<class>((The {0})|(This class)).+?)More\.\.\..*?\n" +
                                                                        @"Detailed Description\s+(?<detailed>.*?)(\n){{3,}}" +
                                                                        @"((\w+ )*\w+ Documentation\n(?<members>.+))", typeName),
                                               RegexOptions.Singleline);
                if (match.Success)
                {
                    type.Comments.Add(new CodeCommentStatement("<summary>", true));
                    string summary = match.Groups["class"].Value.Trim();
                    type.Comments.Add(new CodeCommentStatement(HtmlEncoder.HtmlEncode(summary), true));
                    type.Comments.Add(new CodeCommentStatement("</summary>", true));
                    string detailed = match.Groups["detailed"].Value.Replace(summary, string.Empty);
                    Util.FormatComment(detailed.Replace("\n/", "\n /"), type, false, "remarks");
                    docs.Add(match.Groups["members"].Value);
                }
                else
                {
                    docs.Add(classDocs);
                }
            }
        }
        this.memberDocumentation[type] = docs;
    }
Exemplo n.º 2
0
        public virtual void GenerateComment(RawComment comment)
        {
            if (comment.FullComment != null)
            {
                PushBlock(BlockKind.BlockComment);
                WriteLine(comment.FullComment.CommentToString(DocumentationCommentKind));
                PopBlock();
                return;
            }

            if (string.IsNullOrWhiteSpace(comment.BriefText))
            {
                return;
            }

            var lines = new List <string>();

            if (comment.BriefText.Contains("\n"))
            {
                lines.Add("<summary>");
                foreach (string line in HtmlEncoder.HtmlEncode(comment.BriefText).Split(
                             Environment.NewLine.ToCharArray()))
                {
                    lines.Add($"<para>{line}</para>");
                }
                lines.Add("</summary>");
            }
            else
            {
                lines.Add($"<summary>{comment.BriefText}</summary>");
            }

            GenerateMultiLineComment(lines, CommentKind);
        }
Exemplo n.º 3
0
        /// <summary>
        /// 根据ID得到一个提交实体
        /// </summary>
        /// <param name="id">提交ID</param>
        /// <returns>提交实体</returns>
        public static SolutionEntity GetSourceCode(Int32 id)
        {
            if (id <= 0)
            {
                throw new InvalidRequstException(RequestType.Solution);
            }

            SolutionEntity solu = SolutionRepository.Instance.GetEntity(id);

            if (solu == null)
            {
                throw new NullResponseException(RequestType.Solution);
            }
            else
            {
                solu.SourceCode = HtmlEncoder.HtmlEncode(solu.SourceCode);
            }

            if (!SolutionManager.CanViewSource(solu.UserName))
            {
                throw new NoPermissionException("You have no privilege to view the code!");
            }

            return(solu);
        }
Exemplo n.º 4
0
        private static string GetText(Comment comment)
        {
            var textComment = ((TextComment)comment);
            var text        = textComment.Text;

            return(HtmlEncoder.HtmlEncode(
                       text.Length > 1 && text[0] == ' ' && text[1] != ' ' ? text.Substring(1) : text));
        }
Exemplo n.º 5
0
        private static void AddObsoleteAttribute(Declaration function)
        {
            StringBuilder obsoleteMessageBuilder = new StringBuilder();

            obsoleteMessageBuilder.Append(HtmlEncoder.HtmlDecode(HtmlEncoder.HtmlEncode(function.Comment.BriefText).Split(
                                                                     Environment.NewLine.ToCharArray()).FirstOrDefault(line => line.Contains("instead") || line.Contains("deprecated"))));
            Attribute annotation = new Attribute();

            annotation.Type  = typeof(ObsoleteAttribute);
            annotation.Value = string.Format("\"{0}\"", obsoleteMessageBuilder);
            function.Attributes.Add(annotation);
        }
Exemplo n.º 6
0
        private static void AddObsoleteAttribute(Declaration function)
        {
            var obsoleteMessageBuilder = new StringBuilder();

            obsoleteMessageBuilder.Append(HtmlEncoder.HtmlDecode(HtmlEncoder.HtmlEncode(function.Comment.BriefText).Split(
                                                                     Environment.NewLine.ToCharArray()).FirstOrDefault(line => line.Contains("instead") || line.Contains("deprecated"))));
            function.Attributes.Add(new Attribute
            {
                Type  = typeof(ObsoleteAttribute),
                Value = $"\"{obsoleteMessageBuilder}\""
            });
        }
Exemplo n.º 7
0
        private static string GetText(Comment comment, bool trim = false)
        {
            var textComment = ((TextComment)comment);
            var text        = textComment.Text;

            if (trim)
            {
                text = text.Trim();
            }
            return(HtmlEncoder.HtmlEncode(
                       text.Length > 1 && text[0] == ' ' && text[1] != ' ' ? text.Substring(1) : text));
        }
Exemplo n.º 8
0
        public async Task RenderAsync_DoesNotCopyContentOnceRazorTextWriterIsNoLongerBuffering()
        {
            // Arrange
            var htmlEncoder = new HtmlEncoder();
            var expected    = "layout-1" +
                              htmlEncoder.HtmlEncode(Environment.NewLine) +
                              "body content" +
                              Environment.NewLine +
                              "section-content-1" +
                              Environment.NewLine +
                              "section-content-2";

            var page = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout      = "layout-1";
                v.WriteLiteral("body content" + Environment.NewLine);
                v.DefineSection("foo", async _ =>
                {
                    v.WriteLiteral("section-content-1" + Environment.NewLine);
                    await v.FlushAsync();
                    v.WriteLiteral("section-content-2");
                });
            });

            var layout1 = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Write("layout-1" + Environment.NewLine);
                v.RenderBodyPublic();
                v.Write(v.RenderSection("foo"));
            });

            var viewEngine = new Mock <IRazorViewEngine>();

            viewEngine.Setup(p => p.FindPage(It.IsAny <ActionContext>(), "layout-1"))
            .Returns(new RazorPageResult("layout-1", layout1));

            var view = new RazorView(viewEngine.Object,
                                     Mock.Of <IRazorPageActivator>(),
                                     CreateViewStartProvider(),
                                     page,
                                     isPartial: false);
            var viewContext = CreateViewContext(view);

            // Act
            await view.RenderAsync(viewContext);

            // Assert
            Assert.Equal(expected, viewContext.Writer.ToString());
        }
Exemplo n.º 9
0
        public async Task RenderAsync_WithNestedSections_ThrowsIfSectionsWereDefinedButNotRendered()
        {
            // Arrange
            var htmlEncoder = new HtmlEncoder();
            var page        = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout      = "~/Shared/Layout1.cshtml";
                v.WriteLiteral("BodyContent");
                v.DefineSection("foo", async writer =>
                {
                    await writer.WriteLineAsync("foo-content");
                });
            });
            var nestedLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout      = "~/Shared/Layout2.cshtml";
                v.Write("NestedLayout" + Environment.NewLine);
                v.RenderBodyPublic();
                v.DefineSection("foo", async writer =>
                {
                    await writer.WriteLineAsync(htmlEncoder.HtmlEncode(v.RenderSection("foo").ToString()));
                });
            });
            var baseLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Write("BaseLayout" + Environment.NewLine);
                v.RenderBodyPublic();
            });

            var viewEngine = new Mock <IRazorViewEngine>();

            viewEngine.Setup(p => p.FindPage(It.IsAny <ActionContext>(), "~/Shared/Layout1.cshtml"))
            .Returns(new RazorPageResult("~/Shared/Layout1.cshtml", nestedLayout));
            viewEngine.Setup(p => p.FindPage(It.IsAny <ActionContext>(), "~/Shared/Layout2.cshtml"))
            .Returns(new RazorPageResult("~/Shared/Layout2.cshtml", baseLayout));

            var view = new RazorView(viewEngine.Object,
                                     Mock.Of <IRazorPageActivator>(),
                                     CreateViewStartProvider(),
                                     page,
                                     isPartial: false);
            var viewContext = CreateViewContext(view);

            // Act and Assert
            var ex = await Assert.ThrowsAsync <InvalidOperationException>(() => view.RenderAsync(viewContext));

            Assert.Equal("The following sections have been defined but have not been rendered: 'foo'.", ex.Message);
        }
        public string ConvertToHtml()
        {
            using (TextReader fileStream = File.OpenText(fileNameWithPath))
            {
                string html = string.Empty;
                string line = fileStream.ReadLine();

                while (line != null)
                {
                    html += htmlEncoder.HtmlEncode(line);
                    html += htmlEncoder.BreakLine();
                    line  = fileStream.ReadLine();
                }

                return(html);
            }
        }
Exemplo n.º 11
0
        public async Task RenderAsync_AsPartial_ExecutesLayout_ButNotViewStartPages()
        {
            // Arrange
            var htmlEncoder = new HtmlEncoder();
            var expected    = string.Join(htmlEncoder.HtmlEncode(Environment.NewLine),
                                          "layout-content",
                                          "page-content");
            var page = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout      = LayoutPath;
                v.Write("page-content");
            });

            var layout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Write("layout-content" + Environment.NewLine);
                v.RenderBodyPublic();
            });
            var pageFactory = new Mock <IRazorPageFactory>();

            pageFactory.Setup(p => p.CreateInstance(LayoutPath))
            .Returns(layout);

            var viewEngine = new Mock <IRazorViewEngine>();

            viewEngine.Setup(v => v.FindPage(It.IsAny <ActionContext>(), LayoutPath))
            .Returns(new RazorPageResult(LayoutPath, layout));

            var viewStartProvider = CreateViewStartProvider();
            var view = new RazorView(viewEngine.Object,
                                     Mock.Of <IRazorPageActivator>(),
                                     viewStartProvider,
                                     page,
                                     isPartial: true);
            var viewContext = CreateViewContext(view);

            // Act
            await view.RenderAsync(viewContext);

            // Assert
            Mock.Get(viewStartProvider)
            .Verify(v => v.GetViewStartPages(It.IsAny <string>()), Times.Never());
            Assert.Equal(expected, viewContext.Writer.ToString());
        }
Exemplo n.º 12
0
        private static string GetText(Comment comment, bool trim = false)
        {
            var textComment = ((TextComment)comment);
            var text        = textComment.Text;

            if (trim)
            {
                text = text.Trim();
            }

            if (Helpers.RegexTag.IsMatch(text))
            {
                return(String.Empty);
            }

            return(HtmlEncoder.HtmlEncode(
                       text.Length > 1 && text[0] == ' ' && text[1] != ' ' ? text.Substring(1) : text));
        }
Exemplo n.º 13
0
        /// <summary>
        /// 根据ID得到一个提交错误实体
        /// </summary>
        /// <param name="id">提交ID</param>
        /// <returns>提交错误实体</returns>
        public static SolutionErrorEntity GetSolutionError(Int32 id)
        {
            if (id <= 0)
            {
                throw new InvalidRequstException(RequestType.SolutionError);
            }

            SolutionErrorEntity entity = SolutionErrorRepository.Instance.GetEntity(id);

            if (entity == null)
            {
                throw new NullResponseException(RequestType.SolutionError);
            }

            entity.ErrorInfo = HtmlEncoder.HtmlEncode(entity.ErrorInfo, 0, false, true);

            return(entity);
        }
        /// <summary>
        /// Creates an html string for displaying the details of the exception in a div.
        /// </summary>
        /// <param name="e">The exception that is being handled.</param>
        /// <param name="fileName">The relative path of the file that the exception occurred in.</param>
        /// <param name="method">The method the exception occurred in.</param>
        /// <param name="lineNumber">The line number that the exception occurred at.</param>
        /// <returns>Details of the exception formatted as html.</returns>
        private string BuildExceptionHtml(Exception e, string fileName, string method, int lineNumber)
        {
            HtmlEncoder encoder;
            string      html;

            encoder = new HtmlEncoder();

            html = "<style>" + Environment.NewLine +
                   "  .exceptiondetailmyapi td {" + Environment.NewLine +
                   "    vertical-align: top !important;" + Environment.NewLine +
                   "    padding-top: 5px !important;" + Environment.NewLine +
                   "  }" + Environment.NewLine + Environment.NewLine +
                   "  .exceptiondetailmyapi td:nth-child(1) {" + Environment.NewLine +
                   "    text-align: right; !important;" + Environment.NewLine +
                   "    font-weight: bold !important;" + Environment.NewLine +
                   "    white-space: nowrap !important;" + Environment.NewLine +
                   "    padding-right: 5px !important;" + Environment.NewLine +
                   "  }" + Environment.NewLine +
                   "</style>" + Environment.NewLine +
                   "<table class=\"exceptiondetailmyapi\"> " + Environment.NewLine +
                   "  <tr>" + Environment.NewLine +
                   "    <td>Exeception:</td>" + Environment.NewLine +
                   "    <td>" + e.Message + "</td>" + Environment.NewLine +
                   "  </tr>" + Environment.NewLine +
                   "  <tr>" + Environment.NewLine +
                   "    <td>&nbsp;</td>" + Environment.NewLine +
                   "    <td>&nbsp;</td>" + Environment.NewLine +
                   "  </tr>" + Environment.NewLine +
                   "  <tr>" + Environment.NewLine +
                   "    <td>File Name:</td>" + Environment.NewLine +
                   "    <td>" + fileName + "</td>" + Environment.NewLine +
                   "  </tr>" + Environment.NewLine +
                   "  <tr>" + Environment.NewLine +
                   "    <td>Method:</td>" + Environment.NewLine +
                   "    <td>" + encoder.HtmlEncode(method) + "</td>" + Environment.NewLine +
                   "  </tr>" + Environment.NewLine +
                   "  <tr>" + Environment.NewLine +
                   "    <td>Line Number:</td>" + Environment.NewLine +
                   "    <td>" + lineNumber.ToString() + "</td>" + Environment.NewLine +
                   "  </tr>" + Environment.NewLine +
                   "</table>";

            return(html);
        }
Exemplo n.º 15
0
        /// <summary>
        /// 根据ID得到一个题目实体
        /// </summary>
        /// <param name="id">题目ID</param>
        /// <returns>题目实体</returns>
        internal static ProblemEntity InternalGetProblemModel(Int32 id)
        {
            ProblemEntity problem = ProblemCache.GetProblemCache(id);//获取缓存

            if (problem == null)
            {
                problem = ProblemRepository.Instance.GetEntity(id);

                if (problem != null)
                {
                    problem.SampleInput  = HtmlEncoder.HtmlEncode(problem.SampleInput);
                    problem.SampleOutput = HtmlEncoder.HtmlEncode(problem.SampleOutput);

                    ProblemCache.SetProblemCache(problem);//设置缓存
                }
            }

            return(problem);
        }
Exemplo n.º 16
0
        private void BuildFallbackBlock(TagHelperContent builder)
        {
            EnsureGlobbingUrlBuilder();
            var fallbackHrefs =
                GlobbingUrlBuilder.BuildUrlList(FallbackHref, FallbackHrefInclude, FallbackHrefExclude).ToArray();

            if (fallbackHrefs.Length > 0)
            {
                if (FileVersion == true)
                {
                    for (var i = 0; i < fallbackHrefs.Length; i++)
                    {
                        // fallbackHrefs come from bound attributes and globbing. Must always be non-null.
                        Debug.Assert(fallbackHrefs[i] != null);

                        fallbackHrefs[i] = _fileVersionProvider.AddFileVersionToPath(fallbackHrefs[i]);
                    }
                }

                builder.Append(Environment.NewLine);

                // Build the <meta /> tag that's used to test for the presence of the stylesheet
                builder.Append(string.Format(
                                   CultureInfo.InvariantCulture,
                                   "<meta name=\"x-stylesheet-fallback-test\" class=\"{0}\" />",
                                   HtmlEncoder.HtmlEncode(FallbackTestClass)));

                // Build the <script /> tag that checks the effective style of <meta /> tag above and renders the extra
                // <link /> tag to load the fallback stylesheet if the test CSS property value is found to be false,
                // indicating that the primary stylesheet failed to load.
                builder
                .Append("<script>")
                .Append(string.Format(
                            CultureInfo.InvariantCulture,
                            JavaScriptResources.GetEmbeddedJavaScript(FallbackJavaScriptResourceName),
                            JavaScriptEncoder.JavaScriptStringEncode(FallbackTestProperty),
                            JavaScriptEncoder.JavaScriptStringEncode(FallbackTestValue),
                            JavaScriptStringArrayEncoder.Encode(JavaScriptEncoder, fallbackHrefs)))
                .Append("</script>");
            }
        }
Exemplo n.º 17
0
    public static void FormatComment(string docs, CodeTypeMember cmp, bool obsolete = false, string tag = "summary")
    {
        StringBuilder obsoleteMessageBuilder = new StringBuilder();

        cmp.Comments.Add(new CodeCommentStatement(string.Format("<{0}>", tag), true));
        foreach (string line in HtmlEncoder.HtmlEncode(docs).Split(Environment.NewLine.ToCharArray(), StringSplitOptions.None))
        {
            cmp.Comments.Add(new CodeCommentStatement(string.Format("<para>{0}</para>", line), true));
            if (obsolete && (line.Contains("instead") || line.Contains("deprecated")))
            {
                obsoleteMessageBuilder.Append(HtmlEncoder.HtmlDecode(line));
                obsoleteMessageBuilder.Append(' ');
            }
        }
        cmp.Comments.Add(new CodeCommentStatement(string.Format("</{0}>", tag), true));
        if (obsoleteMessageBuilder.Length > 0)
        {
            obsoleteMessageBuilder.Remove(obsoleteMessageBuilder.Length - 1, 1);
            CodeTypeReference       obsoleteAttribute = new CodeTypeReference(typeof(ObsoleteAttribute));
            CodePrimitiveExpression obsoleteMessage   = new CodePrimitiveExpression(obsoleteMessageBuilder.ToString());
            cmp.CustomAttributes.Add(new CodeAttributeDeclaration(obsoleteAttribute, new CodeAttributeArgument(obsoleteMessage)));
        }
    }
Exemplo n.º 18
0
        /// <summary>
        /// 发布新主题
        /// </summary>
        /// <param name="topic">主题实体</param>
        /// <param name="cid">竞赛ID</param>
        /// <param name="pid">题目ID</param>
        /// <param name="content">主题帖内容</param>
        /// <param name="postip">发布者IP</param>
        /// <returns>是否成功发布</returns>
        public static Boolean InsertForumTopic(ForumTopicEntity topic, String cid, String pid, String content, String postip)
        {
            if (!UserManager.IsUserLogined)
            {
                throw new UserUnLoginException();
            }

            if (String.IsNullOrEmpty(topic.Title))
            {
                throw new InvalidInputException("Topic title can not be NULL!");
            }

            if (topic.Title.Length > ForumPostRepository.TITLE_MAXLEN)
            {
                throw new InvalidInputException("Topic title is too long!");
            }

            if (!KeywordsFilterManager.IsForumPostContentLegal(topic.Title))
            {
                throw new InvalidInputException("Topic title can not contain illegal keywords!");
            }

            if (String.IsNullOrEmpty(content) || content.Length < ForumPostRepository.POST_MINLEN)
            {
                throw new InvalidInputException("Topic content is too short!");
            }

            if (content.Length > ForumPostRepository.POST_MAXLEN)
            {
                throw new InvalidInputException("Topic content is too long!");
            }

            if (!KeywordsFilterManager.IsForumPostContentLegal(content))
            {
                throw new InvalidInputException("Topic content can not contain illegal keywords!");
            }

            if (!UserSubmitStatus.CheckLastSubmitForumPostTime(UserManager.CurrentUserName))
            {
                throw new InvalidInputException(String.Format("You can not submit post more than twice in {0} seconds!", ConfigurationManager.SubmitInterval.ToString()));
            }

            topic.Type       = ForumTopicManager.GetForumTopicType(cid, pid);
            topic.RelativeID = (topic.Type == ForumTopicType.Default ? 0 : ForumTopicManager.GetRelativeID(cid, pid));

            if (topic.Type == ForumTopicType.Problem && !ProblemManager.InternalExistsProblem(topic.RelativeID))
            {
                throw new InvalidRequstException(RequestType.Problem);
            }
            else if (topic.Type == ForumTopicType.Contest && !ContestManager.InternalExistsContest(topic.RelativeID))
            {
                throw new InvalidRequstException(RequestType.Contest);
            }

            topic.UserName = UserManager.CurrentUserName;
            topic.LastDate = DateTime.Now;
            topic.Title    = HtmlEncoder.HtmlEncode(topic.Title);
            content        = HtmlEncoder.HtmlEncode(content);

            Boolean success = ForumTopicRepository.Instance.InsertEntity(topic, content, postip) > 0;

            if (success)
            {
                ForumTopicCache.IncreaseForumTopicCountCache(topic.Type, topic.RelativeID);//更新缓存

                if (topic.Type == ForumTopicType.Problem)
                {
                    ForumTopicCache.IncreaseForumTopicCountCache(ForumTopicType.Default, 0);//更新缓存
                }
            }

            return(success);
        }
Exemplo n.º 19
0
        private void GenerateSignalEvents(GeneratorOutput generatorOutput)
        {
            foreach (Block block in from template in generatorOutput.Templates
                     from block in template.FindBlocks(CSharpBlockKind.Event)
                     select block)
            {
                Event @event = (Event)block.Declaration;
                if (this.events.Contains(@event))
                {
                    block.Text.StringBuilder.Clear();
                    Class @class = (Class)@event.Namespace;

                    int           argNum          = 1;
                    StringBuilder fullNameBuilder = new StringBuilder("Action");
                    foreach (Parameter parameter in @event.Parameters)
                    {
                        argNum++;
                        if (argNum == 2)
                        {
                            fullNameBuilder.Append('<');
                        }
                        fullNameBuilder.Append(parameter.Type);
                        fullNameBuilder.Append(',');
                    }
                    if (fullNameBuilder[fullNameBuilder.Length - 1] == ',')
                    {
                        fullNameBuilder[fullNameBuilder.Length - 1] = '>';
                    }
                    string signature = string.Format("{0}({1})", @event.OriginalName,
                                                     string.Join(", ",
                                                                 from e in @event.Parameters
                                                                 select GetOriginalParameterType(e)));
                    Event existing = @class.Events.FirstOrDefault(e => e.Name == @event.Name);
                    if (existing != null && existing != @event)
                    {
                        if (@event.Parameters.Count > 0)
                        {
                            @event.Name += GetSignalEventSuffix(@event);
                        }
                        else
                        {
                            existing.Name += GetSignalEventSuffix(@event);
                        }
                    }
                    else
                    {
                        if (@event.Parameters.Count > 0 &&
                            (@class.Methods.Any(m => m.IsGenerated && m.OriginalName == @event.Name) ||
                             @class.Properties.Any(p => p.IsGenerated && p.OriginalName == @event.Name)))
                        {
                            @event.Name += GetSignalEventSuffix(@event);
                        }
                    }
                    if (@event.OriginalDeclaration.Comment != null)
                    {
                        block.WriteLine("/// <summary>");
                        foreach (string line in HtmlEncoder.HtmlEncode(@event.OriginalDeclaration.Comment.BriefText).Split(
                                     Environment.NewLine.ToCharArray()))
                        {
                            block.WriteLine("/// <para>{0}</para>", line);
                        }
                        block.WriteLine("/// </summary>");
                    }
                    block.WriteLine(string.Format(@"public event {0} {1}
{{
	add
	{{
        ConnectDynamicSlot(this, ""{2}"", value);
	}}
	remove
	{{
        DisconnectDynamicSlot(this, ""{2}"", value);
	}}
}}", fullNameBuilder, char.ToUpperInvariant(@event.Name[0]) + @event.Name.Substring(1), signature));
                }
            }
            foreach (Block block in from template in generatorOutput.Templates
                     from block in template.FindBlocks(CSharpBlockKind.Method)
                     where block.Declaration != null && block.Declaration.Name == "Qt_metacall"
                     select block)
            {
                block.Text.StringBuilder.Clear();
                block.WriteLine(@"public {0} unsafe int Qt_metacall(QMetaObject.Call call, int id, void** arguments)
{{
    var index = Internal.Qt_metacall_0({1}, call, id, arguments);

    return HandleQtMetacall(index, call, arguments);
}}", block.Declaration.Namespace.Name == "QObject" ? "virtual" : "override", Helpers.InstanceIdentifier);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// 尝试发送邮件
        /// </summary>
        /// <param name="model">邮件实体</param>
        /// <param name="error">出错信息</param>
        /// <returns>是否发送成功</returns>
        public static Boolean TrySendUserMail(UserMailEntity entity, out String error)
        {
            if (!UserManager.IsUserLogined)
            {
                error = "Please login first!";
                return(false);
            }

            if (String.IsNullOrEmpty(entity.Title))
            {
                error = "Title can not be NULL!";
                return(false);
            }

            if (entity.Title.Length > UserMailRepository.TITLE_MAXLEN)
            {
                error = "Title is too long!";
                return(false);
            }

            if (String.IsNullOrEmpty(entity.Content) || entity.Content.Length < UserMailRepository.CONTENT_MINLEN)
            {
                error = "Content is too short!";
                return(false);
            }

            if (entity.Content.Length > UserMailRepository.CONTENT_MAXLEN)
            {
                error = "Content is too long!";
                return(false);
            }

            if (String.IsNullOrEmpty(entity.ToUserName))
            {
                error = "Username can not be NULL!";
                return(false);
            }

            if (!RegexVerify.IsUserName(entity.ToUserName))
            {
                error = "Username is INVALID!";
                return(false);
            }

            if (String.Equals(ConfigurationManager.SystemAccount, entity.ToUserName, StringComparison.OrdinalIgnoreCase))
            {
                error = "You can not send mail to system account!";
                return(false);
            }

            if (String.Equals(UserManager.CurrentUserName, entity.ToUserName, StringComparison.OrdinalIgnoreCase))
            {
                error = "You can not send mail to yourself!";
                return(false);
            }

            if (!UserSubmitStatus.CheckLastSubmitUserMailTime(UserManager.CurrentUserName))
            {
                throw new InvalidInputException(String.Format("You can not submit user mail more than twice in {0} seconds!", ConfigurationManager.SubmitInterval.ToString()));
            }

            if (!UserManager.InternalExistsUser(entity.ToUserName))
            {
                error = String.Format("The username \"{0}\" doesn't exist!", entity.ToUserName);
                return(false);
            }

            entity.Title        = HtmlEncoder.HtmlEncode(entity.Title);
            entity.Content      = HtmlEncoder.HtmlEncode(entity.Content);
            entity.FromUserName = UserManager.CurrentUserName;

            if (!UserMailManager.InternalSendUserMail(entity))
            {
                error = "Failed to send your mail";
                return(false);
            }

            error = String.Empty;
            return(true);
        }
Exemplo n.º 21
0
        /// <summary>
        /// 尝试更新用户信息
        /// </summary>
        /// <param name="entity">对象实体</param>
        /// <param name="currentPassword">当前密码</param>
        /// <param name="newPassword">新密码</param>
        /// <param name="newPassword2">重复新密码</param>
        /// <param name="result">执行结果</param>
        /// <returns>执行结果</returns>
        public static IMethodResult UpdateUserInfo(UserEntity entity, String currentPassword, String newPassword, String newPassword2)
        {
            if (String.IsNullOrEmpty(currentPassword))
            {
                return(MethodResult.Failed("Current password can not be NULL!"));
            }
            else
            {
                entity.UserName = UserManager.CurrentUserName;
                entity.NickName = HtmlEncoder.HtmlEncode(entity.NickName);
                currentPassword = PassWordEncrypt.Encrypt(entity.UserName, currentPassword);
            }

            if (!String.Equals(newPassword, newPassword2))
            {
                return(MethodResult.Failed("Two new passwords are not match!"));
            }

            if (String.IsNullOrEmpty(entity.Email))
            {
                return(MethodResult.Failed("Email address can not be NULL!"));
            }

            if (!RegexVerify.IsEmail(entity.Email))
            {
                return(MethodResult.Failed("Email address is INVALID!"));
            }

            if (entity.Email.Length > UserRepository.EMAIL_MAXLEN)
            {
                return(MethodResult.Failed("Email address is too long!"));
            }

            if (!String.IsNullOrEmpty(entity.NickName) && entity.NickName.Length > UserRepository.NICKNAME_MAXLEN)
            {
                return(MethodResult.Failed("Nick Name is too long!"));
            }

            if (!KeywordsFilterManager.IsUserNameLegal(entity.NickName))
            {
                return(MethodResult.Failed("Nick Name can not contain illegal keywords!"));
            }

            if (!String.IsNullOrEmpty(entity.School) && entity.School.Length > UserRepository.SCHOOL_MAXLEN)
            {
                return(MethodResult.Failed("School Name is too long!"));
            }

            if (!String.IsNullOrEmpty(newPassword))
            {
                entity.PassWord = PassWordEncrypt.Encrypt(entity.UserName, newPassword);
            }

            try
            {
                if (UserRepository.Instance.UpdateEntityForUser(entity, currentPassword) <= 0)
                {
                    return(MethodResult.Failed("Current password is wrong!"));
                }
            }
            catch (System.Exception ex)
            {
                return(MethodResult.Failed(ex.Message));
            }

            return(MethodResult.SuccessAndLog("User update info"));
        }
Exemplo n.º 22
0
        /// <summary>
        /// 尝试注册用户
        /// </summary>
        /// <param name="entity">用户实体</param>
        /// <param name="password">密码</param>
        /// <param name="password2">重复密码</param>
        /// <param name="checkCode">验证码</param>
        /// <param name="userip">用户IP</param>
        /// <returns>执行结果</returns>
        public static IMethodResult SignUp(UserEntity entity, String password, String password2, String checkCode, String userip)
        {
            if (!CheckCodeStatus.VerifyCheckCode(checkCode))
            {
                return(MethodResult.Failed("The verification code you input didn't match the picture, Please try again!"));
            }

            if (String.IsNullOrEmpty(entity.UserName))
            {
                return(MethodResult.Failed("Username can not be NULL!"));
            }

            if (!RegexVerify.IsUserName(entity.UserName) || !SQLValidator.IsNonNullANDSafe(entity.UserName))
            {
                return(MethodResult.Failed("Username can not contain illegal characters!"));
            }

            if (!KeywordsFilterManager.IsUserNameLegal(entity.UserName))
            {
                return(MethodResult.Failed("Username can not contain illegal keywords!"));
            }

            if (entity.UserName.Length > UserRepository.USERNAME_MAXLEN)
            {
                return(MethodResult.Failed("Username is too long!"));
            }

            if (String.IsNullOrEmpty(password))
            {
                return(MethodResult.Failed("Password can not be NULL!"));
            }

            if (!String.Equals(password, password2))
            {
                return(MethodResult.Failed("Two passwords are not match!"));
            }

            if (String.IsNullOrEmpty(entity.Email))
            {
                return(MethodResult.Failed("Email address can not be NULL!"));
            }

            if (!RegexVerify.IsEmail(entity.Email))
            {
                return(MethodResult.Failed("Email address is INVALID!"));
            }

            if (entity.Email.Length > UserRepository.EMAIL_MAXLEN)
            {
                return(MethodResult.Failed("Email address is too long!"));
            }

            if (!String.IsNullOrEmpty(entity.NickName) && entity.NickName.Length > UserRepository.NICKNAME_MAXLEN)
            {
                return(MethodResult.Failed("Nick Name is too long!"));
            }

            if (!KeywordsFilterManager.IsUserNameLegal(entity.NickName))
            {
                return(MethodResult.Failed("Nick Name can not contain illegal keywords!"));
            }

            if (!String.IsNullOrEmpty(entity.School) && entity.School.Length > UserRepository.SCHOOL_MAXLEN)
            {
                return(MethodResult.Failed("School Name is too long!"));
            }

            if (UserRepository.Instance.ExistsEntity(entity.UserName))
            {
                return(MethodResult.Failed("The username \"{0}\" has already existed!", entity.UserName));
            }

            if (!UserIPStatus.CheckLastRegisterTime(userip))
            {
                return(MethodResult.Failed("You can only register one user from single ip in {0} seconds!", ConfigurationManager.RegisterInterval.ToString()));
            }

            entity.PassWord   = PassWordEncrypt.Encrypt(entity.UserName, password);
            entity.NickName   = HtmlEncoder.HtmlEncode(entity.NickName);
            entity.Permission = PermissionType.None;
            entity.CreateIP   = userip;
            entity.CreateDate = DateTime.Now;

            try
            {
                if (UserRepository.Instance.InsertEntity(entity) == 0)
                {
                    return(MethodResult.Failed("User Registration Failed!"));
                }
            }
            catch (System.Exception ex)
            {
                return(MethodResult.Failed(ex.Message));
            }

            UserCache.RemoveRanklistUserCountCache();//删除缓存

            return(MethodResult.SuccessAndLog("User sign up"));
        }
Exemplo n.º 23
0
        public async Task RenderAsync_ExecutesLayoutPages()
        {
            // Arrange
            var htmlEncoder        = new HtmlEncoder();
            var htmlEncodedNewLine = htmlEncoder.HtmlEncode(Environment.NewLine);
            var expected           = "layout-content" +
                                     htmlEncodedNewLine +
                                     "head-content" +
                                     htmlEncodedNewLine +
                                     "body-content" +
                                     htmlEncodedNewLine +
                                     "foot-content";

            var page = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.WriteLiteral("body-content");
                v.Layout = LayoutPath;
                v.DefineSection("head", async writer =>
                {
                    await writer.WriteAsync("head-content");
                });
                v.DefineSection("foot", async writer =>
                {
                    await writer.WriteAsync("foot-content");
                });
            });
            var layout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Write("layout-content" + Environment.NewLine);
                v.Write(v.RenderSection("head"));
                v.Write(Environment.NewLine);
                v.RenderBodyPublic();
                v.Write(Environment.NewLine);
                v.Write(v.RenderSection("foot"));
            });
            var activator = new Mock <IRazorPageActivator>();

            activator.Setup(a => a.Activate(page, It.IsAny <ViewContext>()))
            .Verifiable();
            activator.Setup(a => a.Activate(layout, It.IsAny <ViewContext>()))
            .Verifiable();
            var viewEngine = new Mock <IRazorViewEngine>();

            var view = new RazorView(viewEngine.Object,
                                     activator.Object,
                                     CreateViewStartProvider(),
                                     page,
                                     isPartial: false);
            var viewContext = CreateViewContext(view);

            viewEngine.Setup(p => p.FindPage(viewContext, LayoutPath))
            .Returns(new RazorPageResult(LayoutPath, layout))
            .Verifiable();

            // Act
            await view.RenderAsync(viewContext);

            // Assert
            // Verify the activator was invoked for the primary page and layout page.
            activator.Verify();
            Assert.Equal(expected, viewContext.Writer.ToString());
            viewEngine.Verify();
        }
Exemplo n.º 24
0
        public async Task RenderAsync_ExecutesNestedLayoutsWithNestedSections()
        {
            // Arrange
            var htmlEncoder        = new HtmlEncoder();
            var htmlEncodedNewLine = htmlEncoder.HtmlEncode(Environment.NewLine);
            var expected           = "BaseLayout" +
                                     htmlEncodedNewLine +
                                     "NestedLayout" +
                                     htmlEncodedNewLine +
                                     "BodyContent" +
                                     "foo-content" +
                                     Environment.NewLine +
                                     Environment.NewLine;

            var page = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout      = "~/Shared/Layout1.cshtml";
                v.WriteLiteral("BodyContent");
                v.DefineSection("foo", async writer =>
                {
                    await writer.WriteLineAsync("foo-content");
                });
            });
            var nestedLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout      = "~/Shared/Layout2.cshtml";
                v.Write("NestedLayout" + Environment.NewLine);
                v.RenderBodyPublic();
                v.DefineSection("foo", async writer =>
                {
                    await writer.WriteLineAsync(htmlEncoder.HtmlEncode(v.RenderSection("foo").ToString()));
                });
            });
            var baseLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Write("BaseLayout" + Environment.NewLine);
                v.RenderBodyPublic();
                v.Write(v.RenderSection("foo"));
            });
            var viewEngine = new Mock <IRazorViewEngine>();

            viewEngine.Setup(p => p.FindPage(It.IsAny <ActionContext>(), "~/Shared/Layout1.cshtml"))
            .Returns(new RazorPageResult("~/Shared/Layout1.cshtml", nestedLayout));
            viewEngine.Setup(p => p.FindPage(It.IsAny <ActionContext>(), "~/Shared/Layout2.cshtml"))
            .Returns(new RazorPageResult("~/Shared/Layout2.cshtml", baseLayout));

            var view = new RazorView(viewEngine.Object,
                                     Mock.Of <IRazorPageActivator>(),
                                     CreateViewStartProvider(),
                                     page,
                                     isPartial: false);
            var viewContext = CreateViewContext(view);

            // Act
            await view.RenderAsync(viewContext);

            // Assert
            Assert.Equal(expected, viewContext.Writer.ToString());
        }
Exemplo n.º 25
0
        private void GenerateSignalEvents(GeneratorOutput generatorOutput)
        {
            foreach (var block in from output in generatorOutput.Outputs
                     from block in output.FindBlocks(BlockKind.Event)
                     select block)
            {
                Event @event = (Event)block.Object;
                if (this.events.Contains(@event))
                {
                    block.Text.StringBuilder.Clear();
                    Class @class = (Class)@event.Namespace;

                    int           argNum          = 1;
                    StringBuilder fullNameBuilder = new StringBuilder("global::System.Action");
                    foreach (Parameter parameter in @event.Parameters)
                    {
                        argNum++;
                        if (argNum == 2)
                        {
                            fullNameBuilder.Append('<');
                        }
                        fullNameBuilder.Append(parameter.Type);
                        fullNameBuilder.Append(',');
                    }
                    if (fullNameBuilder[fullNameBuilder.Length - 1] == ',')
                    {
                        fullNameBuilder[fullNameBuilder.Length - 1] = '>';
                    }
                    string signature = string.Format("{0}({1})", @event.OriginalName,
                                                     string.Join(", ",
                                                                 from e in @event.Parameters
                                                                 select GetOriginalParameterType(e)));
                    Event existing = @class.Events.FirstOrDefault(e => e.Name == @event.Name);
                    if (existing != null && existing != @event)
                    {
                        if (@event.Parameters.Count > 0)
                        {
                            @event.Name += GetSignalEventSuffix(@event);
                        }
                        else
                        {
                            existing.Name += GetSignalEventSuffix(@event);
                        }
                    }
                    else
                    {
                        if (@event.Parameters.Count > 0 &&
                            (@class.Methods.Any(m => m.IsGenerated && m.OriginalName == @event.Name) ||
                             @class.Properties.Any(p => p.IsGenerated && p.OriginalName == @event.Name)))
                        {
                            @event.Name += GetSignalEventSuffix(@event);
                        }
                    }
                    if (@event.OriginalDeclaration.Comment != null)
                    {
                        block.WriteLine("/// <summary>");
                        foreach (string line in HtmlEncoder.HtmlEncode(@event.OriginalDeclaration.Comment.BriefText).Split(
                                     Environment.NewLine.ToCharArray()))
                        {
                            block.WriteLine("/// <para>{0}</para>", line);
                        }
                        block.WriteLine("/// </summary>");
                    }
                    var finalName = char.ToUpperInvariant(@event.Name[0]) + @event.Name.Substring(1);
                    if (@event.Namespace.Declarations.Exists(d => d != @event && d.Name == finalName))
                    {
                        finalName += "Signal";
                    }
                    block.WriteLine(string.Format(@"public event {0} {1}
{{
	add
	{{
        ConnectDynamicSlot(this, ""{2}"", value);
	}}
	remove
	{{
        DisconnectDynamicSlot(this, ""{2}"", value);
	}}
}}", fullNameBuilder, finalName, signature));
                }
            }
            var qtMetacall = (from output in generatorOutput.Outputs
                              from block in output.FindBlocks(BlockKind.Method)
                              let declaration = block.Object as Declaration
                                                where declaration != null && declaration.Name == "QtMetacall" &&
                                                declaration.Namespace.Name == "QObject"
                                                select block).FirstOrDefault();

            if (qtMetacall != null)
            {
                qtMetacall.Text.StringBuilder.Replace("return __ret;", "return HandleQtMetacall(__ret, _0, _2);");
            }
        }
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            error_p        = false;
            body           = "";
            redirect       = "";
            requiredFields = "";
            splitFields    = "";
            foreach (string key in context.Request.Form.AllKeys)
            {
                switch (key)
                {
                case "submit.x": break;     // ignore

                case "submit.y": break;     // ignore

                case "__from":
                    from = context.Request.Params[key];
                    if (!EmailSyntaxValidator.Valid(from, true))
                    {
                        errorList.Add("Error: from email '" + from + "' is invalid. Please go back and enter a valid email address.");
                        error_p = true;
                    }
                    break;

                case "__subject": subject = context.Request.Params[key]; break;

                case "__recipient":
                    to = ConfigurationManager.AppSettings[context.Request.Params[key]];
                    if ((to == null) || (to == ""))
                    {
                        errorList.Add("Error: recipient '" + context.Request.Params[key] + "' is not configured.");
                        error_p = true;
                    }
                    break;

                case "__redirectto": redirect = context.Request.Params[key]; break;

                case "__requiredfields": requiredFields = context.Request.Params[key].Trim().Replace(" ", ""); break;

                case "__splitFields": splitFields = "," + context.Request.Params[key].Replace(" ", "") + ","; break;

                // Recaptcha fields
                case "g-recaptcha-response": recaptchaResponseField = context.Request.Form[key]; break;

                default:
                    if (key.StartsWith("__linebreak"))
                    {
                        body += "\n";
                    }
                    else
                    {
                        if (!key.StartsWith("__"))
                        {     // only send "real" fields
                            if (splitFields.IndexOf(key) == -1)
                            {
                                body += key.Replace("_", " ") + ": " + context.Request.Params[key] + "\n";
                            }
                            else
                            {
                                // split the field into multiple lines
                                body += key.Replace("_", " ") + ": \n\t\t" + context.Server.UrlDecode(context.Request.Params[key].Replace(",", "\n\t\t")) + "\n";
                            }
                        }
                    }
                    break;
                }
            }

            if (requiredFields != "")
            {
                foreach (string field in requiredFields.Split(','))
                {
                    if ((context.Request.Params[field] == null) || (context.Request.Params[field].Trim() == ""))
                    {
                        errorList.Add("Required field missing: " + field);
                        error_p = true;
                    }
                }
            }

            // Verify captcha was submitted, and is valid
            ReCaptchaValidator captcha = ValidateCaptcha(recaptchaResponseField, context.Request.UserHostAddress);

            if (!captcha.Success)
            {
                if (captcha.ErrorCodes == null)
                {
                    errorList.Add("reCAPTCHA check not completed!");
                }
                else
                {
                    errorList.AddRange(captcha.ErrorCodes);
                }
                error_p = true;
            }

            if (!error_p)
            {
                try
                {
                    SendEmail();
                }
                catch (Exception exception)
                {
                    errorList.Add("Error: " + exception.Message);
                    error_p = true;
                }

                if (!error_p && redirect != null)
                {
                    context.Response.Redirect(redirect);
                }
            }

            if (error_p)
            {
                Content = string.Empty;
                errorList.ForEach(entry => {
                    Content += HtmlEncoder.HtmlEncode(entry) + "<br>\n";
                });

                context.Response.Write(Content);
            }
        }
Exemplo n.º 27
0
        private void OnUnitGenerated(GeneratorOutput generatorOutput)
        {
            foreach (Block block in from template in generatorOutput.Templates
                     from block in template.FindBlocks(CSharpBlockKind.Event)
                     select block)
            {
                Event @event = (Event)block.Declaration;
                if (this.events.Contains(@event))
                {
                    block.Text.StringBuilder.Clear();
                    Class @class = (Class)@event.Namespace;
                    if (!this.addedEventHandlers && @class.Name == "QObject")
                    {
                        block.WriteLine("protected readonly System.Collections.Generic.List<QEventHandler> " +
                                        "eventFilters = new System.Collections.Generic.List<QEventHandler>();");
                        block.NewLine();
                        this.addedEventHandlers = true;
                    }
                    bool isQAbstractScrollArea = @class.Name != "QAbstractScrollArea";
                    if (@event.OriginalDeclaration.Comment != null)
                    {
                        block.WriteLine("/// <summary>");
                        foreach (string line in HtmlEncoder.HtmlEncode(@event.OriginalDeclaration.Comment.BriefText).Split(
                                     Environment.NewLine.ToCharArray()))
                        {
                            block.WriteLine("/// <para>{0}</para>", line);
                        }
                        block.WriteLine("/// </summary>");
                    }
                    block.WriteLine(@"public {0} event EventHandler<QEventArgs<{1}>> {2}
{{
	add
	{{
		QEventArgs<{1}> qEventArgs = new QEventArgs<{1}>(new System.Collections.Generic.List<QEvent.Type> {{ {3} }});
		QEventHandler<{1}> qEventHandler = new QEventHandler<{1}>(this{4}, qEventArgs, value);
        foreach (QEventHandler eventFilter in eventFilters)
        {{
            this{4}.RemoveEventFilter(eventFilter);
        }}
		eventFilters.Add(qEventHandler);
        for (int i = eventFilters.Count - 1; i >= 0; i--)
        {{
		    this{4}.InstallEventFilter(eventFilters[i]);                    
        }}
	}}
	remove
	{{
		for (int i = eventFilters.Count - 1; i >= 0; i--)
		{{
			QEventHandler eventFilter = eventFilters[i];
			if (eventFilter.Handler == value)
			{{
				this{4}.RemoveEventFilter(eventFilter);
				eventFilters.RemoveAt(i);
                break;
			}}
		}}
	}}
}}",
                                    isQAbstractScrollArea ? "virtual" : "override", @event.Parameters[0].Type, @event.Name,
                                    this.GetEventTypes(@event), isQAbstractScrollArea ? string.Empty : ".Viewport");
                }
            }
        }
Exemplo n.º 28
0
 /// <summary>
 /// Writes the specified <paramref name="value"/> with HTML encoding to <paramref name="writer"/>.
 /// </summary>
 /// <param name="writer">The <see cref="TextWriter"/> instance to write to.</param>
 /// <param name="value">The <see cref="string"/> to write.</param>
 protected void WriteTo(TextWriter writer, string value)
 {
     WriteLiteralTo(writer, HtmlEncoder.HtmlEncode(value));
 }
Exemplo n.º 29
0
        /// <summary>
        /// 增加一条回帖
        /// </summary>
        /// <param name="post">帖子实体</param>
        /// <param name="topic">主题实体</param>
        /// <param name="parentPost">回复的帖子实体</param>
        /// <param name="postip">发布者IP</param>
        /// <param name="link">当前页面地址</param>
        /// <returns>是否成功增加</returns>
        public static Boolean InsertForumPost(ForumPostEntity post, ForumTopicEntity topic, ForumPostEntity parentPost, String postip, String link)
        {
            if (!UserManager.IsUserLogined)
            {
                throw new UserUnLoginException();
            }

            if (String.IsNullOrEmpty(post.Title))
            {
                throw new InvalidInputException("Reply title can not be NULL!");
            }

            if (post.Title.Length > ForumPostRepository.TITLE_MAXLEN)
            {
                throw new InvalidInputException("Reply title is too long!");
            }

            if (!KeywordsFilterManager.IsForumPostContentLegal(post.Title))
            {
                throw new InvalidInputException("Reply title can not contain illegal keywords!");
            }

            if (String.IsNullOrEmpty(post.Content) || post.Content.Length < ForumPostRepository.POST_MINLEN)
            {
                throw new InvalidInputException("Reply content is too short!");
            }

            if (post.Content.Length > ForumPostRepository.POST_MAXLEN)
            {
                throw new InvalidInputException("Reply content is too long!");
            }

            if (!KeywordsFilterManager.IsForumPostContentLegal(post.Content))
            {
                throw new InvalidInputException("Reply content can not contain illegal keywords!");
            }

            if (parentPost.Deepth + 1 < ForumPostRepository.DEEPTH_MIN)
            {
                throw new InvalidInputException("Reply deepth is INVALID!");
            }

            if (parentPost.Deepth + 1 > ForumPostRepository.DEEPTH_MAX)
            {
                throw new InvalidInputException("Reply deepth is too deep!");
            }

            if (topic.IsLocked)
            {
                throw new NoPermissionException("You have no privilege to reply the post!");
            }

            if (!UserSubmitStatus.CheckLastSubmitForumPostTime(UserManager.CurrentUserName))
            {
                throw new InvalidInputException(String.Format("You can not submit post more than twice in {0} seconds!", ConfigurationManager.SubmitInterval.ToString()));
            }

            post.TopicID      = parentPost.TopicID;
            post.Title        = HtmlEncoder.HtmlEncode(post.Title);
            post.Content      = HtmlEncoder.HtmlEncode(post.Content);
            post.UserName     = UserManager.CurrentUserName;
            post.Deepth       = parentPost.Deepth + 1;
            post.ParentPostID = parentPost.PostID;
            post.PostDate     = DateTime.Now;
            post.PostIP       = postip;

            Boolean success = ForumPostRepository.Instance.InsertEntity(post) > 0;

            if (success && !String.Equals(parentPost.UserName, post.UserName))
            {
                if (ConfigurationManager.ReplyPostMailNotification)
                {
                    try
                    {
                        UserMailEntity mail = new UserMailEntity();
                        String         url  = ConfigurationManager.DomainUrl + ((link[0] == '/') ? link.Substring(1) : link);

                        mail.FromUserName = ConfigurationManager.SystemAccount;
                        mail.ToUserName   = parentPost.UserName;
                        mail.Title        = "Your post has new reply!";
                        mail.Content      =
                            String.Format("Your post \"{0}\" has new reply, <br/>", parentPost.Title) +
                            String.Format("Please visit <a href=\"{0}\" target=\"_blank\">{0}</a>", url);

                        UserMailManager.InternalSendUserMail(mail);
                    }
                    catch { }
                }
            }

            return(success);
        }