private void ParseAttributes(string content, ref int pos) { if (pos >= content.Length) { return; } char attributeEndChar = HtmlStringHelper.GetAttributeTerminatingChar(content[pos]); if (attributeEndChar != '\0') { string attributes = HtmlStringHelper.ExtractTokenFromTagString(content, ref pos, new[] { attributeEndChar }); if (attributes[attributes.Length - 1] != attributeEndChar) { throw new HamlMalformedTagException( "Malformed HTML Attributes collection \"" + attributes + "\".", SourceFileLineNum); } var attribCollection = new HamlNodeHtmlAttributeCollection(SourceFileLineNum, attributes); foreach (var attribute in attribCollection.Children.OfType <HamlNodeHtmlAttribute>().OrderBy(n => n.Name)) { _attributes.Add(attribute); } pos++; } }
public void ExtractHeadFromHtmlStringShallReturnOnlyATheHeadTagFromAHtmlBlob() { //Small file test //Setup const string headTagHtml1 = "<head><script something blah blah /></head>"; const string htmlString1 = "<html>" + headTagHtml1 + "</html>"; //Exercise var result1 = HtmlStringHelper.ExtractHeadFromHtmlString(htmlString1); //Verify Assert.AreEqual(headTagHtml1, result1); //Large file test //Setup string htmlString2 = GetLiveTestHtml(); //Exercise var result2 = HtmlStringHelper.ExtractHeadFromHtmlString(htmlString2); //Verify Assert.IsTrue(result2.Contains("text-decoration: none; color: purple}")); }
public void ListCiteElementNotFoundTest() { var htmlHelper = new HtmlStringHelper(); var result = htmlHelper.ListCiteElement(""); // Assert Assert.IsNotNull(result); Assert.IsTrue(result.Count == 0); }
public void ListCiteElementTest() { var htmlHelper = new HtmlStringHelper(); var result = htmlHelper.ListCiteElement(GetHtmlStringData()); // Assert Assert.IsNotNull(result); Assert.IsTrue(result.Count == 3); }
public void FormatSearchResultNotFoundTest() { var htmlHelper = new HtmlStringHelper(); var targetSite = "test.com.au"; var result = htmlHelper.FormatSearchResult(ListCiteElementData(), targetSite); // Assert Assert.IsNotNull(result); Assert.IsTrue(string.Equals(result, "0")); }
public JsonResult Search(string keyword, string searchEngineSite, string targetSite, int noFirstResult = 100) { var googleProvider = new HtmlStringGoogleProvider(); var htmlStringHelper = new HtmlStringHelper(); var googleService = new HtmlStringGoogleService(googleProvider, htmlStringHelper); var searchEngineUrl = "https://www.google.com.au/search"; var googleResult = googleService.Search(keyword, searchEngineUrl, targetSite, noFirstResult); return(Json(googleResult, JsonRequestBehavior.AllowGet)); }
private void ParseName(ref int index) { string result = HtmlStringHelper.ExtractTokenFromTagString(Content, ref index, new[] { '=', '\0' }); if (string.IsNullOrEmpty(result)) { throw new HamlMalformedTagException("Malformed HTML attribute \"" + Content + "\"", SourceFileLineNum); } _name = result.TrimEnd('='); }
private static string ParseName(ref int index, string content, int lineNumber) { string result = HtmlStringHelper.ExtractTokenFromTagString(content, ref index, new[] { ':', '\0' }); if (string.IsNullOrEmpty(result)) { throw new HamlMalformedTagException("Malformed HTML attribute \"" + content + "\"", lineNumber); } return(result.TrimEnd(':').TrimStart(' ')); }
private static string GetNextAttributeToken(string attributeCollection, char closingBracketChar, ref int index) { var terminatingChars = new[] { ',', ' ', '\t', closingBracketChar }; string nameValuePair = HtmlStringHelper.ExtractTokenFromTagString(attributeCollection, ref index, terminatingChars); if (terminatingChars.Contains(nameValuePair[nameValuePair.Length - 1])) { nameValuePair = nameValuePair.Substring(0, nameValuePair.Length - 1); } return(nameValuePair); }
public void GivenWebPageContentExpectCorrectUrlsAreExtracted() { //Arrange const string SomeRandomWebPageContent = "<!doctype html><html><span class=\"Z98Wse\">Ad</span><cite>https://www.infotrack.com.au/Property_<b>Search</b></cite><span class=\"CiacGf\"></span><cite>www.saiglobal.com/<b>title</b>-<b>search</b></cite></div><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td valign=\"top\"></html>"; //Act List <string> urls = HtmlStringHelper.ExtractUrlsFromWebPageContent(SomeRandomWebPageContent); //Assert Assert.AreEqual("https://www.infotrack.com.au/Property_Search", urls[0]); Assert.AreEqual("www.saiglobal.com/title-search", urls[1]); }
private string GetHtmlToken(string content, ref int pos) { int startIndex = pos; while (pos < content.Length) { if (HtmlStringHelper.IsHtmlIdentifierChar(content[pos])) { pos++; } else { break; } } return(content.Substring(startIndex, pos - startIndex)); }
public bool ValidateInput(string input, int min, int max) { // count array var wordCount = HtmlStringHelper.GetWordCount(input); // validate count if (wordCount > max) { Error = "Error: The words has exceeded " + max + " words"; return(false); } else if (wordCount <= min) { Error = "Error: There must me a minimum of " + min + " words"; return(false); } return(true); }
private void ParseAttributes(string content, ref int pos) { if (pos >= content.Length) { return; } char attributeEndChar = HtmlStringHelper.GetAttributeTerminatingChar(content[pos]); if (attributeEndChar != '\0') { string attributes = HtmlStringHelper.ExtractTokenFromTagString(content, ref pos, new[] { attributeEndChar }); if (attributes[attributes.Length - 1] != attributeEndChar) { throw new HamlMalformedTagException( "Malformed HTML Attributes collection \"" + attributes + "\".", SourceFileLineNum); } AddChild(new HamlNodeHtmlAttributeCollection(SourceFileLineNum, attributes)); pos++; } }
public HttpResponseMessage Export(string id) { string tmplCode = Request.RequestUri.ParseQueryString().Get("tmplCode"); if (string.IsNullOrEmpty(tmplCode)) { throw new Exception("缺少参数TmplCode"); } SQLHelper sqlHeper = SQLHelper.CreateSqlHelper(ConnEnum.Base); var dtWordTmpl = sqlHeper.ExecuteDataTable(string.Format("select * from S_UI_Word where Code='{0}'", tmplCode)); if (dtWordTmpl.Rows.Count == 0) { throw new Exception("Word导出定义不存在"); } if (string.IsNullOrEmpty(id)) { throw new Exception("缺少参数ID"); } //string tmplName = dtWordTmpl.Rows[0]["Code"].ToString() + ".docx"; ////var path = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'); ////string tempPath = path.Substring(0, path.LastIndexOf('\\') + 1) + "WordTemplate/" + tmplName;// Server.MapPath("/") + //string tempPath = System.Web.HttpContext.Current.Server.MapPath("/") + "WordTemplate/" + tmplName; //word历史版本功能 UIFO uiFO = FormulaHelper.CreateFO <UIFO>(); DataSet ds = uiFO.GetWordDataSource(tmplCode, id, false);//客户端转图访问时,没有当前用户,防止报错 DataRow wordTmplRow = dtWordTmpl.Rows[0]; DateTime date; if (ds.Tables[0].Columns.Contains("CreateTime")) { date = DateTime.Parse(ds.Tables[0].Rows[0]["CreateTime"].ToString()); } else { date = DateTime.Parse(ds.Tables[0].Rows[0]["CreateDate"].ToString()); } foreach (DataRow row in dtWordTmpl.Rows) { var _startDate = DateTime.Parse(row["VersionStartDate"].ToString()); var _endDate = DateTime.MaxValue; if (row["VersionEndDate"].ToString() != "") { _endDate = DateTime.Parse(row["VersionEndDate"].ToString()); } if (date > _startDate && date < _endDate) { wordTmplRow = row; break; } } int?versionNum = 1; if (wordTmplRow["VersionNum"].ToString() != "") { versionNum = int.Parse(wordTmplRow["VersionNum"].ToString()); } string tempPath = HttpContext.Current.Server.MapPath("/") + "WordTemplate/" + wordTmplRow["Code"].ToString() + "_" + versionNum + ".docx"; //兼容以前没有版本时 if (System.IO.File.Exists(tempPath) == false) { tempPath = HttpContext.Current.Server.MapPath("/") + "WordTemplate/" + wordTmplRow["Code"].ToString() + ".docx"; } AsposeWordExporter export = new AsposeWordExporter(); byte[] bytesArray = export.ExportWord(ds, tempPath, delegate(FieldMergingArgs e) { string strValues = e.FieldValue == null?"":e.FieldValue.ToString(); if (HtmlStringHelper.CheckHtml(strValues)) { DocumentBuilder builder = new DocumentBuilder(e.Document); builder.MoveToMergeField(e.FieldName); builder.InsertHtml(strValues); } }); string fileName = dtWordTmpl.Rows[0]["Name"].ToString(); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(bytesArray); result.Content.Headers.ContentLength = bytesArray.Length; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = fileName; return(result); }
private void handlePaste( PasteMode pasteMode) { if (Document != null) { var doc = (HTMLDocument)Document.DomDocument; if (IsControlSelection) { doc.execCommand(@"Delete", false, null); } string html; if (Clipboard.ContainsImage() && // 2014-08-19, Uwe Keim: Excel hat HTML _und_ Bild, deshalb hier prüfen, sonst // wird Excel auch als Bild eingefügt. !Clipboard.ContainsText(TextDataFormat.Html)) { var image = Clipboard.GetImage(); var file = Path.Combine(_tmpFolderPath, _objectID.ToString(CultureInfo.InvariantCulture)); if (image != null) { image.Save(file, image.RawFormat); } _objectID++; if (Configuration.AllowEmbeddedImages) { var data = File.ReadAllBytes(file); var imageContent = Convert.ToBase64String(data, 0, data.Length); File.Delete(file); html = string.Format(@"<img src=""data:image;base64,{0}"" />", imageContent); } else { html = string.Format(@"<img src=""{0}"" id=""Img{1}"" />", file, DateTime.Now.Ticks); } } else { if (pasteMode != PasteMode.Text && Clipboard.ContainsText(TextDataFormat.Html)) { // only body from fragment html = HtmlClipboardHelper.GetHtmlFromClipboard().GetBodyFromHtmlCode().CheckCompleteHtmlTable(); // images save or load from web html = checkImages( HtmlConversionHelper.FindImgs(html), html, HtmlClipboardHelper.GetSourceUrlFromClipboard()); if (pasteMode == PasteMode.MsWord) { html = html.CleanMsWordHtml(); } } else if (Clipboard.ContainsText(TextDataFormat.UnicodeText)) { html = Clipboard.GetText(TextDataFormat.UnicodeText); if (pasteMode == PasteMode.Text) { html = html.GetOnlyTextFromHtmlCode(); } html = PathHelper.HtmlEncode(html); html = HtmlStringHelper.AddNewLineToText(html); } else if (Clipboard.ContainsText(TextDataFormat.Text)) { html = Clipboard.GetText(TextDataFormat.Text); if (pasteMode == PasteMode.Text) { html = html.GetOnlyTextFromHtmlCode(); } html = PathHelper.HtmlEncode(html); html = HtmlStringHelper.AddNewLineToText(html); } else { html = string.Empty; } } var selection = doc.selection; var range = (IHTMLTxtRange)selection.createRange(); range.pasteHTML(html); } }
public FileResult Export(string tmplCode, string id) { if (string.IsNullOrEmpty(tmplCode)) { throw new Exception("缺少参数TmplCode"); } SQLHelper sqlHeper = SQLHelper.CreateSqlHelper(ConnEnum.Base); var dtWordTmpl = sqlHeper.ExecuteDataTable(string.Format("select TOP 1 * from S_UI_Word where Code='{0}' ORDER BY VersionNum DESC", tmplCode)); if (dtWordTmpl.Rows.Count == 0) { throw new Exception("Word导出定义不存在"); } #region 预览时的自动ID if (Request["TopID"] == "true" && string.IsNullOrEmpty(id)) { SQLHelper sqlHelperWord = SQLHelper.CreateSqlHelper(dtWordTmpl.Rows[0]["ConnName"].ToString()); string sql = string.Format("select top 1 ID from ({0}) a", dtWordTmpl.Rows[0]["SQL"]); if (Config.Constant.IsOracleDb) { sql = string.Format("select ID from({0}) a where rownum=1", dtWordTmpl.Rows[0]["SQL"]); } try { var obj = sqlHelperWord.ExecuteScalar(sql); if (obj != null) { id = obj.ToString(); } } catch { // Response.Write("SQL错误,或者表不存在!"); Response.Redirect("/MvcConfig/Error.html?errMsg=SQL错误,或者表不存在!"); Response.End(); return(null); } if (string.IsNullOrEmpty(id)) { Response.Write("表中没有数据,无法导出Word。"); Response.End(); return(null); } } #endregion if (string.IsNullOrEmpty(id)) { throw new Exception("缺少参数ID"); } //string tmplName = dtWordTmpl.Rows[0]["Code"].ToString() + ".docx"; //string tempPath = Server.MapPath("/") + "WordTemplate/" + tmplName; UIFO uiFO = FormulaHelper.CreateFO <UIFO>(); DataSet ds = uiFO.GetWordDataSource(tmplCode, id); DataRow wordTmplRow = dtWordTmpl.Rows[0]; DateTime date; if (ds.Tables[0].Columns.Contains("CreateTime")) { date = DateTime.Parse(ds.Tables[0].Rows[0]["CreateTime"].ToString()); } else { date = DateTime.Parse(ds.Tables[0].Rows[0]["CreateDate"].ToString()); } foreach (DataRow row in dtWordTmpl.Rows) { var _startDate = DateTime.Parse(row["VersionStartDate"].ToString()); var _endDate = DateTime.MaxValue; if (row["VersionEndDate"].ToString() != "") { _endDate = DateTime.Parse(row["VersionEndDate"].ToString()); } if (date > _startDate && date < _endDate) { wordTmplRow = row; break; } } int?versionNum = 1; if (wordTmplRow["VersionNum"].ToString() != "") { versionNum = int.Parse(wordTmplRow["VersionNum"].ToString()); } string tempPath = HttpContext.Server.MapPath("/") + "WordTemplate/" + wordTmplRow["Code"].ToString() + "_" + versionNum + ".docx"; //兼容以前没有版本时 if (System.IO.File.Exists(tempPath) == false) { tempPath = HttpContext.Server.MapPath("/") + "WordTemplate/" + wordTmplRow["Code"].ToString() + ".docx"; } AsposeWordExporter export = new AsposeWordExporter(); byte[] result = null; if (Request["pdf"] == "true") { result = export.ExportPDF(ds, tempPath, delegate(FieldMergingArgs e) { if (e.FieldValue != null) { string strValues = e.FieldValue.ToString(); if (HtmlStringHelper.CheckHtml(strValues)) { DocumentBuilder builder = new DocumentBuilder(e.Document); builder.MoveToMergeField(e.FieldName); builder.InsertHtml(strValues); } } }); } else { result = export.ExportWord(ds, tempPath, delegate(FieldMergingArgs e) { if (e.FieldValue != null) { string strValues = e.FieldValue.ToString(); if (HtmlStringHelper.CheckHtml(strValues)) { DocumentBuilder builder = new DocumentBuilder(e.Document); builder.MoveToMergeField(e.FieldName); builder.InsertHtml(strValues); } } }); } MemoryStream docStream = new MemoryStream(result); string realFileName = dtWordTmpl.Rows[0]["Name"].ToString(); if (wordTmplRow["WordNameTmpl"].ToString() != "") { realFileName = uiFO.ReplaceString(wordTmplRow["WordNameTmpl"].ToString(), ds.Tables[0].Rows[0]); } if (!String.IsNullOrEmpty(Request["filename"])) { realFileName = Request["filename"]; } var explorerName = HttpContext.Request.Browser.Browser.ToUpper(); if (explorerName == "IE" || explorerName == "INTERNETEXPLORER" || HttpContext.Request.UserAgent.ToString().IndexOf("rv:11") > 0) { realFileName = HttpUtility.UrlEncode(realFileName, System.Text.Encoding.UTF8); realFileName = realFileName.Replace("+", "%20"); } if (Request["pdf"] == "true") { return(base.File(docStream.ToArray(), "application/pdf", realFileName + ".pdf")); } else { return(base.File(docStream.ToArray(), "application/msword", realFileName + ".doc")); } }